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