Merge branch 'master' into 1.1
[tinc] / src / net_packet.c
1 /*
2     net_packet.c -- Handles in- and outgoing VPN packets
3     Copyright (C) 1998-2005 Ivo Timmermans,
4                   2000-2010 Guus Sliepen <guus@tinc-vpn.org>
5                   2010      Timothy Redaelli <timothy@redaelli.eu>
6
7     This program is free software; you can redistribute it and/or modify
8     it under the terms of the GNU General Public License as published by
9     the Free Software Foundation; either version 2 of the License, or
10     (at your option) any later version.
11
12     This program is distributed in the hope that it will be useful,
13     but WITHOUT ANY WARRANTY; without even the implied warranty of
14     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15     GNU General Public License for more details.
16
17     You should have received a copy of the GNU General Public License along
18     with this program; if not, write to the Free Software Foundation, Inc.,
19     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 */
21
22 #include "system.h"
23
24 #include <openssl/rand.h>
25 #include <openssl/err.h>
26 #include <openssl/evp.h>
27 #include <openssl/pem.h>
28 #include <openssl/hmac.h>
29
30 #ifdef HAVE_ZLIB
31 #include <zlib.h>
32 #endif
33
34 #ifdef HAVE_LZO
35 #include LZO1X_H
36 #endif
37
38 #include "splay_tree.h"
39 #include "cipher.h"
40 #include "conf.h"
41 #include "connection.h"
42 #include "crypto.h"
43 #include "digest.h"
44 #include "device.h"
45 #include "ethernet.h"
46 #include "graph.h"
47 #include "list.h"
48 #include "logger.h"
49 #include "net.h"
50 #include "netutl.h"
51 #include "protocol.h"
52 #include "process.h"
53 #include "route.h"
54 #include "utils.h"
55 #include "xalloc.h"
56
57 int keylifetime = 0;
58 int keyexpires = 0;
59 #ifdef HAVE_LZO
60 static char lzo_wrkmem[LZO1X_999_MEM_COMPRESS > LZO1X_1_MEM_COMPRESS ? LZO1X_999_MEM_COMPRESS : LZO1X_1_MEM_COMPRESS];
61 #endif
62
63 static void send_udppacket(node_t *, vpn_packet_t *);
64
65 #define MAX_SEQNO 1073741824
66
67 // mtuprobes == 1..30: initial discovery, send bursts with 1 second interval
68 // mtuprobes ==    31: sleep pinginterval seconds
69 // mtuprobes ==    32: send 1 burst, sleep pingtimeout second
70 // mtuprobes ==    33: no response from other side, restart PMTU discovery process
71
72 static void send_mtu_probe_handler(int fd, short events, void *data) {
73         node_t *n = data;
74         vpn_packet_t packet;
75         int len, i;
76         int timeout = 1;
77         
78         n->mtuprobes++;
79
80         if(!n->status.reachable || !n->status.validkey) {
81                 ifdebug(TRAFFIC) logger(LOG_INFO, "Trying to send MTU probe to unreachable or rekeying node %s (%s)", n->name, n->hostname);
82                 n->mtuprobes = 0;
83                 return;
84         }
85
86         if(n->mtuprobes > 32) {
87                 ifdebug(TRAFFIC) logger(LOG_INFO, "%s (%s) did not respond to UDP ping, restarting PMTU discovery", n->name, n->hostname);
88                 n->mtuprobes = 1;
89                 n->minmtu = 0;
90                 n->maxmtu = MTU;
91         }
92
93         if(n->mtuprobes >= 10 && !n->minmtu) {
94                 ifdebug(TRAFFIC) logger(LOG_INFO, "No response to MTU probes from %s (%s)", n->name, n->hostname);
95                 n->mtuprobes = 0;
96                 return;
97         }
98
99         if(n->mtuprobes == 30 || (n->mtuprobes < 30 && n->minmtu >= n->maxmtu)) {
100                 if(n->minmtu > n->maxmtu)
101                         n->minmtu = n->maxmtu;
102                 else
103                         n->maxmtu = n->minmtu;
104                 n->mtu = n->minmtu;
105                 ifdebug(TRAFFIC) logger(LOG_INFO, "Fixing MTU of %s (%s) to %d after %d probes", n->name, n->hostname, n->mtu, n->mtuprobes);
106                 n->mtuprobes = 31;
107         }
108
109         if(n->mtuprobes == 31) {
110                 timeout = pinginterval;
111                 goto end;
112         } else if(n->mtuprobes == 32) {
113                 timeout = pingtimeout;
114         }
115
116         for(i = 0; i < 3; i++) {
117                 if(n->maxmtu <= n->minmtu)
118                         len = n->maxmtu;
119                 else
120                         len = n->minmtu + 1 + rand() % (n->maxmtu - n->minmtu);
121
122                 if(len < 64)
123                         len = 64;
124                 
125                 memset(packet.data, 0, 14);
126                 randomize(packet.data + 14, len - 14);
127                 packet.len = len;
128                 packet.priority = 0;
129
130                 ifdebug(TRAFFIC) logger(LOG_INFO, "Sending MTU probe length %d to %s (%s)", len, n->name, n->hostname);
131
132                 send_udppacket(n, &packet);
133         }
134
135 end:
136         event_add(&n->mtuevent, &(struct timeval){timeout, 0});
137 }
138
139 void send_mtu_probe(node_t *n) {
140         if(!timeout_initialized(&n->mtuevent))
141                 timeout_set(&n->mtuevent, send_mtu_probe_handler, n);
142         send_mtu_probe_handler(0, 0, n);
143 }
144
145 void mtu_probe_h(node_t *n, vpn_packet_t *packet, length_t len) {
146         ifdebug(TRAFFIC) logger(LOG_INFO, "Got MTU probe length %d from %s (%s)", packet->len, n->name, n->hostname);
147
148         if(!packet->data[0]) {
149                 packet->data[0] = 1;
150                 send_udppacket(n, packet);
151         } else {
152                 if(len > n->maxmtu)
153                         len = n->maxmtu;
154                 if(n->minmtu < len)
155                         n->minmtu = len;
156                 if(n->mtuprobes > 30)
157                         n->mtuprobes = 30;
158         }
159 }
160
161 static length_t compress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level) {
162         if(level == 0) {
163                 memcpy(dest, source, len);
164                 return len;
165         } else if(level == 10) {
166 #ifdef HAVE_LZO
167                 lzo_uint lzolen = MAXSIZE;
168                 lzo1x_1_compress(source, len, dest, &lzolen, lzo_wrkmem);
169                 return lzolen;
170 #else
171                 return -1;
172 #endif
173         } else if(level < 10) {
174 #ifdef HAVE_ZLIB
175                 unsigned long destlen = MAXSIZE;
176                 if(compress2(dest, &destlen, source, len, level) == Z_OK)
177                         return destlen;
178                 else
179 #endif
180                         return -1;
181         } else {
182 #ifdef HAVE_LZO
183                 lzo_uint lzolen = MAXSIZE;
184                 lzo1x_999_compress(source, len, dest, &lzolen, lzo_wrkmem);
185                 return lzolen;
186 #else
187                 return -1;
188 #endif
189         }
190         
191         return -1;
192 }
193
194 static length_t uncompress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level) {
195         if(level == 0) {
196                 memcpy(dest, source, len);
197                 return len;
198         } else if(level > 9) {
199 #ifdef HAVE_LZO
200                 lzo_uint lzolen = MAXSIZE;
201                 if(lzo1x_decompress_safe(source, len, dest, &lzolen, NULL) == LZO_E_OK)
202                         return lzolen;
203                 else
204 #endif
205                         return -1;
206         }
207 #ifdef HAVE_ZLIB
208         else {
209                 unsigned long destlen = MAXSIZE;
210                 if(uncompress(dest, &destlen, source, len) == Z_OK)
211                         return destlen;
212                 else
213                         return -1;
214         }
215 #endif
216
217         return -1;
218 }
219
220 /* VPN packet I/O */
221
222 static void receive_packet(node_t *n, vpn_packet_t *packet) {
223         ifdebug(TRAFFIC) logger(LOG_DEBUG, "Received packet of %d bytes from %s (%s)",
224                            packet->len, n->name, n->hostname);
225
226         route(n, packet);
227 }
228
229 static bool try_mac(node_t *n, const vpn_packet_t *inpkt) {
230         if(!digest_active(&n->indigest) || inpkt->len < sizeof inpkt->seqno + digest_length(&n->indigest))
231                 return false;
232
233         return digest_verify(&n->indigest, &inpkt->seqno, inpkt->len - n->indigest.maclength, (const char *)&inpkt->seqno + inpkt->len - n->indigest.maclength);
234 }
235
236 static void receive_udppacket(node_t *n, vpn_packet_t *inpkt) {
237         vpn_packet_t pkt1, pkt2;
238         vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
239         int nextpkt = 0;
240         vpn_packet_t *outpkt = pkt[0];
241         size_t outlen;
242         int i;
243
244         if(!cipher_active(&n->incipher)) {
245                 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Got packet from %s (%s) but he hasn't got our key yet",
246                                         n->name, n->hostname);
247                 return;
248         }
249
250         /* Check packet length */
251
252         if(inpkt->len < sizeof inpkt->seqno + digest_length(&n->indigest)) {
253                 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Got too short packet from %s (%s)",
254                                         n->name, n->hostname);
255                 return;
256         }
257
258         /* Check the message authentication code */
259
260         if(digest_active(&n->indigest)) {
261                 inpkt->len -= n->indigest.maclength;
262                 if(!digest_verify(&n->indigest, &inpkt->seqno, inpkt->len, (const char *)&inpkt->seqno + inpkt->len)) {
263                         ifdebug(TRAFFIC) logger(LOG_DEBUG, "Got unauthenticated packet from %s (%s)", n->name, n->hostname);
264                         return;
265                 }
266         }
267         /* Decrypt the packet */
268
269         if(cipher_active(&n->incipher)) {
270                 outpkt = pkt[nextpkt++];
271                 outlen = MAXSIZE;
272
273                 if(!cipher_decrypt(&n->incipher, &inpkt->seqno, inpkt->len, &outpkt->seqno, &outlen, true)) {
274                         ifdebug(TRAFFIC) logger(LOG_DEBUG, "Error decrypting packet from %s (%s)", n->name, n->hostname);
275                         return;
276                 }
277                 
278                 outpkt->len = outlen;
279                 inpkt = outpkt;
280         }
281
282         /* Check the sequence number */
283
284         inpkt->len -= sizeof inpkt->seqno;
285         inpkt->seqno = ntohl(inpkt->seqno);
286
287         if(inpkt->seqno != n->received_seqno + 1) {
288                 if(inpkt->seqno >= n->received_seqno + sizeof n->late * 8) {
289                         logger(LOG_WARNING, "Lost %d packets from %s (%s)",
290                                            inpkt->seqno - n->received_seqno - 1, n->name, n->hostname);
291                         
292                         memset(n->late, 0, sizeof n->late);
293                 } else if (inpkt->seqno <= n->received_seqno) {
294                         if((n->received_seqno >= sizeof n->late * 8 && inpkt->seqno <= n->received_seqno - sizeof n->late * 8) || !(n->late[(inpkt->seqno / 8) % sizeof n->late] & (1 << inpkt->seqno % 8))) {
295                                 logger(LOG_WARNING, "Got late or replayed packet from %s (%s), seqno %d, last received %d",
296                                            n->name, n->hostname, inpkt->seqno, n->received_seqno);
297                                 return;
298                         }
299                 } else {
300                         for(i = n->received_seqno + 1; i < inpkt->seqno; i++)
301                                 n->late[(i / 8) % sizeof n->late] |= 1 << i % 8;
302                 }
303         }
304         
305         n->late[(inpkt->seqno / 8) % sizeof n->late] &= ~(1 << inpkt->seqno % 8);
306
307         if(inpkt->seqno > n->received_seqno)
308                 n->received_seqno = inpkt->seqno;
309                         
310         if(n->received_seqno > MAX_SEQNO)
311                 regenerate_key();
312
313         /* Decompress the packet */
314
315         length_t origlen = inpkt->len;
316
317         if(n->incompression) {
318                 outpkt = pkt[nextpkt++];
319
320                 if((outpkt->len = uncompress_packet(outpkt->data, inpkt->data, inpkt->len, n->incompression)) < 0) {
321                         ifdebug(TRAFFIC) logger(LOG_ERR, "Error while uncompressing packet from %s (%s)",
322                                                  n->name, n->hostname);
323                         return;
324                 }
325
326                 inpkt = outpkt;
327
328                 origlen -= MTU/64 + 20;
329         }
330
331         inpkt->priority = 0;
332
333         if(!inpkt->data[12] && !inpkt->data[13])
334                 mtu_probe_h(n, inpkt, origlen);
335         else
336                 receive_packet(n, inpkt);
337 }
338
339 void receive_tcppacket(connection_t *c, char *buffer, int len) {
340         vpn_packet_t outpkt;
341
342         outpkt.len = len;
343         if(c->options & OPTION_TCPONLY)
344                 outpkt.priority = 0;
345         else
346                 outpkt.priority = -1;
347         memcpy(outpkt.data, buffer, len);
348
349         receive_packet(c->node, &outpkt);
350 }
351
352 static void send_udppacket(node_t *n, vpn_packet_t *origpkt) {
353         vpn_packet_t pkt1, pkt2;
354         vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
355         vpn_packet_t *inpkt = origpkt;
356         int nextpkt = 0;
357         vpn_packet_t *outpkt;
358         int origlen;
359         size_t outlen;
360 #if defined(SOL_IP) && defined(IP_TOS)
361         static int priority = 0;
362 #endif
363         int origpriority;
364         int sock;
365
366         if(!n->status.reachable) {
367                 ifdebug(TRAFFIC) logger(LOG_INFO, "Trying to send UDP packet to unreachable node %s (%s)", n->name, n->hostname);
368                 return;
369         }
370
371         /* Make sure we have a valid key */
372
373         if(!n->status.validkey) {
374                 time_t now = time(NULL);
375
376                 ifdebug(TRAFFIC) logger(LOG_INFO,
377                                    "No valid key known yet for %s (%s), forwarding via TCP",
378                                    n->name, n->hostname);
379
380                 if(n->last_req_key + 10 < now) {
381                         send_req_key(n);
382                         n->last_req_key = now;
383                 }
384
385                 send_tcppacket(n->nexthop->connection, origpkt);
386
387                 return;
388         }
389
390         if(n->options & OPTION_PMTU_DISCOVERY && inpkt->len > n->minmtu && (inpkt->data[12] | inpkt->data[13])) {
391                 ifdebug(TRAFFIC) logger(LOG_INFO,
392                                 "Packet for %s (%s) larger than minimum MTU, forwarding via %s",
393                                 n->name, n->hostname, n != n->nexthop ? n->nexthop->name : "TCP");
394
395                 if(n != n->nexthop)
396                         send_packet(n->nexthop, origpkt);
397                 else
398                         send_tcppacket(n->nexthop->connection, origpkt);
399
400                 return;
401         }
402
403         origlen = inpkt->len;
404         origpriority = inpkt->priority;
405
406         /* Compress the packet */
407
408         if(n->outcompression) {
409                 outpkt = pkt[nextpkt++];
410
411                 if((outpkt->len = compress_packet(outpkt->data, inpkt->data, inpkt->len, n->outcompression)) < 0) {
412                         ifdebug(TRAFFIC) logger(LOG_ERR, "Error while compressing packet to %s (%s)",
413                                    n->name, n->hostname);
414                         return;
415                 }
416
417                 inpkt = outpkt;
418         }
419
420         /* Add sequence number */
421
422         inpkt->seqno = htonl(++(n->sent_seqno));
423         inpkt->len += sizeof inpkt->seqno;
424
425         /* Encrypt the packet */
426
427         if(cipher_active(&n->outcipher)) {
428                 outpkt = pkt[nextpkt++];
429                 outlen = MAXSIZE;
430
431                 if(!cipher_encrypt(&n->outcipher, &inpkt->seqno, inpkt->len, &outpkt->seqno, &outlen, true)) {
432                         ifdebug(TRAFFIC) logger(LOG_ERR, "Error while encrypting packet to %s (%s)", n->name, n->hostname);
433                         goto end;
434                 }
435
436                 outpkt->len = outlen;
437                 inpkt = outpkt;
438         }
439
440         /* Add the message authentication code */
441
442         if(digest_active(&n->outdigest)) {
443                 digest_create(&n->outdigest, &inpkt->seqno, inpkt->len, (char *)&inpkt->seqno + inpkt->len);
444                 inpkt->len += digest_length(&n->outdigest);
445         }
446
447         /* Determine which socket we have to use */
448
449         for(sock = 0; sock < listen_sockets; sock++)
450                 if(n->address.sa.sa_family == listen_socket[sock].sa.sa.sa_family)
451                         break;
452
453         if(sock >= listen_sockets)
454                 sock = 0;                               /* If none is available, just use the first and hope for the best. */
455
456         /* Send the packet */
457
458 #if defined(SOL_IP) && defined(IP_TOS)
459         if(priorityinheritance && origpriority != priority
460            && listen_socket[sock].sa.sa.sa_family == AF_INET) {
461                 priority = origpriority;
462                 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Setting outgoing packet priority to %d", priority);
463                 if(setsockopt(listen_socket[sock].udp, SOL_IP, IP_TOS, &priority, sizeof priority))     /* SO_PRIORITY doesn't seem to work */
464                         logger(LOG_ERR, "System call `%s' failed: %s", "setsockopt", strerror(errno));
465         }
466 #endif
467
468         if(sendto(listen_socket[sock].udp, (char *) &inpkt->seqno, inpkt->len, 0, &(n->address.sa), SALEN(n->address.sa)) < 0 && !sockwouldblock(sockerrno)) {
469                 if(sockmsgsize(sockerrno)) {
470                         if(n->maxmtu >= origlen)
471                                 n->maxmtu = origlen - 1;
472                         if(n->mtu >= origlen)
473                                 n->mtu = origlen - 1;
474                 } else
475                         logger(LOG_ERR, "Error sending packet to %s (%s): %s", n->name, n->hostname, sockstrerror(sockerrno));
476         }
477
478 end:
479         origpkt->len = origlen;
480 }
481
482 /*
483   send a packet to the given vpn ip.
484 */
485 void send_packet(const node_t *n, vpn_packet_t *packet) {
486         node_t *via;
487
488         if(n == myself) {
489                 if(overwrite_mac)
490                          memcpy(packet->data, mymac.x, ETH_ALEN);
491                 write_packet(packet);
492                 return;
493         }
494
495         ifdebug(TRAFFIC) logger(LOG_ERR, "Sending packet of %d bytes to %s (%s)",
496                            packet->len, n->name, n->hostname);
497
498         if(!n->status.reachable) {
499                 ifdebug(TRAFFIC) logger(LOG_INFO, "Node %s (%s) is not reachable",
500                                    n->name, n->hostname);
501                 return;
502         }
503
504         via = (packet->priority == -1 || n->via == myself) ? n->nexthop : n->via;
505
506         if(via != n)
507                 ifdebug(TRAFFIC) logger(LOG_INFO, "Sending packet to %s via %s (%s)",
508                            n->name, via->name, n->via->hostname);
509
510         if(packet->priority == -1 || ((myself->options | via->options) & OPTION_TCPONLY)) {
511                 if(!send_tcppacket(via->connection, packet))
512                         terminate_connection(via->connection, true);
513         } else
514                 send_udppacket(via, packet);
515 }
516
517 /* Broadcast a packet using the minimum spanning tree */
518
519 void broadcast_packet(const node_t *from, vpn_packet_t *packet) {
520         splay_node_t *node;
521         connection_t *c;
522
523         ifdebug(TRAFFIC) logger(LOG_INFO, "Broadcasting packet of %d bytes from %s (%s)",
524                            packet->len, from->name, from->hostname);
525
526         if(from != myself) {
527                 send_packet(myself, packet);
528
529                 // In TunnelServer mode, do not forward broadcast packets.
530                 // The MST might not be valid and create loops.
531                 if(tunnelserver)
532                         return;
533         }
534
535         for(node = connection_tree->head; node; node = node->next) {
536                 c = node->data;
537
538                 if(c->status.active && c->status.mst && c != from->nexthop->connection)
539                         send_packet(c->node, packet);
540         }
541 }
542
543 static node_t *try_harder(const sockaddr_t *from, const vpn_packet_t *pkt) {
544         splay_node_t *node;
545         node_t *n, *found = NULL;
546         static time_t last_hard_try = 0;
547         time_t now = time(NULL);
548
549         if(last_hard_try == now)
550                 return NULL;
551         else
552                 last_hard_try = now;
553
554         for(node = node_tree->head; node; node = node->next) {
555                 n = node->data;
556
557                 if(n == myself || !n->status.reachable || !digest_active(&n->indigest))
558                         continue;
559
560                 if(try_mac(n, pkt)) {
561                         found = n;
562                         break;
563                 }
564         }
565
566         return found;
567 }
568
569 void handle_incoming_vpn_data(int sock, short events, void *data) {
570         vpn_packet_t pkt;
571         char *hostname;
572         sockaddr_t from;
573         socklen_t fromlen = sizeof from;
574         node_t *n;
575         int len;
576
577         len = recvfrom(sock, (char *) &pkt.seqno, MAXSIZE, 0, &from.sa, &fromlen);
578
579         if(len <= 0 || len > MAXSIZE) {
580                 if(!sockwouldblock(sockerrno))
581                         logger(LOG_ERR, "Receiving packet failed: %s", sockstrerror(sockerrno));
582                 return;
583         }
584
585         pkt.len = len;
586
587         sockaddrunmap(&from);           /* Some braindead IPv6 implementations do stupid things. */
588
589         n = lookup_node_udp(&from);
590
591         if(!n) {
592                 n = try_harder(&from, &pkt);
593                 if(n)
594                         update_node_udp(n, &from);
595                 else ifdebug(PROTOCOL) {
596                         hostname = sockaddr2hostname(&from);
597                         logger(LOG_WARNING, "Received UDP packet from unknown source %s", hostname);
598                         free(hostname);
599                         return;
600                 }
601                 else
602                         return;
603         }
604
605         receive_udppacket(n, &pkt);
606 }
607
608 void handle_device_data(int sock, short events, void *data) {
609         vpn_packet_t packet;
610
611         if(read_packet(&packet))
612                 route(myself, &packet);
613 }