Format string checking for logger().
[tinc] / src / net_packet.c
1 /*
2     net_packet.c -- Handles in- and outgoing VPN packets
3     Copyright (C) 1998-2003 Ivo Timmermans <ivo@o2w.nl>,
4                   2000-2003 Guus Sliepen <guus@sliepen.eu.org>
5
6     This program is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     This program is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with this program; if not, write to the Free Software
18     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19
20     $Id: net_packet.c,v 1.1.2.33 2003/07/12 17:41:46 guus Exp $
21 */
22
23 #include "config.h"
24
25 #include <errno.h>
26 #include <fcntl.h>
27 #include <netdb.h>
28 #include <netinet/in.h>
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <signal.h>
33 #include <sys/time.h>
34 #include <sys/types.h>
35 #include <unistd.h>
36 #include <sys/ioctl.h>
37 /* SunOS really wants sys/socket.h BEFORE net/if.h,
38    and FreeBSD wants these lines below the rest. */
39 #include <arpa/inet.h>
40 #include <sys/socket.h>
41 #include <net/if.h>
42 #ifdef HAVE_NETINET_IN_SYSTM_H
43 #include <netinet/in_systm.h>
44 #endif
45 #ifdef HAVE_NETINET_IP_H
46 #include <netinet/ip.h>
47 #endif
48 #ifdef HAVE_NETINET_TCP_H
49 #include <netinet/tcp.h>
50 #endif
51
52 #include <openssl/rand.h>
53 #include <openssl/evp.h>
54 #include <openssl/pem.h>
55 #include <openssl/hmac.h>
56
57 #include <zlib.h>
58 #include <lzo1x.h>
59
60 #include <utils.h>
61 #include <xalloc.h>
62 #include <avl_tree.h>
63 #include <list.h>
64
65 #include "conf.h"
66 #include "connection.h"
67 #include "meta.h"
68 #include "net.h"
69 #include "netutl.h"
70 #include "process.h"
71 #include "protocol.h"
72 #include "subnet.h"
73 #include "graph.h"
74 #include "process.h"
75 #include "route.h"
76 #include "device.h"
77 #include "event.h"
78 #include "logger.h"
79
80 #include "system.h"
81
82 int keylifetime = 0;
83 int keyexpires = 0;
84 EVP_CIPHER_CTX packet_ctx;
85 static char lzo_wrkmem[LZO1X_999_MEM_COMPRESS > LZO1X_1_MEM_COMPRESS ? LZO1X_999_MEM_COMPRESS : LZO1X_1_MEM_COMPRESS];
86
87
88 #define MAX_SEQNO 1073741824
89
90 static length_t compress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level)
91 {
92         if(level == 10) {
93                 lzo_uint lzolen = MAXSIZE;
94                 lzo1x_1_compress(source, len, dest, &lzolen, lzo_wrkmem);
95                 return lzolen;
96         } else if(level < 10) {
97                 unsigned long destlen = MAXSIZE;
98                 if(compress2(dest, &destlen, source, len, level) == Z_OK)
99                         return destlen;
100                 else
101                         return -1;
102         } else {
103                 lzo_uint lzolen = MAXSIZE;
104                 lzo1x_999_compress(source, len, dest, &lzolen, lzo_wrkmem);
105                 return lzolen;
106         }
107         
108         return -1;
109 }
110
111 static length_t uncompress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level)
112 {
113         if(level > 9) {
114                 lzo_uint lzolen = MAXSIZE;
115                 if(lzo1x_decompress_safe(source, len, dest, &lzolen, NULL) == LZO_E_OK)
116                         return lzolen;
117                 else
118                         return -1;
119         } else {
120                 unsigned long destlen = MAXSIZE;
121                 if(uncompress(dest, &destlen, source, len) == Z_OK)
122                         return destlen;
123                 else
124                         return -1;
125         }
126         
127         return -1;
128 }
129
130 /* VPN packet I/O */
131
132 static void receive_packet(node_t *n, vpn_packet_t *packet)
133 {
134         cp();
135
136         ifdebug(TRAFFIC) logger(LOG_DEBUG, _("Received packet of %d bytes from %s (%s)"),
137                            packet->len, n->name, n->hostname);
138
139         route_incoming(n, packet);
140 }
141
142 static void receive_udppacket(node_t *n, vpn_packet_t *inpkt)
143 {
144         vpn_packet_t pkt1, pkt2;
145         vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
146         int nextpkt = 0;
147         vpn_packet_t *outpkt = pkt[0];
148         int outlen, outpad;
149         char hmac[EVP_MAX_MD_SIZE];
150         int i;
151
152         cp();
153
154         /* Check the message authentication code */
155
156         if(myself->digest && myself->maclength) {
157                 inpkt->len -= myself->maclength;
158                 HMAC(myself->digest, myself->key, myself->keylength,
159                          (char *) &inpkt->seqno, inpkt->len, hmac, NULL);
160
161                 if(memcmp(hmac, (char *) &inpkt->seqno + inpkt->len, myself->maclength)) {
162                         ifdebug(TRAFFIC) logger(LOG_DEBUG, _("Got unauthenticated packet from %s (%s)"),
163                                            n->name, n->hostname);
164                         return;
165                 }
166         }
167
168         /* Decrypt the packet */
169
170         if(myself->cipher) {
171                 outpkt = pkt[nextpkt++];
172
173 //              EVP_DecryptInit_ex(&packet_ctx, myself->cipher, NULL, myself->key,
174 //                                              myself->key + myself->cipher->key_len);
175                 EVP_DecryptInit_ex(&packet_ctx, NULL, NULL, NULL, NULL);
176                 EVP_DecryptUpdate(&packet_ctx, (char *) &outpkt->seqno, &outlen,
177                                                   (char *) &inpkt->seqno, inpkt->len);
178                 EVP_DecryptFinal_ex(&packet_ctx, (char *) &outpkt->seqno + outlen, &outpad);
179                 
180                 outpkt->len = outlen + outpad;
181                 inpkt = outpkt;
182         }
183
184         /* Check the sequence number */
185
186         inpkt->len -= sizeof(inpkt->seqno);
187         inpkt->seqno = ntohl(inpkt->seqno);
188
189         if(inpkt->seqno != n->received_seqno + 1) {
190                 if(inpkt->seqno >= n->received_seqno + sizeof(n->late) * 8) {
191                         logger(LOG_WARNING, _("Lost %d packets from %s (%s)"),
192                                            inpkt->seqno - n->received_seqno - 1, n->name, n->hostname);
193                         
194                         memset(n->late, 0, sizeof(n->late));
195                 } else if (inpkt->seqno <= n->received_seqno) {
196                         if(inpkt->seqno <= n->received_seqno - sizeof(n->late) * 8 || !(n->late[(inpkt->seqno / 8) % sizeof(n->late)] & (1 << inpkt->seqno % 8))) {
197                                 logger(LOG_WARNING, _("Got late or replayed packet from %s (%s), seqno %d, last received %d"),
198                                            n->name, n->hostname, inpkt->seqno, n->received_seqno);
199                         } else
200                                 for(i = n->received_seqno + 1; i < inpkt->seqno; i++)
201                                         n->late[(inpkt->seqno / 8) % sizeof(n->late)] |= 1 << i % 8;
202                 }
203         }
204         
205         n->received_seqno = inpkt->seqno;
206         n->late[(n->received_seqno / 8) % sizeof(n->late)] &= ~(1 << n->received_seqno % 8);
207                         
208         if(n->received_seqno > MAX_SEQNO)
209                 keyexpires = 0;
210
211         /* Decompress the packet */
212
213         if(myself->compression) {
214                 outpkt = pkt[nextpkt++];
215
216                 if((outpkt->len = uncompress_packet(outpkt->data, inpkt->data, inpkt->len, myself->compression)) < 0) {
217                         logger(LOG_ERR, _("Error while uncompressing packet from %s (%s)"),
218                                    n->name, n->hostname);
219                         return;
220                 }
221
222                 inpkt = outpkt;
223         }
224
225         receive_packet(n, inpkt);
226 }
227
228 void receive_tcppacket(connection_t *c, char *buffer, int len)
229 {
230         vpn_packet_t outpkt;
231
232         cp();
233
234         outpkt.len = len;
235         memcpy(outpkt.data, buffer, len);
236
237         receive_packet(c->node, &outpkt);
238 }
239
240 static void send_udppacket(node_t *n, vpn_packet_t *inpkt)
241 {
242         vpn_packet_t pkt1, pkt2;
243         vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
244         int nextpkt = 0;
245         vpn_packet_t *outpkt;
246         int origlen;
247         int outlen, outpad;
248         vpn_packet_t *copy;
249         static int priority = 0;
250         int origpriority;
251         int sock;
252
253         cp();
254
255         /* Make sure we have a valid key */
256
257         if(!n->status.validkey) {
258                 ifdebug(TRAFFIC) logger(LOG_INFO,
259                                    _("No valid key known yet for %s (%s), queueing packet"),
260                                    n->name, n->hostname);
261
262                 /* Since packet is on the stack of handle_tap_input(), we have to make a copy of it first. */
263
264                 copy = xmalloc(sizeof(vpn_packet_t));
265                 memcpy(copy, inpkt, sizeof(vpn_packet_t));
266
267                 list_insert_tail(n->queue, copy);
268
269                 if(n->queue->count > MAXQUEUELENGTH)
270                         list_delete_head(n->queue);
271
272                 if(!n->status.waitingforkey)
273                         send_req_key(n->nexthop->connection, myself, n);
274
275                 n->status.waitingforkey = 1;
276
277                 return;
278         }
279
280         origlen = inpkt->len;
281         origpriority = inpkt->priority;
282
283         /* Compress the packet */
284
285         if(n->compression) {
286                 outpkt = pkt[nextpkt++];
287
288                 if((outpkt->len = compress_packet(outpkt->data, inpkt->data, inpkt->len, n->compression)) < 0) {
289                         logger(LOG_ERR, _("Error while compressing packet to %s (%s)"),
290                                    n->name, n->hostname);
291                         return;
292                 }
293
294                 inpkt = outpkt;
295         }
296
297         /* Add sequence number */
298
299         inpkt->seqno = htonl(++(n->sent_seqno));
300         inpkt->len += sizeof(inpkt->seqno);
301
302         /* Encrypt the packet */
303
304         if(n->cipher) {
305                 outpkt = pkt[nextpkt++];
306
307 //              EVP_EncryptInit_ex(&packet_ctx, n->cipher, NULL, n->key, n->key + n->cipher->key_len);
308                 EVP_EncryptInit_ex(&n->packet_ctx, NULL, NULL, NULL, NULL);
309                 EVP_EncryptUpdate(&n->packet_ctx, (char *) &outpkt->seqno, &outlen,
310                                                   (char *) &inpkt->seqno, inpkt->len);
311                 EVP_EncryptFinal_ex(&n->packet_ctx, (char *) &outpkt->seqno + outlen, &outpad);
312
313                 outpkt->len = outlen + outpad;
314                 inpkt = outpkt;
315         }
316
317         /* Add the message authentication code */
318
319         if(n->digest && n->maclength) {
320                 HMAC(n->digest, n->key, n->keylength, (char *) &inpkt->seqno,
321                          inpkt->len, (char *) &inpkt->seqno + inpkt->len, &outlen);
322                 inpkt->len += n->maclength;
323         }
324
325         /* Determine which socket we have to use */
326
327         for(sock = 0; sock < listen_sockets; sock++)
328                 if(n->address.sa.sa_family == listen_socket[sock].sa.sa.sa_family)
329                         break;
330
331         if(sock >= listen_sockets)
332                 sock = 0;                               /* If none is available, just use the first and hope for the best. */
333
334         /* Send the packet */
335
336 #if defined(SOL_IP) && defined(IP_TOS)
337         if(priorityinheritance && origpriority != priority
338            && listen_socket[sock].sa.sa.sa_family == AF_INET) {
339                 priority = origpriority;
340                 ifdebug(TRAFFIC) logger(LOG_DEBUG, _("Setting outgoing packet priority to %d"), priority);
341                 if(setsockopt(listen_socket[sock].udp, SOL_IP, IP_TOS, &priority, sizeof(priority)))    /* SO_PRIORITY doesn't seem to work */
342                         logger(LOG_ERR, _("System call `%s' failed: %s"), "setsockopt",
343                                    strerror(errno));
344         }
345 #endif
346
347         if((sendto(listen_socket[sock].udp, (char *) &inpkt->seqno, inpkt->len, 0, &(n->address.sa), SALEN(n->address.sa))) < 0) {
348                 logger(LOG_ERR, _("Error sending packet to %s (%s): %s"), n->name,
349                            n->hostname, strerror(errno));
350                 return;
351         }
352
353         inpkt->len = origlen;
354 }
355
356 /*
357   send a packet to the given vpn ip.
358 */
359 void send_packet(node_t *n, vpn_packet_t *packet)
360 {
361         node_t *via;
362
363         cp();
364
365         ifdebug(TRAFFIC) logger(LOG_ERR, _("Sending packet of %d bytes to %s (%s)"),
366                            packet->len, n->name, n->hostname);
367
368         if(n == myself) {
369                 ifdebug(TRAFFIC) logger(LOG_NOTICE, _("Packet is looping back to us!"));
370                 return;
371         }
372
373         if(!n->status.reachable) {
374                 ifdebug(TRAFFIC) logger(LOG_INFO, _("Node %s (%s) is not reachable"),
375                                    n->name, n->hostname);
376                 return;
377         }
378
379         via = (n->via == myself) ? n->nexthop : n->via;
380
381         if(via != n)
382                 ifdebug(TRAFFIC) logger(LOG_ERR, _("Sending packet to %s via %s (%s)"),
383                            n->name, via->name, n->via->hostname);
384
385         if((myself->options | via->options) & OPTION_TCPONLY) {
386                 if(send_tcppacket(via->connection, packet))
387                         terminate_connection(via->connection, 1);
388         } else
389                 send_udppacket(via, packet);
390 }
391
392 /* Broadcast a packet using the minimum spanning tree */
393
394 void broadcast_packet(node_t *from, vpn_packet_t *packet)
395 {
396         avl_node_t *node;
397         connection_t *c;
398
399         cp();
400
401         ifdebug(TRAFFIC) logger(LOG_INFO, _("Broadcasting packet of %d bytes from %s (%s)"),
402                            packet->len, from->name, from->hostname);
403
404         for(node = connection_tree->head; node; node = node->next) {
405                 c = (connection_t *) node->data;
406
407                 if(c->status.active && c->status.mst && c != from->nexthop->connection)
408                         send_packet(c->node, packet);
409         }
410 }
411
412 void flush_queue(node_t *n)
413 {
414         list_node_t *node, *next;
415
416         cp();
417
418         ifdebug(TRAFFIC) logger(LOG_INFO, _("Flushing queue for %s (%s)"), n->name, n->hostname);
419
420         for(node = n->queue->head; node; node = next) {
421                 next = node->next;
422                 send_udppacket(n, (vpn_packet_t *) node->data);
423                 list_delete_node(n->queue, node);
424         }
425 }
426
427 void handle_incoming_vpn_data(int sock)
428 {
429         vpn_packet_t pkt;
430         int x, l = sizeof(x);
431         char *hostname;
432         sockaddr_t from;
433         socklen_t fromlen = sizeof(from);
434         node_t *n;
435
436         cp();
437
438         if(getsockopt(sock, SOL_SOCKET, SO_ERROR, &x, &l) < 0) {
439                 logger(LOG_ERR, _("This is a bug: %s:%d: %d:%s"),
440                            __FILE__, __LINE__, sock, strerror(errno));
441                 cp_trace();
442                 exit(1);
443         }
444
445         if(x) {
446                 logger(LOG_ERR, _("Incoming data socket error: %s"), strerror(x));
447                 return;
448         }
449
450         pkt.len = recvfrom(sock, (char *) &pkt.seqno, MAXSIZE, 0, &from.sa, &fromlen);
451
452         if(pkt.len <= 0) {
453                 logger(LOG_ERR, _("Receiving packet failed: %s"), strerror(errno));
454                 return;
455         }
456
457         sockaddrunmap(&from);           /* Some braindead IPv6 implementations do stupid things. */
458
459         n = lookup_node_udp(&from);
460
461         if(!n) {
462                 hostname = sockaddr2hostname(&from);
463                 logger(LOG_WARNING, _("Received UDP packet from unknown source %s"),
464                            hostname);
465                 free(hostname);
466                 return;
467         }
468
469         if(n->connection)
470                 n->connection->last_ping_time = now;
471
472         receive_udppacket(n, &pkt);
473 }