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