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