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