]> 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 "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                 if(!n->minmtu) {
91                         n->mtuprobes = 31;
92                         timeout = pinginterval;
93                         goto end;
94                 }
95
96                 ifdebug(TRAFFIC) logger(LOG_INFO, "%s (%s) did not respond to UDP ping, restarting PMTU discovery", n->name, n->hostname);
97                 n->mtuprobes = 1;
98                 n->minmtu = 0;
99                 n->maxmtu = MTU;
100         }
101
102         if(n->mtuprobes >= 10 && n->mtuprobes < 32 && !n->minmtu) {
103                 ifdebug(TRAFFIC) logger(LOG_INFO, "No response to MTU probes from %s (%s)", n->name, n->hostname);
104                 n->mtuprobes = 31;
105         }
106
107         if(n->mtuprobes == 30 || (n->mtuprobes < 30 && n->minmtu >= n->maxmtu)) {
108                 if(n->minmtu > n->maxmtu)
109                         n->minmtu = n->maxmtu;
110                 else
111                         n->maxmtu = n->minmtu;
112                 n->mtu = n->minmtu;
113                 ifdebug(TRAFFIC) logger(LOG_INFO, "Fixing MTU of %s (%s) to %d after %d probes", n->name, n->hostname, n->mtu, n->mtuprobes);
114                 n->mtuprobes = 31;
115         }
116
117         if(n->mtuprobes == 31) {
118                 timeout = pinginterval;
119                 goto end;
120         } else if(n->mtuprobes == 32) {
121                 timeout = pingtimeout;
122         }
123
124         for(i = 0; i < 3; i++) {
125                 if(n->maxmtu <= n->minmtu)
126                         len = n->maxmtu;
127                 else
128                         len = n->minmtu + 1 + rand() % (n->maxmtu - n->minmtu);
129
130                 if(len < 64)
131                         len = 64;
132                 
133                 memset(packet.data, 0, 14);
134                 randomize(packet.data + 14, len - 14);
135                 packet.len = len;
136                 packet.priority = 0;
137
138                 ifdebug(TRAFFIC) logger(LOG_INFO, "Sending MTU probe length %d to %s (%s)", len, n->name, n->hostname);
139
140                 send_udppacket(n, &packet);
141         }
142
143 end:
144         event_add(&n->mtuevent, &(struct timeval){timeout, 0});
145 }
146
147 void send_mtu_probe(node_t *n) {
148         if(!timeout_initialized(&n->mtuevent))
149                 timeout_set(&n->mtuevent, send_mtu_probe_handler, n);
150         send_mtu_probe_handler(0, 0, n);
151 }
152
153 void mtu_probe_h(node_t *n, vpn_packet_t *packet, length_t len) {
154         ifdebug(TRAFFIC) logger(LOG_INFO, "Got MTU probe length %d from %s (%s)", packet->len, n->name, n->hostname);
155
156         if(!packet->data[0]) {
157                 packet->data[0] = 1;
158                 send_udppacket(n, packet);
159         } else {
160                 if(n->mtuprobes > 30) {
161                         if(n->minmtu)
162                                 n->mtuprobes = 30;
163                         else
164                                 n->mtuprobes = 1;
165                 }
166
167                 if(len > n->maxmtu)
168                         len = n->maxmtu;
169                 if(n->minmtu < len)
170                         n->minmtu = len;
171         }
172 }
173
174 static length_t compress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level) {
175         if(level == 0) {
176                 memcpy(dest, source, len);
177                 return len;
178         } else if(level == 10) {
179 #ifdef HAVE_LZO
180                 lzo_uint lzolen = MAXSIZE;
181                 lzo1x_1_compress(source, len, dest, &lzolen, lzo_wrkmem);
182                 return lzolen;
183 #else
184                 return -1;
185 #endif
186         } else if(level < 10) {
187 #ifdef HAVE_ZLIB
188                 unsigned long destlen = MAXSIZE;
189                 if(compress2(dest, &destlen, source, len, level) == Z_OK)
190                         return destlen;
191                 else
192 #endif
193                         return -1;
194         } else {
195 #ifdef HAVE_LZO
196                 lzo_uint lzolen = MAXSIZE;
197                 lzo1x_999_compress(source, len, dest, &lzolen, lzo_wrkmem);
198                 return lzolen;
199 #else
200                 return -1;
201 #endif
202         }
203         
204         return -1;
205 }
206
207 static length_t uncompress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level) {
208         if(level == 0) {
209                 memcpy(dest, source, len);
210                 return len;
211         } else if(level > 9) {
212 #ifdef HAVE_LZO
213                 lzo_uint lzolen = MAXSIZE;
214                 if(lzo1x_decompress_safe(source, len, dest, &lzolen, NULL) == LZO_E_OK)
215                         return lzolen;
216                 else
217 #endif
218                         return -1;
219         }
220 #ifdef HAVE_ZLIB
221         else {
222                 unsigned long destlen = MAXSIZE;
223                 if(uncompress(dest, &destlen, source, len) == Z_OK)
224                         return destlen;
225                 else
226                         return -1;
227         }
228 #endif
229
230         return -1;
231 }
232
233 /* VPN packet I/O */
234
235 static void receive_packet(node_t *n, vpn_packet_t *packet) {
236         ifdebug(TRAFFIC) logger(LOG_DEBUG, "Received packet of %d bytes from %s (%s)",
237                            packet->len, n->name, n->hostname);
238
239         route(n, packet);
240 }
241
242 static bool try_mac(node_t *n, const vpn_packet_t *inpkt) {
243         if(!digest_active(&n->indigest) || inpkt->len < sizeof inpkt->seqno + digest_length(&n->indigest))
244                 return false;
245
246         return digest_verify(&n->indigest, &inpkt->seqno, inpkt->len - n->indigest.maclength, (const char *)&inpkt->seqno + inpkt->len - n->indigest.maclength);
247 }
248
249 static void receive_udppacket(node_t *n, vpn_packet_t *inpkt) {
250         vpn_packet_t pkt1, pkt2;
251         vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
252         int nextpkt = 0;
253         vpn_packet_t *outpkt = pkt[0];
254         size_t outlen;
255         int i;
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(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, 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;
379         size_t outlen;
380 #if defined(SOL_IP) && defined(IP_TOS)
381         static int priority = 0;
382 #endif
383         int origpriority;
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         origlen = inpkt->len;
424         origpriority = inpkt->priority;
425
426         /* Compress the packet */
427
428         if(n->outcompression) {
429                 outpkt = pkt[nextpkt++];
430
431                 if((outpkt->len = compress_packet(outpkt->data, inpkt->data, inpkt->len, n->outcompression)) < 0) {
432                         ifdebug(TRAFFIC) logger(LOG_ERR, "Error while compressing packet to %s (%s)",
433                                    n->name, n->hostname);
434                         return;
435                 }
436
437                 inpkt = outpkt;
438         }
439
440         /* Add sequence number */
441
442         inpkt->seqno = htonl(++(n->sent_seqno));
443         inpkt->len += sizeof inpkt->seqno;
444
445         /* Encrypt the packet */
446
447         if(cipher_active(&n->outcipher)) {
448                 outpkt = pkt[nextpkt++];
449                 outlen = MAXSIZE;
450
451                 if(!cipher_encrypt(&n->outcipher, &inpkt->seqno, inpkt->len, &outpkt->seqno, &outlen, true)) {
452                         ifdebug(TRAFFIC) logger(LOG_ERR, "Error while encrypting packet to %s (%s)", n->name, n->hostname);
453                         goto end;
454                 }
455
456                 outpkt->len = outlen;
457                 inpkt = outpkt;
458         }
459
460         /* Add the message authentication code */
461
462         if(digest_active(&n->outdigest)) {
463                 digest_create(&n->outdigest, &inpkt->seqno, inpkt->len, (char *)&inpkt->seqno + inpkt->len);
464                 inpkt->len += digest_length(&n->outdigest);
465         }
466
467         /* Determine which socket we have to use */
468
469         for(sock = 0; sock < listen_sockets; sock++)
470                 if(n->address.sa.sa_family == listen_socket[sock].sa.sa.sa_family)
471                         break;
472
473         if(sock >= listen_sockets)
474                 sock = 0;                               /* If none is available, just use the first and hope for the best. */
475
476         /* Send the packet */
477
478 #if defined(SOL_IP) && defined(IP_TOS)
479         if(priorityinheritance && origpriority != priority
480            && listen_socket[sock].sa.sa.sa_family == AF_INET) {
481                 priority = origpriority;
482                 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Setting outgoing packet priority to %d", priority);
483                 if(setsockopt(listen_socket[sock].udp, SOL_IP, IP_TOS, &priority, sizeof priority))     /* SO_PRIORITY doesn't seem to work */
484                         logger(LOG_ERR, "System call `%s' failed: %s", "setsockopt", strerror(errno));
485         }
486 #endif
487
488         if(sendto(listen_socket[sock].udp, (char *) &inpkt->seqno, inpkt->len, 0, &(n->address.sa), SALEN(n->address.sa)) < 0 && !sockwouldblock(sockerrno)) {
489                 if(sockmsgsize(sockerrno)) {
490                         if(n->maxmtu >= origlen)
491                                 n->maxmtu = origlen - 1;
492                         if(n->mtu >= origlen)
493                                 n->mtu = origlen - 1;
494                 } else
495                         logger(LOG_ERR, "Error sending packet to %s (%s): %s", n->name, n->hostname, sockstrerror(sockerrno));
496         }
497
498 end:
499         origpkt->len = origlen;
500 }
501
502 /*
503   send a packet to the given vpn ip.
504 */
505 void send_packet(const node_t *n, vpn_packet_t *packet) {
506         node_t *via;
507
508         if(n == myself) {
509                 if(overwrite_mac)
510                          memcpy(packet->data, mymac.x, ETH_ALEN);
511                 write_packet(packet);
512                 return;
513         }
514
515         ifdebug(TRAFFIC) logger(LOG_ERR, "Sending packet of %d bytes to %s (%s)",
516                            packet->len, n->name, n->hostname);
517
518         if(!n->status.reachable) {
519                 ifdebug(TRAFFIC) logger(LOG_INFO, "Node %s (%s) is not reachable",
520                                    n->name, n->hostname);
521                 return;
522         }
523
524         via = (packet->priority == -1 || n->via == myself) ? n->nexthop : n->via;
525
526         if(via != n)
527                 ifdebug(TRAFFIC) logger(LOG_INFO, "Sending packet to %s via %s (%s)",
528                            n->name, via->name, n->via->hostname);
529
530         if(packet->priority == -1 || ((myself->options | via->options) & OPTION_TCPONLY)) {
531                 if(!send_tcppacket(via->connection, packet))
532                         terminate_connection(via->connection, true);
533         } else
534                 send_udppacket(via, packet);
535 }
536
537 /* Broadcast a packet using the minimum spanning tree */
538
539 void broadcast_packet(const node_t *from, vpn_packet_t *packet) {
540         splay_node_t *node;
541         connection_t *c;
542
543         ifdebug(TRAFFIC) logger(LOG_INFO, "Broadcasting packet of %d bytes from %s (%s)",
544                            packet->len, from->name, from->hostname);
545
546         if(from != myself) {
547                 send_packet(myself, packet);
548
549                 // In TunnelServer mode, do not forward broadcast packets.
550                 // The MST might not be valid and create loops.
551                 if(tunnelserver)
552                         return;
553         }
554
555         for(node = connection_tree->head; node; node = node->next) {
556                 c = node->data;
557
558                 if(c->status.active && c->status.mst && c != from->nexthop->connection)
559                         send_packet(c->node, packet);
560         }
561 }
562
563 static node_t *try_harder(const sockaddr_t *from, const vpn_packet_t *pkt) {
564         splay_node_t *node;
565         edge_t *e;
566         node_t *n = NULL;
567         bool hard = false;
568         static time_t last_hard_try = 0;
569         time_t now = time(NULL);
570
571         if(last_hard_try == now)
572                 return NULL;
573         else
574                 last_hard_try = now;
575
576         for(node = edge_weight_tree->head; node; node = node->next) {
577                 e = node->data;
578
579                 if(e->to == myself)
580                         continue;
581
582                 if(sockaddrcmp_noport(from, &e->address)) {
583                         if(last_hard_try == now)
584                                 continue;
585                         hard = true;
586                 }
587
588                 if(!try_mac(e->to, pkt))
589                         continue;
590
591                 n = e->to;
592                 break;
593         }
594
595         if(hard)
596                 last_hard_try = now;
597
598         return n;
599 }
600
601 void handle_incoming_vpn_data(int sock, short events, void *data) {
602         vpn_packet_t pkt;
603         char *hostname;
604         sockaddr_t from;
605         socklen_t fromlen = sizeof from;
606         node_t *n;
607         int len;
608
609         len = recvfrom(sock, (char *) &pkt.seqno, MAXSIZE, 0, &from.sa, &fromlen);
610
611         if(len <= 0 || len > MAXSIZE) {
612                 if(!sockwouldblock(sockerrno))
613                         logger(LOG_ERR, "Receiving packet failed: %s", sockstrerror(sockerrno));
614                 return;
615         }
616
617         pkt.len = len;
618
619         sockaddrunmap(&from);           /* Some braindead IPv6 implementations do stupid things. */
620
621         n = lookup_node_udp(&from);
622
623         if(!n) {
624                 n = try_harder(&from, &pkt);
625                 if(n)
626                         update_node_udp(n, &from);
627                 else ifdebug(PROTOCOL) {
628                         hostname = sockaddr2hostname(&from);
629                         logger(LOG_WARNING, "Received UDP packet from unknown source %s", hostname);
630                         free(hostname);
631                         return;
632                 }
633                 else
634                         return;
635         }
636
637         receive_udppacket(n, &pkt);
638 }
639
640 void handle_device_data(int sock, short events, void *data) {
641         vpn_packet_t packet;
642
643         if(read_packet(&packet))
644                 route(myself, &packet);
645 }