Do not try to dereference myself->connection->config_tree.
[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(int fd, short events, 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         event_add(&n->mtuevent, &(struct timeval){timeout, 0});
140 }
141
142 void send_mtu_probe(node_t *n) {
143         if(!timeout_initialized(&n->mtuevent))
144                 timeout_set(&n->mtuevent, send_mtu_probe_handler, n);
145         send_mtu_probe_handler(0, 0, n);
146 }
147
148 void mtu_probe_h(node_t *n, vpn_packet_t *packet, length_t len) {
149         ifdebug(TRAFFIC) logger(LOG_INFO, "Got MTU probe length %d from %s (%s)", packet->len, n->name, n->hostname);
150
151         if(!packet->data[0]) {
152                 packet->data[0] = 1;
153                 send_udppacket(n, packet);
154         } else {
155                 if(len > n->maxmtu)
156                         len = n->maxmtu;
157                 if(n->minmtu < len)
158                         n->minmtu = len;
159                 if(n->mtuprobes > 30)
160                         n->mtuprobes = 30;
161         }
162 }
163
164 static length_t compress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level) {
165         if(level == 0) {
166                 memcpy(dest, source, len);
167                 return len;
168         } else if(level == 10) {
169 #ifdef HAVE_LZO
170                 lzo_uint lzolen = MAXSIZE;
171                 lzo1x_1_compress(source, len, dest, &lzolen, lzo_wrkmem);
172                 return lzolen;
173 #else
174                 return -1;
175 #endif
176         } else if(level < 10) {
177 #ifdef HAVE_ZLIB
178                 unsigned long destlen = MAXSIZE;
179                 if(compress2(dest, &destlen, source, len, level) == Z_OK)
180                         return destlen;
181                 else
182 #endif
183                         return -1;
184         } else {
185 #ifdef HAVE_LZO
186                 lzo_uint lzolen = MAXSIZE;
187                 lzo1x_999_compress(source, len, dest, &lzolen, lzo_wrkmem);
188                 return lzolen;
189 #else
190                 return -1;
191 #endif
192         }
193         
194         return -1;
195 }
196
197 static length_t uncompress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level) {
198         if(level == 0) {
199                 memcpy(dest, source, len);
200                 return len;
201         } else if(level > 9) {
202 #ifdef HAVE_LZO
203                 lzo_uint lzolen = MAXSIZE;
204                 if(lzo1x_decompress_safe(source, len, dest, &lzolen, NULL) == LZO_E_OK)
205                         return lzolen;
206                 else
207 #endif
208                         return -1;
209         }
210 #ifdef HAVE_ZLIB
211         else {
212                 unsigned long destlen = MAXSIZE;
213                 if(uncompress(dest, &destlen, source, len) == Z_OK)
214                         return destlen;
215                 else
216                         return -1;
217         }
218 #endif
219
220         return -1;
221 }
222
223 /* VPN packet I/O */
224
225 static void receive_packet(node_t *n, vpn_packet_t *packet) {
226         ifdebug(TRAFFIC) logger(LOG_DEBUG, "Received packet of %d bytes from %s (%s)",
227                            packet->len, n->name, n->hostname);
228
229         route(n, packet);
230 }
231
232 static bool try_mac(node_t *n, const vpn_packet_t *inpkt) {
233         if(!digest_active(&n->indigest) || inpkt->len < sizeof inpkt->seqno + digest_length(&n->indigest))
234                 return false;
235
236         return digest_verify(&n->indigest, &inpkt->seqno, inpkt->len - n->indigest.maclength, (const char *)&inpkt->seqno + inpkt->len - n->indigest.maclength);
237 }
238
239 static void receive_udppacket(node_t *n, vpn_packet_t *inpkt) {
240         vpn_packet_t pkt1, pkt2;
241         vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
242         int nextpkt = 0;
243         vpn_packet_t *outpkt = pkt[0];
244         size_t outlen;
245         int i;
246
247         if(!cipher_active(&n->incipher)) {
248                 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Got packet from %s (%s) but he hasn't got our key yet",
249                                         n->name, n->hostname);
250                 return;
251         }
252
253         /* Check packet length */
254
255         if(inpkt->len < sizeof inpkt->seqno + digest_length(&n->indigest)) {
256                 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Got too short packet from %s (%s)",
257                                         n->name, n->hostname);
258                 return;
259         }
260
261         /* Check the message authentication code */
262
263         if(digest_active(&n->indigest)) {
264                 inpkt->len -= n->indigest.maclength;
265                 if(!digest_verify(&n->indigest, &inpkt->seqno, inpkt->len, (const char *)&inpkt->seqno + inpkt->len)) {
266                         ifdebug(TRAFFIC) logger(LOG_DEBUG, "Got unauthenticated packet from %s (%s)", n->name, n->hostname);
267                         return;
268                 }
269         }
270         /* Decrypt the packet */
271
272         if(cipher_active(&n->incipher)) {
273                 outpkt = pkt[nextpkt++];
274                 outlen = MAXSIZE;
275
276                 if(!cipher_decrypt(&n->incipher, &inpkt->seqno, inpkt->len, &outpkt->seqno, &outlen, true)) {
277                         ifdebug(TRAFFIC) logger(LOG_DEBUG, "Error decrypting packet from %s (%s)", n->name, n->hostname);
278                         return;
279                 }
280                 
281                 outpkt->len = outlen;
282                 inpkt = outpkt;
283         }
284
285         /* Check the sequence number */
286
287         inpkt->len -= sizeof inpkt->seqno;
288         inpkt->seqno = ntohl(inpkt->seqno);
289
290         if(replaywin) {
291                 if(inpkt->seqno != n->received_seqno + 1) {
292                         if(inpkt->seqno >= n->received_seqno + replaywin * 8) {
293                                 if(n->farfuture++ < replaywin >> 2) {
294                                         logger(LOG_WARNING, "Packet from %s (%s) is %d seqs in the future, dropped (%u)",
295                                                 n->name, n->hostname, inpkt->seqno - n->received_seqno - 1, n->farfuture);
296                                         return;
297                                 }
298                                 logger(LOG_WARNING, "Lost %d packets from %s (%s)",
299                                                 inpkt->seqno - n->received_seqno - 1, n->name, n->hostname);
300                                 memset(n->late, 0, replaywin);
301                         } else if (inpkt->seqno <= n->received_seqno) {
302                                 if((n->received_seqno >= replaywin * 8 && inpkt->seqno <= n->received_seqno - replaywin * 8) || !(n->late[(inpkt->seqno / 8) % replaywin] & (1 << inpkt->seqno % 8))) {
303                                         logger(LOG_WARNING, "Got late or replayed packet from %s (%s), seqno %d, last received %d",
304                                                 n->name, n->hostname, inpkt->seqno, n->received_seqno);
305                                         return;
306                                 }
307                         } else {
308                                 for(i = n->received_seqno + 1; i < inpkt->seqno; i++)
309                                         n->late[(i / 8) % replaywin] |= 1 << i % 8;
310                         }
311                 }
312
313                 n->farfuture = 0;
314                 n->late[(inpkt->seqno / 8) % replaywin] &= ~(1 << inpkt->seqno % 8);
315         }
316
317         if(inpkt->seqno > n->received_seqno)
318                 n->received_seqno = inpkt->seqno;
319                         
320         if(n->received_seqno > MAX_SEQNO)
321                 regenerate_key();
322
323         /* Decompress the packet */
324
325         length_t origlen = inpkt->len;
326
327         if(n->incompression) {
328                 outpkt = pkt[nextpkt++];
329
330                 if((outpkt->len = uncompress_packet(outpkt->data, inpkt->data, inpkt->len, n->incompression)) < 0) {
331                         ifdebug(TRAFFIC) logger(LOG_ERR, "Error while uncompressing packet from %s (%s)",
332                                                  n->name, n->hostname);
333                         return;
334                 }
335
336                 inpkt = outpkt;
337
338                 origlen -= MTU/64 + 20;
339         }
340
341         inpkt->priority = 0;
342
343         if(!inpkt->data[12] && !inpkt->data[13])
344                 mtu_probe_h(n, inpkt, origlen);
345         else
346                 receive_packet(n, inpkt);
347 }
348
349 void receive_tcppacket(connection_t *c, char *buffer, int len) {
350         vpn_packet_t outpkt;
351
352         outpkt.len = len;
353         if(c->options & OPTION_TCPONLY)
354                 outpkt.priority = 0;
355         else
356                 outpkt.priority = -1;
357         memcpy(outpkt.data, buffer, len);
358
359         receive_packet(c->node, &outpkt);
360 }
361
362 static void send_udppacket(node_t *n, vpn_packet_t *origpkt) {
363         vpn_packet_t pkt1, pkt2;
364         vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
365         vpn_packet_t *inpkt = origpkt;
366         int nextpkt = 0;
367         vpn_packet_t *outpkt;
368         int origlen;
369         size_t outlen;
370 #if defined(SOL_IP) && defined(IP_TOS)
371         static int priority = 0;
372 #endif
373         int origpriority;
374         int sock;
375
376         if(!n->status.reachable) {
377                 ifdebug(TRAFFIC) logger(LOG_INFO, "Trying to send UDP packet to unreachable node %s (%s)", n->name, n->hostname);
378                 return;
379         }
380
381         /* Make sure we have a valid key */
382
383         if(!n->status.validkey) {
384                 time_t now = time(NULL);
385
386                 ifdebug(TRAFFIC) logger(LOG_INFO,
387                                    "No valid key known yet for %s (%s), forwarding via TCP",
388                                    n->name, n->hostname);
389
390                 if(n->last_req_key + 10 < now) {
391                         send_req_key(n);
392                         n->last_req_key = now;
393                 }
394
395                 send_tcppacket(n->nexthop->connection, origpkt);
396
397                 return;
398         }
399
400         if(n->options & OPTION_PMTU_DISCOVERY && inpkt->len > n->minmtu && (inpkt->data[12] | inpkt->data[13])) {
401                 ifdebug(TRAFFIC) logger(LOG_INFO,
402                                 "Packet for %s (%s) larger than minimum MTU, forwarding via %s",
403                                 n->name, n->hostname, n != n->nexthop ? n->nexthop->name : "TCP");
404
405                 if(n != n->nexthop)
406                         send_packet(n->nexthop, origpkt);
407                 else
408                         send_tcppacket(n->nexthop->connection, origpkt);
409
410                 return;
411         }
412
413         origlen = inpkt->len;
414         origpriority = inpkt->priority;
415
416         /* Compress the packet */
417
418         if(n->outcompression) {
419                 outpkt = pkt[nextpkt++];
420
421                 if((outpkt->len = compress_packet(outpkt->data, inpkt->data, inpkt->len, n->outcompression)) < 0) {
422                         ifdebug(TRAFFIC) logger(LOG_ERR, "Error while compressing packet to %s (%s)",
423                                    n->name, n->hostname);
424                         return;
425                 }
426
427                 inpkt = outpkt;
428         }
429
430         /* Add sequence number */
431
432         inpkt->seqno = htonl(++(n->sent_seqno));
433         inpkt->len += sizeof inpkt->seqno;
434
435         /* Encrypt the packet */
436
437         if(cipher_active(&n->outcipher)) {
438                 outpkt = pkt[nextpkt++];
439                 outlen = MAXSIZE;
440
441                 if(!cipher_encrypt(&n->outcipher, &inpkt->seqno, inpkt->len, &outpkt->seqno, &outlen, true)) {
442                         ifdebug(TRAFFIC) logger(LOG_ERR, "Error while encrypting packet to %s (%s)", n->name, n->hostname);
443                         goto end;
444                 }
445
446                 outpkt->len = outlen;
447                 inpkt = outpkt;
448         }
449
450         /* Add the message authentication code */
451
452         if(digest_active(&n->outdigest)) {
453                 digest_create(&n->outdigest, &inpkt->seqno, inpkt->len, (char *)&inpkt->seqno + inpkt->len);
454                 inpkt->len += digest_length(&n->outdigest);
455         }
456
457         /* Determine which socket we have to use */
458
459         for(sock = 0; sock < listen_sockets; sock++)
460                 if(n->address.sa.sa_family == listen_socket[sock].sa.sa.sa_family)
461                         break;
462
463         if(sock >= listen_sockets)
464                 sock = 0;                               /* If none is available, just use the first and hope for the best. */
465
466         /* Send the packet */
467
468 #if defined(SOL_IP) && defined(IP_TOS)
469         if(priorityinheritance && origpriority != priority
470            && listen_socket[sock].sa.sa.sa_family == AF_INET) {
471                 priority = origpriority;
472                 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Setting outgoing packet priority to %d", priority);
473                 if(setsockopt(listen_socket[sock].udp, SOL_IP, IP_TOS, &priority, sizeof priority))     /* SO_PRIORITY doesn't seem to work */
474                         logger(LOG_ERR, "System call `%s' failed: %s", "setsockopt", strerror(errno));
475         }
476 #endif
477
478         if(sendto(listen_socket[sock].udp, (char *) &inpkt->seqno, inpkt->len, 0, &(n->address.sa), SALEN(n->address.sa)) < 0 && !sockwouldblock(sockerrno)) {
479                 if(sockmsgsize(sockerrno)) {
480                         if(n->maxmtu >= origlen)
481                                 n->maxmtu = origlen - 1;
482                         if(n->mtu >= origlen)
483                                 n->mtu = origlen - 1;
484                 } else
485                         logger(LOG_ERR, "Error sending packet to %s (%s): %s", n->name, n->hostname, sockstrerror(sockerrno));
486         }
487
488 end:
489         origpkt->len = origlen;
490 }
491
492 /*
493   send a packet to the given vpn ip.
494 */
495 void send_packet(const node_t *n, vpn_packet_t *packet) {
496         node_t *via;
497
498         if(n == myself) {
499                 if(overwrite_mac)
500                          memcpy(packet->data, mymac.x, ETH_ALEN);
501                 write_packet(packet);
502                 return;
503         }
504
505         ifdebug(TRAFFIC) logger(LOG_ERR, "Sending packet of %d bytes to %s (%s)",
506                            packet->len, n->name, n->hostname);
507
508         if(!n->status.reachable) {
509                 ifdebug(TRAFFIC) logger(LOG_INFO, "Node %s (%s) is not reachable",
510                                    n->name, n->hostname);
511                 return;
512         }
513
514         via = (packet->priority == -1 || n->via == myself) ? n->nexthop : n->via;
515
516         if(via != n)
517                 ifdebug(TRAFFIC) logger(LOG_INFO, "Sending packet to %s via %s (%s)",
518                            n->name, via->name, n->via->hostname);
519
520         if(packet->priority == -1 || ((myself->options | via->options) & OPTION_TCPONLY)) {
521                 if(!send_tcppacket(via->connection, packet))
522                         terminate_connection(via->connection, true);
523         } else
524                 send_udppacket(via, packet);
525 }
526
527 /* Broadcast a packet using the minimum spanning tree */
528
529 void broadcast_packet(const node_t *from, vpn_packet_t *packet) {
530         splay_node_t *node;
531         connection_t *c;
532
533         ifdebug(TRAFFIC) logger(LOG_INFO, "Broadcasting packet of %d bytes from %s (%s)",
534                            packet->len, from->name, from->hostname);
535
536         if(from != myself) {
537                 send_packet(myself, packet);
538
539                 // In TunnelServer mode, do not forward broadcast packets.
540                 // The MST might not be valid and create loops.
541                 if(tunnelserver)
542                         return;
543         }
544
545         for(node = connection_tree->head; node; node = node->next) {
546                 c = node->data;
547
548                 if(c->status.active && c->status.mst && c != from->nexthop->connection)
549                         send_packet(c->node, packet);
550         }
551 }
552
553 static node_t *try_harder(const sockaddr_t *from, const vpn_packet_t *pkt) {
554         splay_node_t *node;
555         node_t *n, *found = NULL;
556         static time_t last_hard_try = 0;
557         time_t now = time(NULL);
558
559         if(last_hard_try == now)
560                 return NULL;
561         else
562                 last_hard_try = now;
563
564         for(node = node_tree->head; node; node = node->next) {
565                 n = node->data;
566
567                 if(n == myself || !n->status.reachable || !digest_active(&n->indigest))
568                         continue;
569
570                 if(try_mac(n, pkt)) {
571                         found = n;
572                         break;
573                 }
574         }
575
576         return found;
577 }
578
579 void handle_incoming_vpn_data(int sock, short events, void *data) {
580         vpn_packet_t pkt;
581         char *hostname;
582         sockaddr_t from;
583         socklen_t fromlen = sizeof from;
584         node_t *n;
585         int len;
586
587         len = recvfrom(sock, (char *) &pkt.seqno, MAXSIZE, 0, &from.sa, &fromlen);
588
589         if(len <= 0 || len > MAXSIZE) {
590                 if(!sockwouldblock(sockerrno))
591                         logger(LOG_ERR, "Receiving packet failed: %s", sockstrerror(sockerrno));
592                 return;
593         }
594
595         pkt.len = len;
596
597         sockaddrunmap(&from);           /* Some braindead IPv6 implementations do stupid things. */
598
599         n = lookup_node_udp(&from);
600
601         if(!n) {
602                 n = try_harder(&from, &pkt);
603                 if(n)
604                         update_node_udp(n, &from);
605                 else ifdebug(PROTOCOL) {
606                         hostname = sockaddr2hostname(&from);
607                         logger(LOG_WARNING, "Received UDP packet from unknown source %s", hostname);
608                         free(hostname);
609                         return;
610                 }
611                 else
612                         return;
613         }
614
615         receive_udppacket(n, &pkt);
616 }
617
618 void handle_device_data(int sock, short events, void *data) {
619         vpn_packet_t packet;
620
621         if(read_packet(&packet))
622                 route(myself, &packet);
623 }