cf5fb9391ef548c31d4e93c03e02424ecdb1465c
[oweals/tinc.git] / 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 #if defined(SOL_IP) && defined(IP_TOS)
369         static int priority = 0;
370 #endif
371         int origpriority;
372         int sock;
373
374         if(!n->status.reachable) {
375                 ifdebug(TRAFFIC) logger(LOG_INFO, "Trying to send UDP packet to unreachable node %s (%s)", n->name, n->hostname);
376                 return;
377         }
378
379         /* Make sure we have a valid key */
380
381         if(!n->status.validkey) {
382                 ifdebug(TRAFFIC) logger(LOG_INFO,
383                                    "No valid key known yet for %s (%s), forwarding via TCP",
384                                    n->name, n->hostname);
385
386                 if(n->last_req_key + 10 < now) {
387                         send_req_key(n);
388                         n->last_req_key = now;
389                 }
390
391                 send_tcppacket(n->nexthop->connection, origpkt);
392
393                 return;
394         }
395
396         if(n->options & OPTION_PMTU_DISCOVERY && inpkt->len > n->minmtu && (inpkt->data[12] | inpkt->data[13])) {
397                 ifdebug(TRAFFIC) logger(LOG_INFO,
398                                 "Packet for %s (%s) larger than minimum MTU, forwarding via %s",
399                                 n->name, n->hostname, n != n->nexthop ? n->nexthop->name : "TCP");
400
401                 if(n != n->nexthop)
402                         send_packet(n->nexthop, origpkt);
403                 else
404                         send_tcppacket(n->nexthop->connection, origpkt);
405
406                 return;
407         }
408
409         origlen = inpkt->len;
410         origpriority = inpkt->priority;
411
412         /* Compress the packet */
413
414         if(n->outcompression) {
415                 outpkt = pkt[nextpkt++];
416
417                 if((outpkt->len = compress_packet(outpkt->data, inpkt->data, inpkt->len, n->outcompression)) < 0) {
418                         ifdebug(TRAFFIC) logger(LOG_ERR, "Error while compressing packet to %s (%s)",
419                                    n->name, n->hostname);
420                         return;
421                 }
422
423                 inpkt = outpkt;
424         }
425
426         /* Add sequence number */
427
428         inpkt->seqno = htonl(++(n->sent_seqno));
429         inpkt->len += sizeof(inpkt->seqno);
430
431         /* Encrypt the packet */
432
433         if(n->outcipher) {
434                 outpkt = pkt[nextpkt++];
435
436                 if(!EVP_EncryptInit_ex(&n->outctx, NULL, NULL, NULL, NULL)
437                                 || !EVP_EncryptUpdate(&n->outctx, (unsigned char *) &outpkt->seqno, &outlen,
438                                         (unsigned char *) &inpkt->seqno, inpkt->len)
439                                 || !EVP_EncryptFinal_ex(&n->outctx, (unsigned char *) &outpkt->seqno + outlen, &outpad)) {
440                         ifdebug(TRAFFIC) logger(LOG_ERR, "Error while encrypting packet to %s (%s): %s",
441                                                 n->name, n->hostname, ERR_error_string(ERR_get_error(), NULL));
442                         goto end;
443                 }
444
445                 outpkt->len = outlen + outpad;
446                 inpkt = outpkt;
447         }
448
449         /* Add the message authentication code */
450
451         if(n->outdigest && n->outmaclength) {
452                 HMAC(n->outdigest, n->outkey, n->outkeylength, (unsigned char *) &inpkt->seqno,
453                          inpkt->len, (unsigned char *) &inpkt->seqno + inpkt->len, NULL);
454                 inpkt->len += n->outmaclength;
455         }
456
457         /* Determine which socket we have to use */
458
459         for(sock = 0; sock < listen_sockets; sock++)
460                 if(n->address.sa.sa_family == listen_socket[sock].sa.sa.sa_family)
461                         break;
462
463         if(sock >= listen_sockets)
464                 sock = 0;                               /* If none is available, just use the first and hope for the best. */
465
466         /* Send the packet */
467
468 #if defined(SOL_IP) && defined(IP_TOS)
469         if(priorityinheritance && origpriority != priority
470            && listen_socket[sock].sa.sa.sa_family == AF_INET) {
471                 priority = origpriority;
472                 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Setting outgoing packet priority to %d", priority);
473                 if(setsockopt(listen_socket[sock].udp, SOL_IP, IP_TOS, &priority, sizeof(priority)))    /* SO_PRIORITY doesn't seem to work */
474                         logger(LOG_ERR, "System call `%s' failed: %s", "setsockopt", strerror(errno));
475         }
476 #endif
477
478         if(sendto(listen_socket[sock].udp, (char *) &inpkt->seqno, inpkt->len, 0, &(n->address.sa), SALEN(n->address.sa)) < 0 && !sockwouldblock(sockerrno)) {
479                 if(sockmsgsize(sockerrno)) {
480                         if(n->maxmtu >= origlen)
481                                 n->maxmtu = origlen - 1;
482                         if(n->mtu >= origlen)
483                                 n->mtu = origlen - 1;
484                 } else
485                         logger(LOG_ERR, "Error sending packet to %s (%s): %s", n->name, n->hostname, sockstrerror(sockerrno));
486         }
487
488 end:
489         origpkt->len = origlen;
490 }
491
492 /*
493   send a packet to the given vpn ip.
494 */
495 void send_packet(const node_t *n, vpn_packet_t *packet) {
496         node_t *via;
497
498         if(n == myself) {
499                 if(overwrite_mac)
500                          memcpy(packet->data, mymac.x, ETH_ALEN);
501                 write_packet(packet);
502                 return;
503         }
504
505         ifdebug(TRAFFIC) logger(LOG_ERR, "Sending packet of %d bytes to %s (%s)",
506                            packet->len, n->name, n->hostname);
507
508         if(!n->status.reachable) {
509                 ifdebug(TRAFFIC) logger(LOG_INFO, "Node %s (%s) is not reachable",
510                                    n->name, n->hostname);
511                 return;
512         }
513
514         via = (packet->priority == -1 || n->via == myself) ? n->nexthop : n->via;
515
516         if(via != n)
517                 ifdebug(TRAFFIC) logger(LOG_INFO, "Sending packet to %s via %s (%s)",
518                            n->name, via->name, n->via->hostname);
519
520         if(packet->priority == -1 || ((myself->options | via->options) & OPTION_TCPONLY)) {
521                 if(!send_tcppacket(via->connection, packet))
522                         terminate_connection(via->connection, true);
523         } else
524                 send_udppacket(via, packet);
525 }
526
527 /* Broadcast a packet using the minimum spanning tree */
528
529 void broadcast_packet(const node_t *from, vpn_packet_t *packet) {
530         avl_node_t *node;
531         connection_t *c;
532
533         ifdebug(TRAFFIC) logger(LOG_INFO, "Broadcasting packet of %d bytes from %s (%s)",
534                            packet->len, from->name, from->hostname);
535
536         if(from != myself) {
537                 send_packet(myself, packet);
538
539                 // In TunnelServer mode, do not forward broadcast packets.
540                 // The MST might not be valid and create loops.
541                 if(tunnelserver)
542                         return;
543         }
544
545         for(node = connection_tree->head; node; node = node->next) {
546                 c = node->data;
547
548                 if(c->status.active && c->status.mst && c != from->nexthop->connection)
549                         send_packet(c->node, packet);
550         }
551 }
552
553 static node_t *try_harder(const sockaddr_t *from, const vpn_packet_t *pkt) {
554         avl_node_t *node;
555         edge_t *e;
556         node_t *n = NULL;
557         static time_t last_hard_try = 0;
558
559         for(node = edge_weight_tree->head; node; node = node->next) {
560                 e = node->data;
561
562                 if(sockaddrcmp_noport(from, &e->address)) {
563                         if(last_hard_try == now)
564                                 continue;
565                         last_hard_try = now;
566                 }
567
568                 if(!n)
569                         n = e->to;
570
571                 if(!try_mac(e->to, pkt))
572                         continue;
573
574                 n = e->to;
575                 break;
576         }
577
578         return n;
579 }
580
581 void handle_incoming_vpn_data(int sock) {
582         vpn_packet_t pkt;
583         char *hostname;
584         sockaddr_t from;
585         socklen_t fromlen = sizeof(from);
586         node_t *n;
587
588         pkt.len = recvfrom(sock, (char *) &pkt.seqno, MAXSIZE, 0, &from.sa, &fromlen);
589
590         if(pkt.len < 0) {
591                 if(!sockwouldblock(sockerrno))
592                         logger(LOG_ERR, "Receiving packet failed: %s", sockstrerror(sockerrno));
593                 return;
594         }
595
596         sockaddrunmap(&from);           /* Some braindead IPv6 implementations do stupid things. */
597
598         n = lookup_node_udp(&from);
599
600         if(!n) {
601                 n = try_harder(&from, &pkt);
602                 if(n)
603                         update_node_udp(n, &from);
604                 else ifdebug(PROTOCOL) {
605                         hostname = sockaddr2hostname(&from);
606                         logger(LOG_WARNING, "Received UDP packet from unknown source %s", hostname);
607                         free(hostname);
608                         return;
609                 }
610                 else
611                         return;
612         }
613
614         receive_udppacket(n, &pkt);
615 }