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