2 net_packet.c -- Handles in- and outgoing VPN packets
3 Copyright (C) 1998-2005 Ivo Timmermans,
4 2000-2015 Guus Sliepen <guus@tinc-vpn.org>
5 2010 Timothy Redaelli <timothy@redaelli.eu>
6 2010 Brandon Black <blblack@gmail.com>
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.
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.
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.
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>
41 #include "connection.h"
58 static char lzo_wrkmem[LZO1X_999_MEM_COMPRESS > LZO1X_1_MEM_COMPRESS ? LZO1X_999_MEM_COMPRESS : LZO1X_1_MEM_COMPRESS];
61 static void send_udppacket(node_t *, vpn_packet_t *);
63 unsigned replaywin = 16;
64 bool localdiscovery = false;
66 #define MAX_SEQNO 1073741824
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
73 Probes are sent in batches of at least three, with random sizes between the
74 lower and upper boundaries for the MTU thus far discovered.
76 After the initial discovery, a fourth packet is added to each batch with a
77 size larger than the currently known PMTU, to test if the PMTU has increased.
79 In case local discovery is enabled, another packet is added to each batch,
80 which will be broadcast to the local network.
84 void send_mtu_probe(node_t *n) {
92 if(!n->status.reachable || !n->status.validkey) {
93 ifdebug(TRAFFIC) logger(LOG_INFO, "Trying to send MTU probe to unreachable or rekeying node %s (%s)", n->name, n->hostname);
98 if(n->mtuprobes > 32) {
101 timeout = pinginterval;
105 ifdebug(TRAFFIC) logger(LOG_INFO, "%s (%s) did not respond to UDP ping, restarting PMTU discovery", n->name, n->hostname);
111 if(n->mtuprobes >= 10 && n->mtuprobes < 32 && !n->minmtu) {
112 ifdebug(TRAFFIC) logger(LOG_INFO, "No response to MTU probes from %s (%s)", n->name, n->hostname);
116 if(n->mtuprobes == 30 || (n->mtuprobes < 30 && n->minmtu >= n->maxmtu)) {
117 if(n->minmtu > n->maxmtu)
118 n->minmtu = n->maxmtu;
120 n->maxmtu = n->minmtu;
122 ifdebug(TRAFFIC) logger(LOG_INFO, "Fixing MTU of %s (%s) to %d after %d probes", n->name, n->hostname, n->mtu, n->mtuprobes);
126 if(n->mtuprobes == 31) {
127 timeout = pinginterval;
129 } else if(n->mtuprobes == 32) {
130 timeout = pingtimeout;
133 for(i = 0; i < 4 + localdiscovery; i++) {
135 if(n->mtuprobes < 30 || n->maxmtu + 8 >= MTU)
138 } else if(n->maxmtu <= n->minmtu) {
141 len = n->minmtu + 1 + rand() % (n->maxmtu - n->minmtu);
147 memset(packet.data, 0, 14);
148 RAND_pseudo_bytes(packet.data + 14, len - 14);
150 if(i >= 4 && n->mtuprobes <= 10)
151 packet.priority = -1;
155 ifdebug(TRAFFIC) logger(LOG_INFO, "Sending MTU probe length %d to %s (%s)", len, n->name, n->hostname);
157 send_udppacket(n, &packet);
161 n->mtuevent = new_event();
162 n->mtuevent->handler = (event_handler_t)send_mtu_probe;
163 n->mtuevent->data = n;
164 n->mtuevent->time = now + timeout;
165 event_add(n->mtuevent);
168 void mtu_probe_h(node_t *n, vpn_packet_t *packet, length_t len) {
169 ifdebug(TRAFFIC) logger(LOG_INFO, "Got MTU probe length %d from %s (%s)", packet->len, n->name, n->hostname);
171 if(!packet->data[0]) {
173 send_udppacket(n, packet);
175 if(n->mtuprobes > 30) {
176 if (len == n->maxmtu + 8) {
177 ifdebug(TRAFFIC) logger(LOG_INFO, "Increase in PMTU to %s (%s) detected, restarting PMTU discovery", n->name, n->hostname);
196 static length_t compress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level) {
198 memcpy(dest, source, len);
200 } else if(level == 10) {
202 lzo_uint lzolen = MAXSIZE;
203 lzo1x_1_compress(source, len, dest, &lzolen, lzo_wrkmem);
208 } else if(level < 10) {
210 unsigned long destlen = MAXSIZE;
211 if(compress2(dest, &destlen, source, len, level) == Z_OK)
218 lzo_uint lzolen = MAXSIZE;
219 lzo1x_999_compress(source, len, dest, &lzolen, lzo_wrkmem);
229 static length_t uncompress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level) {
231 memcpy(dest, source, len);
233 } else if(level > 9) {
235 lzo_uint lzolen = MAXSIZE;
236 if(lzo1x_decompress_safe(source, len, dest, &lzolen, NULL) == LZO_E_OK)
244 unsigned long destlen = MAXSIZE;
245 if(uncompress(dest, &destlen, source, len) == Z_OK)
257 static void receive_packet(node_t *n, vpn_packet_t *packet) {
258 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Received packet of %d bytes from %s (%s)",
259 packet->len, n->name, n->hostname);
264 static bool try_mac(const node_t *n, const vpn_packet_t *inpkt) {
265 unsigned char hmac[EVP_MAX_MD_SIZE];
267 if(!n->indigest || !n->inmaclength || !n->inkey || inpkt->len < sizeof inpkt->seqno + n->inmaclength)
270 HMAC(n->indigest, n->inkey, n->inkeylength, (unsigned char *) &inpkt->seqno, inpkt->len - n->inmaclength, (unsigned char *)hmac, NULL);
272 return !memcmp_constant_time(hmac, (char *) &inpkt->seqno + inpkt->len - n->inmaclength, n->inmaclength);
275 static void receive_udppacket(node_t *n, vpn_packet_t *inpkt) {
276 vpn_packet_t pkt1, pkt2;
277 vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
279 vpn_packet_t *outpkt;
281 unsigned char hmac[EVP_MAX_MD_SIZE];
285 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Got packet from %s (%s) but he hasn't got our key yet",
286 n->name, n->hostname);
290 /* Check packet length */
292 if(inpkt->len < sizeof(inpkt->seqno) + n->inmaclength) {
293 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Got too short packet from %s (%s)",
294 n->name, n->hostname);
298 /* Check the message authentication code */
300 if(n->indigest && n->inmaclength) {
301 inpkt->len -= n->inmaclength;
302 HMAC(n->indigest, n->inkey, n->inkeylength,
303 (unsigned char *) &inpkt->seqno, inpkt->len, (unsigned char *)hmac, NULL);
305 if(memcmp_constant_time(hmac, (char *) &inpkt->seqno + inpkt->len, n->inmaclength)) {
306 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Got unauthenticated packet from %s (%s)",
307 n->name, n->hostname);
312 /* Decrypt the packet */
315 outpkt = pkt[nextpkt++];
317 if(!EVP_DecryptInit_ex(&n->inctx, NULL, NULL, NULL, NULL)
318 || !EVP_DecryptUpdate(&n->inctx, (unsigned char *) &outpkt->seqno, &outlen,
319 (unsigned char *) &inpkt->seqno, inpkt->len)
320 || !EVP_DecryptFinal_ex(&n->inctx, (unsigned char *) &outpkt->seqno + outlen, &outpad)) {
321 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Error decrypting packet from %s (%s): %s",
322 n->name, n->hostname, ERR_error_string(ERR_get_error(), NULL));
326 outpkt->len = outlen + outpad;
330 /* Check the sequence number */
332 inpkt->len -= sizeof(inpkt->seqno);
333 inpkt->seqno = ntohl(inpkt->seqno);
336 if(inpkt->seqno != n->received_seqno + 1) {
337 if(inpkt->seqno >= n->received_seqno + replaywin * 8) {
338 if(n->farfuture++ < replaywin >> 2) {
339 logger(LOG_WARNING, "Packet from %s (%s) is %d seqs in the future, dropped (%u)",
340 n->name, n->hostname, inpkt->seqno - n->received_seqno - 1, n->farfuture);
343 logger(LOG_WARNING, "Lost %d packets from %s (%s)",
344 inpkt->seqno - n->received_seqno - 1, n->name, n->hostname);
345 memset(n->late, 0, replaywin);
346 } else if (inpkt->seqno <= n->received_seqno) {
347 if((n->received_seqno >= replaywin * 8 && inpkt->seqno <= n->received_seqno - replaywin * 8) || !(n->late[(inpkt->seqno / 8) % replaywin] & (1 << inpkt->seqno % 8))) {
348 logger(LOG_WARNING, "Got late or replayed packet from %s (%s), seqno %d, last received %d",
349 n->name, n->hostname, inpkt->seqno, n->received_seqno);
353 for(i = n->received_seqno + 1; i < inpkt->seqno; i++)
354 n->late[(i / 8) % replaywin] |= 1 << i % 8;
359 n->late[(inpkt->seqno / 8) % replaywin] &= ~(1 << inpkt->seqno % 8);
362 if(inpkt->seqno > n->received_seqno)
363 n->received_seqno = inpkt->seqno;
365 if(n->received_seqno > MAX_SEQNO)
368 /* Decompress the packet */
370 length_t origlen = inpkt->len;
372 if(n->incompression) {
373 outpkt = pkt[nextpkt++];
375 if((outpkt->len = uncompress_packet(outpkt->data, inpkt->data, inpkt->len, n->incompression)) < 0) {
376 ifdebug(TRAFFIC) logger(LOG_ERR, "Error while uncompressing packet from %s (%s)",
377 n->name, n->hostname);
383 origlen -= MTU/64 + 20;
388 if(!inpkt->data[12] && !inpkt->data[13])
389 mtu_probe_h(n, inpkt, origlen);
391 receive_packet(n, inpkt);
394 void receive_tcppacket(connection_t *c, const char *buffer, int len) {
397 if(len > sizeof outpkt.data)
401 if(c->options & OPTION_TCPONLY)
404 outpkt.priority = -1;
405 memcpy(outpkt.data, buffer, len);
407 receive_packet(c->node, &outpkt);
410 static void send_udppacket(node_t *n, vpn_packet_t *origpkt) {
411 vpn_packet_t pkt1, pkt2;
412 vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
413 vpn_packet_t *inpkt = origpkt;
415 vpn_packet_t *outpkt;
420 if(!n->status.reachable) {
421 ifdebug(TRAFFIC) logger(LOG_INFO, "Trying to send UDP packet to unreachable node %s (%s)", n->name, n->hostname);
425 /* Make sure we have a valid key */
427 if(!n->status.validkey) {
428 ifdebug(TRAFFIC) logger(LOG_INFO,
429 "No valid key known yet for %s (%s), forwarding via TCP",
430 n->name, n->hostname);
432 if(n->last_req_key + 10 <= now) {
434 n->last_req_key = now;
437 send_tcppacket(n->nexthop->connection, origpkt);
442 if(n->options & OPTION_PMTU_DISCOVERY && inpkt->len > n->minmtu && (inpkt->data[12] | inpkt->data[13])) {
443 ifdebug(TRAFFIC) logger(LOG_INFO,
444 "Packet for %s (%s) larger than minimum MTU, forwarding via %s",
445 n->name, n->hostname, n != n->nexthop ? n->nexthop->name : "TCP");
448 send_packet(n->nexthop, origpkt);
450 send_tcppacket(n->nexthop->connection, origpkt);
455 origlen = inpkt->len;
456 origpriority = inpkt->priority;
458 /* Compress the packet */
460 if(n->outcompression) {
461 outpkt = pkt[nextpkt++];
463 if((outpkt->len = compress_packet(outpkt->data, inpkt->data, inpkt->len, n->outcompression)) < 0) {
464 ifdebug(TRAFFIC) logger(LOG_ERR, "Error while compressing packet to %s (%s)",
465 n->name, n->hostname);
472 /* Add sequence number */
474 inpkt->seqno = htonl(++(n->sent_seqno));
475 inpkt->len += sizeof(inpkt->seqno);
477 /* Encrypt the packet */
480 outpkt = pkt[nextpkt++];
482 if(!EVP_EncryptInit_ex(&n->outctx, NULL, NULL, NULL, NULL)
483 || !EVP_EncryptUpdate(&n->outctx, (unsigned char *) &outpkt->seqno, &outlen,
484 (unsigned char *) &inpkt->seqno, inpkt->len)
485 || !EVP_EncryptFinal_ex(&n->outctx, (unsigned char *) &outpkt->seqno + outlen, &outpad)) {
486 ifdebug(TRAFFIC) logger(LOG_ERR, "Error while encrypting packet to %s (%s): %s",
487 n->name, n->hostname, ERR_error_string(ERR_get_error(), NULL));
491 outpkt->len = outlen + outpad;
495 /* Add the message authentication code */
497 if(n->outdigest && n->outmaclength) {
498 HMAC(n->outdigest, n->outkey, n->outkeylength, (unsigned char *) &inpkt->seqno,
499 inpkt->len, (unsigned char *) &inpkt->seqno + inpkt->len, NULL);
500 inpkt->len += n->outmaclength;
503 /* Determine which socket we have to use */
505 if(n->address.sa.sa_family != listen_socket[n->sock].sa.sa.sa_family) {
506 for(int sock = 0; sock < listen_sockets; sock++) {
507 if(n->address.sa.sa_family == listen_socket[sock].sa.sa.sa_family) {
514 /* Send the packet */
519 sockaddr_t broadcast;
521 /* Overloaded use of priority field: -1 means local broadcast */
523 if(origpriority == -1 && n->prevedge) {
524 sock = rand() % listen_sockets;
525 memset(&broadcast, 0, sizeof broadcast);
526 if(listen_socket[sock].sa.sa.sa_family == AF_INET6) {
527 broadcast.in6.sin6_family = AF_INET6;
528 broadcast.in6.sin6_addr.s6_addr[0x0] = 0xff;
529 broadcast.in6.sin6_addr.s6_addr[0x1] = 0x02;
530 broadcast.in6.sin6_addr.s6_addr[0xf] = 0x01;
531 broadcast.in6.sin6_port = n->prevedge->address.in.sin_port;
532 broadcast.in6.sin6_scope_id = listen_socket[sock].sa.in6.sin6_scope_id;
534 broadcast.in.sin_family = AF_INET;
535 broadcast.in.sin_addr.s_addr = -1;
536 broadcast.in.sin_port = n->prevedge->address.in.sin_port;
539 sl = SALEN(broadcast.sa);
541 if(origpriority == -1)
544 sa = &(n->address.sa);
545 sl = SALEN(n->address.sa);
549 if(priorityinheritance && origpriority != listen_socket[n->sock].priority) {
550 listen_socket[n->sock].priority = origpriority;
551 switch(listen_socket[n->sock].sa.sa.sa_family) {
552 #if defined(SOL_IP) && defined(IP_TOS)
554 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Setting IPv4 outgoing packet priority to %d", origpriority);
555 if(setsockopt(listen_socket[n->sock].udp, SOL_IP, IP_TOS, (void *)&origpriority, sizeof(origpriority))) /* SO_PRIORITY doesn't seem to work */
556 logger(LOG_ERR, "System call `%s' failed: %s", "setsockopt", strerror(errno));
559 #if defined(IPPROTO_IPV6) && defined(IPV6_TCLASS)
561 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Setting IPv6 outgoing packet priority to %d", origpriority);
562 if(setsockopt(listen_socket[n->sock].udp, IPPROTO_IPV6, IPV6_TCLASS, (void *)&origpriority, sizeof(origpriority)))
563 logger(LOG_ERR, "System call `%s' failed: %s", "setsockopt", strerror(errno));
571 if(sendto(listen_socket[sock].udp, (char *) &inpkt->seqno, inpkt->len, 0, sa, sl) < 0 && !sockwouldblock(sockerrno)) {
572 if(sockmsgsize(sockerrno)) {
573 if(n->maxmtu >= origlen)
574 n->maxmtu = origlen - 1;
575 if(n->mtu >= origlen)
576 n->mtu = origlen - 1;
578 ifdebug(TRAFFIC) logger(LOG_WARNING, "Error sending packet to %s (%s): %s", n->name, n->hostname, sockstrerror(sockerrno));
582 origpkt->len = origlen;
586 send a packet to the given vpn ip.
588 void send_packet(const node_t *n, vpn_packet_t *packet) {
593 memcpy(packet->data, mymac.x, ETH_ALEN);
594 devops.write(packet);
598 ifdebug(TRAFFIC) logger(LOG_ERR, "Sending packet of %d bytes to %s (%s)",
599 packet->len, n->name, n->hostname);
601 if(!n->status.reachable) {
602 ifdebug(TRAFFIC) logger(LOG_INFO, "Node %s (%s) is not reachable",
603 n->name, n->hostname);
607 via = (packet->priority == -1 || n->via == myself) ? n->nexthop : n->via;
610 ifdebug(TRAFFIC) logger(LOG_INFO, "Sending packet to %s via %s (%s)",
611 n->name, via->name, n->via->hostname);
613 if(packet->priority == -1 || ((myself->options | via->options) & OPTION_TCPONLY)) {
614 if(!send_tcppacket(via->connection, packet))
615 terminate_connection(via->connection, true);
617 send_udppacket(via, packet);
620 /* Broadcast a packet using the minimum spanning tree */
622 void broadcast_packet(const node_t *from, vpn_packet_t *packet) {
627 // Always give ourself a copy of the packet.
629 send_packet(myself, packet);
631 // In TunnelServer mode, do not forward broadcast packets.
632 // The MST might not be valid and create loops.
633 if(tunnelserver || broadcast_mode == BMODE_NONE)
636 ifdebug(TRAFFIC) logger(LOG_INFO, "Broadcasting packet of %d bytes from %s (%s)",
637 packet->len, from->name, from->hostname);
639 switch(broadcast_mode) {
640 // In MST mode, broadcast packets travel via the Minimum Spanning Tree.
641 // This guarantees all nodes receive the broadcast packet, and
642 // usually distributes the sending of broadcast packets over all nodes.
644 for(node = connection_tree->head; node; node = node->next) {
647 if(c->status.active && c->status.mst && c != from->nexthop->connection)
648 send_packet(c->node, packet);
652 // In direct mode, we send copies to each node we know of.
653 // However, this only reaches nodes that can be reached in a single hop.
654 // We don't have enough information to forward broadcast packets in this case.
659 for(node = node_udp_tree->head; node; node = node->next) {
662 if(n->status.reachable && n != myself && ((n->via == myself && n->nexthop == n) || n->via == n))
663 send_packet(n, packet);
672 static node_t *try_harder(const sockaddr_t *from, const vpn_packet_t *pkt) {
676 static time_t last_hard_try = 0;
678 for(node = edge_weight_tree->head; node; node = node->next) {
684 if(last_hard_try == now && sockaddrcmp_noport(from, &e->address))
687 if(!try_mac(e->to, pkt))
698 void handle_incoming_vpn_data(int sock) {
702 socklen_t fromlen = sizeof(from);
705 pkt.len = recvfrom(listen_socket[sock].udp, (char *) &pkt.seqno, MAXSIZE, 0, &from.sa, &fromlen);
708 if(!sockwouldblock(sockerrno))
709 logger(LOG_ERR, "Receiving packet failed: %s", sockstrerror(sockerrno));
713 sockaddrunmap(&from); /* Some braindead IPv6 implementations do stupid things. */
715 n = lookup_node_udp(&from);
718 n = try_harder(&from, &pkt);
720 update_node_udp(n, &from);
721 else ifdebug(PROTOCOL) {
722 hostname = sockaddr2hostname(&from);
723 logger(LOG_WARNING, "Received UDP packet from unknown source %s", hostname);
733 receive_udppacket(n, &pkt);