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