2 net_packet.c -- Handles in- and outgoing VPN packets
3 Copyright (C) 1998-2005 Ivo Timmermans,
4 2000-2012 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 three, with random sizes between the lower and
74 upper boundaries for the MTU thus far discovered.
76 In case local discovery is enabled, a fourth packet is added to each batch,
77 which will be broadcast to the local network.
80 void send_mtu_probe(node_t *n) {
88 if(!n->status.reachable || !n->status.validkey) {
89 ifdebug(TRAFFIC) logger(LOG_INFO, "Trying to send MTU probe to unreachable or rekeying node %s (%s)", n->name, n->hostname);
94 if(n->mtuprobes > 32) {
97 timeout = pinginterval;
101 ifdebug(TRAFFIC) logger(LOG_INFO, "%s (%s) did not respond to UDP ping, restarting PMTU discovery", n->name, n->hostname);
107 if(n->mtuprobes >= 10 && n->mtuprobes < 32 && !n->minmtu) {
108 ifdebug(TRAFFIC) logger(LOG_INFO, "No response to MTU probes from %s (%s)", n->name, n->hostname);
112 if(n->mtuprobes == 30 || (n->mtuprobes < 30 && n->minmtu >= n->maxmtu)) {
113 if(n->minmtu > n->maxmtu)
114 n->minmtu = n->maxmtu;
116 n->maxmtu = n->minmtu;
118 ifdebug(TRAFFIC) logger(LOG_INFO, "Fixing MTU of %s (%s) to %d after %d probes", n->name, n->hostname, n->mtu, n->mtuprobes);
122 if(n->mtuprobes == 31) {
123 timeout = pinginterval;
125 } else if(n->mtuprobes == 32) {
126 timeout = pingtimeout;
129 for(i = 0; i < 3 + localdiscovery; i++) {
130 if(n->maxmtu <= n->minmtu)
133 len = n->minmtu + 1 + rand() % (n->maxmtu - n->minmtu);
138 memset(packet.data, 0, 14);
139 RAND_pseudo_bytes(packet.data + 14, len - 14);
141 if(i >= 3 && n->mtuprobes <= 10)
142 packet.priority = -1;
146 ifdebug(TRAFFIC) logger(LOG_INFO, "Sending MTU probe length %d to %s (%s)", len, n->name, n->hostname);
148 send_udppacket(n, &packet);
152 n->mtuevent = new_event();
153 n->mtuevent->handler = (event_handler_t)send_mtu_probe;
154 n->mtuevent->data = n;
155 n->mtuevent->time = now + timeout;
156 event_add(n->mtuevent);
159 void mtu_probe_h(node_t *n, vpn_packet_t *packet, length_t len) {
160 ifdebug(TRAFFIC) logger(LOG_INFO, "Got MTU probe length %d from %s (%s)", packet->len, n->name, n->hostname);
162 if(!packet->data[0]) {
164 send_udppacket(n, packet);
166 if(n->mtuprobes > 30) {
180 static length_t compress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level) {
182 memcpy(dest, source, len);
184 } else if(level == 10) {
186 lzo_uint lzolen = MAXSIZE;
187 lzo1x_1_compress(source, len, dest, &lzolen, lzo_wrkmem);
192 } else if(level < 10) {
194 unsigned long destlen = MAXSIZE;
195 if(compress2(dest, &destlen, source, len, level) == Z_OK)
202 lzo_uint lzolen = MAXSIZE;
203 lzo1x_999_compress(source, len, dest, &lzolen, lzo_wrkmem);
213 static length_t uncompress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level) {
215 memcpy(dest, source, len);
217 } else if(level > 9) {
219 lzo_uint lzolen = MAXSIZE;
220 if(lzo1x_decompress_safe(source, len, dest, &lzolen, NULL) == LZO_E_OK)
228 unsigned long destlen = MAXSIZE;
229 if(uncompress(dest, &destlen, source, len) == Z_OK)
241 static void receive_packet(node_t *n, vpn_packet_t *packet) {
242 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Received packet of %d bytes from %s (%s)",
243 packet->len, n->name, n->hostname);
248 static bool try_mac(const node_t *n, const vpn_packet_t *inpkt) {
249 unsigned char hmac[EVP_MAX_MD_SIZE];
251 if(!n->indigest || !n->inmaclength || !n->inkey || inpkt->len < sizeof inpkt->seqno + n->inmaclength)
254 HMAC(n->indigest, n->inkey, n->inkeylength, (unsigned char *) &inpkt->seqno, inpkt->len - n->inmaclength, (unsigned char *)hmac, NULL);
256 return !memcmp(hmac, (char *) &inpkt->seqno + inpkt->len - n->inmaclength, n->inmaclength);
259 static void receive_udppacket(node_t *n, vpn_packet_t *inpkt) {
260 vpn_packet_t pkt1, pkt2;
261 vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
263 vpn_packet_t *outpkt = pkt[0];
265 unsigned char hmac[EVP_MAX_MD_SIZE];
269 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Got packet from %s (%s) but he hasn't got our key yet",
270 n->name, n->hostname);
274 /* Check packet length */
276 if(inpkt->len < sizeof(inpkt->seqno) + n->inmaclength) {
277 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Got too short packet from %s (%s)",
278 n->name, n->hostname);
282 /* Check the message authentication code */
284 if(n->indigest && n->inmaclength) {
285 inpkt->len -= n->inmaclength;
286 HMAC(n->indigest, n->inkey, n->inkeylength,
287 (unsigned char *) &inpkt->seqno, inpkt->len, (unsigned char *)hmac, NULL);
289 if(memcmp(hmac, (char *) &inpkt->seqno + inpkt->len, n->inmaclength)) {
290 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Got unauthenticated packet from %s (%s)",
291 n->name, n->hostname);
296 /* Decrypt the packet */
299 outpkt = pkt[nextpkt++];
301 if(!EVP_DecryptInit_ex(&n->inctx, NULL, NULL, NULL, NULL)
302 || !EVP_DecryptUpdate(&n->inctx, (unsigned char *) &outpkt->seqno, &outlen,
303 (unsigned char *) &inpkt->seqno, inpkt->len)
304 || !EVP_DecryptFinal_ex(&n->inctx, (unsigned char *) &outpkt->seqno + outlen, &outpad)) {
305 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Error decrypting packet from %s (%s): %s",
306 n->name, n->hostname, ERR_error_string(ERR_get_error(), NULL));
310 outpkt->len = outlen + outpad;
314 /* Check the sequence number */
316 inpkt->len -= sizeof(inpkt->seqno);
317 inpkt->seqno = ntohl(inpkt->seqno);
320 if(inpkt->seqno != n->received_seqno + 1) {
321 if(inpkt->seqno >= n->received_seqno + replaywin * 8) {
322 if(n->farfuture++ < replaywin >> 2) {
323 logger(LOG_WARNING, "Packet from %s (%s) is %d seqs in the future, dropped (%u)",
324 n->name, n->hostname, inpkt->seqno - n->received_seqno - 1, n->farfuture);
327 logger(LOG_WARNING, "Lost %d packets from %s (%s)",
328 inpkt->seqno - n->received_seqno - 1, n->name, n->hostname);
329 memset(n->late, 0, replaywin);
330 } else if (inpkt->seqno <= n->received_seqno) {
331 if((n->received_seqno >= replaywin * 8 && inpkt->seqno <= n->received_seqno - replaywin * 8) || !(n->late[(inpkt->seqno / 8) % replaywin] & (1 << inpkt->seqno % 8))) {
332 logger(LOG_WARNING, "Got late or replayed packet from %s (%s), seqno %d, last received %d",
333 n->name, n->hostname, inpkt->seqno, n->received_seqno);
337 for(i = n->received_seqno + 1; i < inpkt->seqno; i++)
338 n->late[(i / 8) % replaywin] |= 1 << i % 8;
343 n->late[(inpkt->seqno / 8) % replaywin] &= ~(1 << inpkt->seqno % 8);
346 if(inpkt->seqno > n->received_seqno)
347 n->received_seqno = inpkt->seqno;
349 if(n->received_seqno > MAX_SEQNO)
352 /* Decompress the packet */
354 length_t origlen = inpkt->len;
356 if(n->incompression) {
357 outpkt = pkt[nextpkt++];
359 if((outpkt->len = uncompress_packet(outpkt->data, inpkt->data, inpkt->len, n->incompression)) < 0) {
360 ifdebug(TRAFFIC) logger(LOG_ERR, "Error while uncompressing packet from %s (%s)",
361 n->name, n->hostname);
367 origlen -= MTU/64 + 20;
372 if(!inpkt->data[12] && !inpkt->data[13])
373 mtu_probe_h(n, inpkt, origlen);
375 receive_packet(n, inpkt);
378 void receive_tcppacket(connection_t *c, const char *buffer, int len) {
382 if(c->options & OPTION_TCPONLY)
385 outpkt.priority = -1;
386 memcpy(outpkt.data, buffer, len);
388 receive_packet(c->node, &outpkt);
391 static void send_udppacket(node_t *n, vpn_packet_t *origpkt) {
392 vpn_packet_t pkt1, pkt2;
393 vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
394 vpn_packet_t *inpkt = origpkt;
396 vpn_packet_t *outpkt;
399 #if defined(SOL_IP) && defined(IP_TOS)
400 static int priority = 0;
404 if(!n->status.reachable) {
405 ifdebug(TRAFFIC) logger(LOG_INFO, "Trying to send UDP packet to unreachable node %s (%s)", n->name, n->hostname);
409 /* Make sure we have a valid key */
411 if(!n->status.validkey) {
412 ifdebug(TRAFFIC) logger(LOG_INFO,
413 "No valid key known yet for %s (%s), forwarding via TCP",
414 n->name, n->hostname);
416 if(n->last_req_key + 10 <= now) {
418 n->last_req_key = now;
421 send_tcppacket(n->nexthop->connection, origpkt);
426 if(n->options & OPTION_PMTU_DISCOVERY && inpkt->len > n->minmtu && (inpkt->data[12] | inpkt->data[13])) {
427 ifdebug(TRAFFIC) logger(LOG_INFO,
428 "Packet for %s (%s) larger than minimum MTU, forwarding via %s",
429 n->name, n->hostname, n != n->nexthop ? n->nexthop->name : "TCP");
432 send_packet(n->nexthop, origpkt);
434 send_tcppacket(n->nexthop->connection, origpkt);
439 origlen = inpkt->len;
440 origpriority = inpkt->priority;
442 /* Compress the packet */
444 if(n->outcompression) {
445 outpkt = pkt[nextpkt++];
447 if((outpkt->len = compress_packet(outpkt->data, inpkt->data, inpkt->len, n->outcompression)) < 0) {
448 ifdebug(TRAFFIC) logger(LOG_ERR, "Error while compressing packet to %s (%s)",
449 n->name, n->hostname);
456 /* Add sequence number */
458 inpkt->seqno = htonl(++(n->sent_seqno));
459 inpkt->len += sizeof(inpkt->seqno);
461 /* Encrypt the packet */
464 outpkt = pkt[nextpkt++];
466 if(!EVP_EncryptInit_ex(&n->outctx, NULL, NULL, NULL, NULL)
467 || !EVP_EncryptUpdate(&n->outctx, (unsigned char *) &outpkt->seqno, &outlen,
468 (unsigned char *) &inpkt->seqno, inpkt->len)
469 || !EVP_EncryptFinal_ex(&n->outctx, (unsigned char *) &outpkt->seqno + outlen, &outpad)) {
470 ifdebug(TRAFFIC) logger(LOG_ERR, "Error while encrypting packet to %s (%s): %s",
471 n->name, n->hostname, ERR_error_string(ERR_get_error(), NULL));
475 outpkt->len = outlen + outpad;
479 /* Add the message authentication code */
481 if(n->outdigest && n->outmaclength) {
482 HMAC(n->outdigest, n->outkey, n->outkeylength, (unsigned char *) &inpkt->seqno,
483 inpkt->len, (unsigned char *) &inpkt->seqno + inpkt->len, NULL);
484 inpkt->len += n->outmaclength;
487 /* Determine which socket we have to use */
489 if(n->address.sa.sa_family != listen_socket[n->sock].sa.sa.sa_family) {
490 for(int sock = 0; sock < listen_sockets; sock++) {
491 if(n->address.sa.sa_family == listen_socket[sock].sa.sa.sa_family) {
498 /* Send the packet */
503 sockaddr_t broadcast;
505 /* Overloaded use of priority field: -1 means local broadcast */
507 if(origpriority == -1 && n->prevedge) {
508 sock = rand() % listen_sockets;
509 memset(&broadcast, 0, sizeof broadcast);
510 if(listen_socket[sock].sa.sa.sa_family == AF_INET6) {
511 broadcast.in6.sin6_family = AF_INET6;
512 broadcast.in6.sin6_addr.s6_addr[0x0] = 0xff;
513 broadcast.in6.sin6_addr.s6_addr[0x1] = 0x02;
514 broadcast.in6.sin6_addr.s6_addr[0xf] = 0x01;
515 broadcast.in6.sin6_port = n->prevedge->address.in.sin_port;
516 broadcast.in6.sin6_scope_id = listen_socket[sock].sa.in6.sin6_scope_id;
518 broadcast.in.sin_family = AF_INET;
519 broadcast.in.sin_addr.s_addr = -1;
520 broadcast.in.sin_port = n->prevedge->address.in.sin_port;
523 sl = SALEN(broadcast.sa);
525 if(origpriority == -1)
528 sa = &(n->address.sa);
529 sl = SALEN(n->address.sa);
533 #if defined(SOL_IP) && defined(IP_TOS)
534 if(priorityinheritance && origpriority != priority
535 && listen_socket[n->sock].sa.sa.sa_family == AF_INET) {
536 priority = origpriority;
537 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Setting outgoing packet priority to %d", priority);
538 if(setsockopt(listen_socket[n->sock].udp, SOL_IP, IP_TOS, &priority, sizeof(priority))) /* SO_PRIORITY doesn't seem to work */
539 logger(LOG_ERR, "System call `%s' failed: %s", "setsockopt", strerror(errno));
543 if(sendto(listen_socket[sock].udp, (char *) &inpkt->seqno, inpkt->len, 0, sa, sl) < 0 && !sockwouldblock(sockerrno)) {
544 if(sockmsgsize(sockerrno)) {
545 if(n->maxmtu >= origlen)
546 n->maxmtu = origlen - 1;
547 if(n->mtu >= origlen)
548 n->mtu = origlen - 1;
550 ifdebug(TRAFFIC) logger(LOG_WARNING, "Error sending packet to %s (%s): %s", n->name, n->hostname, sockstrerror(sockerrno));
554 origpkt->len = origlen;
558 send a packet to the given vpn ip.
560 void send_packet(const node_t *n, vpn_packet_t *packet) {
565 memcpy(packet->data, mymac.x, ETH_ALEN);
566 devops.write(packet);
570 ifdebug(TRAFFIC) logger(LOG_ERR, "Sending packet of %d bytes to %s (%s)",
571 packet->len, n->name, n->hostname);
573 if(!n->status.reachable) {
574 ifdebug(TRAFFIC) logger(LOG_INFO, "Node %s (%s) is not reachable",
575 n->name, n->hostname);
579 via = (packet->priority == -1 || n->via == myself) ? n->nexthop : n->via;
582 ifdebug(TRAFFIC) logger(LOG_INFO, "Sending packet to %s via %s (%s)",
583 n->name, via->name, n->via->hostname);
585 if(packet->priority == -1 || ((myself->options | via->options) & OPTION_TCPONLY)) {
586 if(!send_tcppacket(via->connection, packet))
587 terminate_connection(via->connection, true);
589 send_udppacket(via, packet);
592 /* Broadcast a packet using the minimum spanning tree */
594 void broadcast_packet(const node_t *from, vpn_packet_t *packet) {
599 // Always give ourself a copy of the packet.
601 send_packet(myself, packet);
603 // In TunnelServer mode, do not forward broadcast packets.
604 // The MST might not be valid and create loops.
605 if(tunnelserver || broadcast_mode == BMODE_NONE)
608 ifdebug(TRAFFIC) logger(LOG_INFO, "Broadcasting packet of %d bytes from %s (%s)",
609 packet->len, from->name, from->hostname);
611 switch(broadcast_mode) {
612 // In MST mode, broadcast packets travel via the Minimum Spanning Tree.
613 // This guarantees all nodes receive the broadcast packet, and
614 // usually distributes the sending of broadcast packets over all nodes.
616 for(node = connection_tree->head; node; node = node->next) {
619 if(c->status.active && c->status.mst && c != from->nexthop->connection)
620 send_packet(c->node, packet);
624 // In direct mode, we send copies to each node we know of.
625 // However, this only reaches nodes that can be reached in a single hop.
626 // We don't have enough information to forward broadcast packets in this case.
631 for(node = node_udp_tree->head; node; node = node->next) {
634 if(n->status.reachable && ((n->via == myself && n->nexthop == n) || n->via == n))
635 send_packet(n, packet);
644 static node_t *try_harder(const sockaddr_t *from, const vpn_packet_t *pkt) {
649 static time_t last_hard_try = 0;
651 for(node = edge_weight_tree->head; node; node = node->next) {
657 if(sockaddrcmp_noport(from, &e->address)) {
658 if(last_hard_try == now)
663 if(!try_mac(e->to, pkt))
677 void handle_incoming_vpn_data(int sock) {
681 socklen_t fromlen = sizeof(from);
684 pkt.len = recvfrom(listen_socket[sock].udp, (char *) &pkt.seqno, MAXSIZE, 0, &from.sa, &fromlen);
687 if(!sockwouldblock(sockerrno))
688 logger(LOG_ERR, "Receiving packet failed: %s", sockstrerror(sockerrno));
692 sockaddrunmap(&from); /* Some braindead IPv6 implementations do stupid things. */
694 n = lookup_node_udp(&from);
697 n = try_harder(&from, &pkt);
699 update_node_udp(n, &from);
700 else ifdebug(PROTOCOL) {
701 hostname = sockaddr2hostname(&from);
702 logger(LOG_WARNING, "Received UDP packet from unknown source %s", hostname);
712 receive_udppacket(n, &pkt);