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