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>
39 #include "splay_tree.h"
42 #include "connection.h"
59 static char lzo_wrkmem[LZO1X_999_MEM_COMPRESS > LZO1X_1_MEM_COMPRESS ? LZO1X_999_MEM_COMPRESS : LZO1X_1_MEM_COMPRESS];
62 static void send_udppacket(node_t *, vpn_packet_t *);
64 unsigned replaywin = 16;
65 bool localdiscovery = false;
67 #define MAX_SEQNO 1073741824
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
74 Probes are sent in batches of three, with random sizes between the lower and
75 upper boundaries for the MTU thus far discovered.
77 In case local discovery is enabled, a fourth packet is added to each batch,
78 which will be broadcast to the local network.
81 static void send_mtu_probe_handler(int fd, short events, void *data) {
89 if(!n->status.reachable || !n->status.validkey) {
90 logger(DEBUG_TRAFFIC, LOG_INFO, "Trying to send MTU probe to unreachable or rekeying node %s (%s)", n->name, n->hostname);
95 if(n->mtuprobes > 32) {
98 timeout = pinginterval;
102 logger(DEBUG_TRAFFIC, LOG_INFO, "%s (%s) did not respond to UDP ping, restarting PMTU discovery", n->name, n->hostname);
108 if(n->mtuprobes >= 10 && n->mtuprobes < 32 && !n->minmtu) {
109 logger(DEBUG_TRAFFIC, LOG_INFO, "No response to MTU probes from %s (%s)", n->name, n->hostname);
113 if(n->mtuprobes == 30 || (n->mtuprobes < 30 && n->minmtu >= n->maxmtu)) {
114 if(n->minmtu > n->maxmtu)
115 n->minmtu = n->maxmtu;
117 n->maxmtu = n->minmtu;
119 logger(DEBUG_TRAFFIC, LOG_INFO, "Fixing MTU of %s (%s) to %d after %d probes", n->name, n->hostname, n->mtu, n->mtuprobes);
123 if(n->mtuprobes == 31) {
124 timeout = pinginterval;
126 } else if(n->mtuprobes == 32) {
127 timeout = pingtimeout;
130 for(i = 0; i < 3 + localdiscovery; i++) {
131 if(n->maxmtu <= n->minmtu)
134 len = n->minmtu + 1 + rand() % (n->maxmtu - n->minmtu);
139 memset(packet.data, 0, 14);
140 randomize(packet.data + 14, len - 14);
142 if(i >= 3 && n->mtuprobes <= 10)
143 packet.priority = -1;
147 logger(DEBUG_TRAFFIC, LOG_INFO, "Sending MTU probe length %d to %s (%s)", len, n->name, n->hostname);
149 send_udppacket(n, &packet);
153 event_add(&n->mtuevent, &(struct timeval){timeout, 0});
156 void send_mtu_probe(node_t *n) {
157 if(!timeout_initialized(&n->mtuevent))
158 timeout_set(&n->mtuevent, send_mtu_probe_handler, n);
159 send_mtu_probe_handler(0, 0, n);
162 static void mtu_probe_h(node_t *n, vpn_packet_t *packet, length_t len) {
163 logger(DEBUG_TRAFFIC, LOG_INFO, "Got MTU probe length %d from %s (%s)", packet->len, n->name, n->hostname);
165 if(!packet->data[0]) {
167 send_udppacket(n, packet);
169 if(n->mtuprobes > 30) {
183 static length_t compress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level) {
185 memcpy(dest, source, len);
187 } else if(level == 10) {
189 lzo_uint lzolen = MAXSIZE;
190 lzo1x_1_compress(source, len, dest, &lzolen, lzo_wrkmem);
195 } else if(level < 10) {
197 unsigned long destlen = MAXSIZE;
198 if(compress2(dest, &destlen, source, len, level) == Z_OK)
205 lzo_uint lzolen = MAXSIZE;
206 lzo1x_999_compress(source, len, dest, &lzolen, lzo_wrkmem);
216 static length_t uncompress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level) {
218 memcpy(dest, source, len);
220 } else if(level > 9) {
222 lzo_uint lzolen = MAXSIZE;
223 if(lzo1x_decompress_safe(source, len, dest, &lzolen, NULL) == LZO_E_OK)
231 unsigned long destlen = MAXSIZE;
232 if(uncompress(dest, &destlen, source, len) == Z_OK)
244 static void receive_packet(node_t *n, vpn_packet_t *packet) {
245 logger(DEBUG_TRAFFIC, LOG_DEBUG, "Received packet of %d bytes from %s (%s)",
246 packet->len, n->name, n->hostname);
249 n->in_bytes += packet->len;
254 static bool try_mac(node_t *n, const vpn_packet_t *inpkt) {
255 if(!digest_active(&n->indigest) || inpkt->len < sizeof inpkt->seqno + digest_length(&n->indigest))
258 return digest_verify(&n->indigest, &inpkt->seqno, inpkt->len - n->indigest.maclength, (const char *)&inpkt->seqno + inpkt->len - n->indigest.maclength);
261 static void receive_udppacket(node_t *n, vpn_packet_t *inpkt) {
262 vpn_packet_t pkt1, pkt2;
263 vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
265 vpn_packet_t *outpkt = pkt[0];
268 if(experimental && OPTION_VERSION(n->options) >= 2) {
269 sptps_receive_data(&n->sptps, (char *)inpkt->data - 4, inpkt->len);
273 if(!cipher_active(&n->incipher)) {
274 logger(DEBUG_TRAFFIC, LOG_DEBUG, "Got packet from %s (%s) but he hasn't got our key yet",
275 n->name, n->hostname);
279 /* Check packet length */
281 if(inpkt->len < sizeof inpkt->seqno + digest_length(&n->indigest)) {
282 logger(DEBUG_TRAFFIC, LOG_DEBUG, "Got too short packet from %s (%s)",
283 n->name, n->hostname);
287 /* Check the message authentication code */
289 if(digest_active(&n->indigest)) {
290 inpkt->len -= n->indigest.maclength;
291 if(!digest_verify(&n->indigest, &inpkt->seqno, inpkt->len, (const char *)&inpkt->seqno + inpkt->len)) {
292 logger(DEBUG_TRAFFIC, LOG_DEBUG, "Got unauthenticated packet from %s (%s)", n->name, n->hostname);
296 /* Decrypt the packet */
298 if(cipher_active(&n->incipher)) {
299 outpkt = pkt[nextpkt++];
302 if(!cipher_decrypt(&n->incipher, &inpkt->seqno, inpkt->len, &outpkt->seqno, &outlen, true)) {
303 logger(DEBUG_TRAFFIC, LOG_DEBUG, "Error decrypting packet from %s (%s)", n->name, n->hostname);
307 outpkt->len = outlen;
311 /* Check the sequence number */
313 inpkt->len -= sizeof inpkt->seqno;
314 inpkt->seqno = ntohl(inpkt->seqno);
317 if(inpkt->seqno != n->received_seqno + 1) {
318 if(inpkt->seqno >= n->received_seqno + replaywin * 8) {
319 if(n->farfuture++ < replaywin >> 2) {
320 logger(DEBUG_ALWAYS, LOG_WARNING, "Packet from %s (%s) is %d seqs in the future, dropped (%u)",
321 n->name, n->hostname, inpkt->seqno - n->received_seqno - 1, n->farfuture);
324 logger(DEBUG_ALWAYS, LOG_WARNING, "Lost %d packets from %s (%s)",
325 inpkt->seqno - n->received_seqno - 1, n->name, n->hostname);
326 memset(n->late, 0, replaywin);
327 } else if (inpkt->seqno <= n->received_seqno) {
328 if((n->received_seqno >= replaywin * 8 && inpkt->seqno <= n->received_seqno - replaywin * 8) || !(n->late[(inpkt->seqno / 8) % replaywin] & (1 << inpkt->seqno % 8))) {
329 logger(DEBUG_ALWAYS, LOG_WARNING, "Got late or replayed packet from %s (%s), seqno %d, last received %d",
330 n->name, n->hostname, inpkt->seqno, n->received_seqno);
334 for(int i = n->received_seqno + 1; i < inpkt->seqno; i++)
335 n->late[(i / 8) % replaywin] |= 1 << i % 8;
340 n->late[(inpkt->seqno / 8) % replaywin] &= ~(1 << inpkt->seqno % 8);
343 if(inpkt->seqno > n->received_seqno)
344 n->received_seqno = inpkt->seqno;
346 if(n->received_seqno > MAX_SEQNO)
349 /* Decompress the packet */
351 length_t origlen = inpkt->len;
353 if(n->incompression) {
354 outpkt = pkt[nextpkt++];
356 if((outpkt->len = uncompress_packet(outpkt->data, inpkt->data, inpkt->len, n->incompression)) < 0) {
357 logger(DEBUG_TRAFFIC, LOG_ERR, "Error while uncompressing packet from %s (%s)",
358 n->name, n->hostname);
364 origlen -= MTU/64 + 20;
369 if(!inpkt->data[12] && !inpkt->data[13])
370 mtu_probe_h(n, inpkt, origlen);
372 receive_packet(n, inpkt);
375 void receive_tcppacket(connection_t *c, const char *buffer, int len) {
379 if(c->options & OPTION_TCPONLY)
382 outpkt.priority = -1;
383 memcpy(outpkt.data, buffer, len);
385 receive_packet(c->node, &outpkt);
388 static void send_udppacket(node_t *n, vpn_packet_t *origpkt) {
389 vpn_packet_t pkt1, pkt2;
390 vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
391 vpn_packet_t *inpkt = origpkt;
393 vpn_packet_t *outpkt;
394 int origlen = origpkt->len;
396 #if defined(SOL_IP) && defined(IP_TOS)
397 static int priority = 0;
399 int origpriority = origpkt->priority;
401 if(!n->status.reachable) {
402 logger(DEBUG_TRAFFIC, LOG_INFO, "Trying to send UDP packet to unreachable node %s (%s)", n->name, n->hostname);
406 /* Make sure we have a valid key */
408 if(!n->status.validkey) {
409 time_t now = time(NULL);
411 logger(DEBUG_TRAFFIC, LOG_INFO,
412 "No valid key known yet for %s (%s), forwarding via TCP",
413 n->name, n->hostname);
415 if(n->last_req_key + 10 <= now) {
417 n->last_req_key = now;
420 send_tcppacket(n->nexthop->connection, origpkt);
425 if(n->options & OPTION_PMTU_DISCOVERY && inpkt->len > n->minmtu && (inpkt->data[12] | inpkt->data[13])) {
426 logger(DEBUG_TRAFFIC, LOG_INFO,
427 "Packet for %s (%s) larger than minimum MTU, forwarding via %s",
428 n->name, n->hostname, n != n->nexthop ? n->nexthop->name : "TCP");
431 send_packet(n->nexthop, origpkt);
433 send_tcppacket(n->nexthop->connection, origpkt);
438 if(experimental && OPTION_VERSION(n->options) >= 2) {
440 if(!(inpkt->data[12] | inpkt->data[13]))
442 sptps_send_record(&n->sptps, type, (char *)inpkt->data, inpkt->len);
446 /* Compress the packet */
448 if(n->outcompression) {
449 outpkt = pkt[nextpkt++];
451 if((outpkt->len = compress_packet(outpkt->data, inpkt->data, inpkt->len, n->outcompression)) < 0) {
452 logger(DEBUG_TRAFFIC, LOG_ERR, "Error while compressing packet to %s (%s)",
453 n->name, n->hostname);
460 /* Add sequence number */
462 inpkt->seqno = htonl(++(n->sent_seqno));
463 inpkt->len += sizeof inpkt->seqno;
465 /* Encrypt the packet */
467 if(cipher_active(&n->outcipher)) {
468 outpkt = pkt[nextpkt++];
471 if(!cipher_encrypt(&n->outcipher, &inpkt->seqno, inpkt->len, &outpkt->seqno, &outlen, true)) {
472 logger(DEBUG_TRAFFIC, LOG_ERR, "Error while encrypting packet to %s (%s)", n->name, n->hostname);
476 outpkt->len = outlen;
480 /* Add the message authentication code */
482 if(digest_active(&n->outdigest)) {
483 digest_create(&n->outdigest, &inpkt->seqno, inpkt->len, (char *)&inpkt->seqno + inpkt->len);
484 inpkt->len += digest_length(&n->outdigest);
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 */
504 /* Overloaded use of priority field: -1 means local broadcast */
506 if(origpriority == -1 && n->prevedge) {
507 struct sockaddr_in in;
508 in.sin_family = AF_INET;
509 in.sin_addr.s_addr = -1;
510 in.sin_port = n->prevedge->address.in.sin_port;
511 sa = (struct sockaddr *)∈
515 if(origpriority == -1)
518 sa = &(n->address.sa);
519 sl = SALEN(n->address.sa);
523 #if defined(SOL_IP) && defined(IP_TOS)
524 if(priorityinheritance && origpriority != priority
525 && listen_socket[n->sock].sa.sa.sa_family == AF_INET) {
526 priority = origpriority;
527 logger(DEBUG_TRAFFIC, LOG_DEBUG, "Setting outgoing packet priority to %d", priority);
528 if(setsockopt(listen_socket[n->sock].udp, SOL_IP, IP_TOS, &priority, sizeof(priority))) /* SO_PRIORITY doesn't seem to work */
529 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setsockopt", strerror(errno));
533 if(sendto(listen_socket[sock].udp, (char *) &inpkt->seqno, inpkt->len, 0, sa, sl) < 0 && !sockwouldblock(sockerrno)) {
534 if(sockmsgsize(sockerrno)) {
535 if(n->maxmtu >= origlen)
536 n->maxmtu = origlen - 1;
537 if(n->mtu >= origlen)
538 n->mtu = origlen - 1;
540 logger(DEBUG_TRAFFIC, LOG_WARNING, "Error sending packet to %s (%s): %s", n->name, n->hostname, sockstrerror(sockerrno));
544 origpkt->len = origlen;
547 bool send_sptps_data(void *handle, uint8_t type, const char *data, size_t len) {
550 if(type >= SPTPS_HANDSHAKE) {
551 char buf[len * 4 / 3 + 5];
552 b64encode(data, buf, len);
553 if(!to->status.validkey)
554 return send_request(to->nexthop->connection, "%d %s %s %s -1 -1 -1 -1", ANS_KEY, myself->name, to->name, buf);
556 return send_request(to->nexthop->connection, "%d %s %s %d %s", REQ_KEY, myself->name, to->name, REQ_SPTPS, buf);
559 /* Send the packet */
565 sa = &(to->address.sa);
566 sl = SALEN(to->address.sa);
569 if(sendto(listen_socket[sock].udp, data, len, 0, sa, sl) < 0 && !sockwouldblock(sockerrno)) {
570 if(sockmsgsize(sockerrno)) {
571 if(to->maxmtu >= len)
572 to->maxmtu = len - 1;
576 logger(DEBUG_TRAFFIC, LOG_WARNING, "Error sending UDP SPTPS packet to %s (%s): %s", to->name, to->hostname, sockstrerror(sockerrno));
584 bool receive_sptps_record(void *handle, uint8_t type, const char *data, uint16_t len) {
585 node_t *from = handle;
587 if(type == SPTPS_HANDSHAKE) {
588 from->status.validkey = true;
589 logger(DEBUG_META, LOG_INFO, "SPTPS key exchange with %s (%s) succesful", from->name, from->hostname);
594 logger(DEBUG_ALWAYS, LOG_ERR, "Packet from %s (%s) larger than maximum supported size (%d > %d)", from->name, from->hostname, len, MTU);
600 memcpy(inpkt.data, data, len);
602 if(type == PKT_PROBE) {
603 mtu_probe_h(from, &inpkt, len);
608 logger(DEBUG_ALWAYS, LOG_ERR, "Unexpected SPTPS record type %d len %d from %s (%s)", type, len, from->name, from->hostname);
612 receive_packet(from, &inpkt);
617 send a packet to the given vpn ip.
619 void send_packet(node_t *n, vpn_packet_t *packet) {
624 memcpy(packet->data, mymac.x, ETH_ALEN);
626 n->out_bytes += packet->len;
627 devops.write(packet);
631 logger(DEBUG_TRAFFIC, LOG_ERR, "Sending packet of %d bytes to %s (%s)",
632 packet->len, n->name, n->hostname);
634 if(!n->status.reachable) {
635 logger(DEBUG_TRAFFIC, LOG_INFO, "Node %s (%s) is not reachable",
636 n->name, n->hostname);
641 n->out_bytes += packet->len;
643 via = (packet->priority == -1 || n->via == myself) ? n->nexthop : n->via;
646 logger(DEBUG_TRAFFIC, LOG_INFO, "Sending packet to %s via %s (%s)",
647 n->name, via->name, n->via->hostname);
649 if(packet->priority == -1 || ((myself->options | via->options) & OPTION_TCPONLY)) {
650 if(!send_tcppacket(via->connection, packet))
651 terminate_connection(via->connection, true);
653 send_udppacket(via, packet);
656 /* Broadcast a packet using the minimum spanning tree */
658 void broadcast_packet(const node_t *from, vpn_packet_t *packet) {
663 // Always give ourself a copy of the packet.
665 send_packet(myself, packet);
667 // In TunnelServer mode, do not forward broadcast packets.
668 // The MST might not be valid and create loops.
669 if(tunnelserver || broadcast_mode == BMODE_NONE)
672 logger(DEBUG_TRAFFIC, LOG_INFO, "Broadcasting packet of %d bytes from %s (%s)",
673 packet->len, from->name, from->hostname);
675 switch(broadcast_mode) {
676 // In MST mode, broadcast packets travel via the Minimum Spanning Tree.
677 // This guarantees all nodes receive the broadcast packet, and
678 // usually distributes the sending of broadcast packets over all nodes.
680 for(node = connection_tree->head; node; node = node->next) {
683 if(c->status.active && c->status.mst && c != from->nexthop->connection)
684 send_packet(c->node, packet);
688 // In direct mode, we send copies to each node we know of.
689 // However, this only reaches nodes that can be reached in a single hop.
690 // We don't have enough information to forward broadcast packets in this case.
695 for(node = node_udp_tree->head; node; node = node->next) {
698 if(n->status.reachable && ((n->via == myself && n->nexthop == n) || n->via == n))
699 send_packet(n, packet);
708 static node_t *try_harder(const sockaddr_t *from, const vpn_packet_t *pkt) {
713 static time_t last_hard_try = 0;
714 time_t now = time(NULL);
716 for(node = edge_weight_tree->head; node; node = node->next) {
722 if(sockaddrcmp_noport(from, &e->address)) {
723 if(last_hard_try == now)
728 if(!try_mac(e->to, pkt))
742 void handle_incoming_vpn_data(int sock, short events, void *data) {
746 socklen_t fromlen = sizeof from;
750 len = recvfrom(sock, (char *) &pkt.seqno, MAXSIZE, 0, &from.sa, &fromlen);
752 if(len <= 0 || len > MAXSIZE) {
753 if(!sockwouldblock(sockerrno))
754 logger(DEBUG_ALWAYS, LOG_ERR, "Receiving packet failed: %s", sockstrerror(sockerrno));
760 sockaddrunmap(&from); /* Some braindead IPv6 implementations do stupid things. */
762 n = lookup_node_udp(&from);
765 n = try_harder(&from, &pkt);
767 update_node_udp(n, &from);
768 else if(debug_level >= DEBUG_PROTOCOL) {
769 hostname = sockaddr2hostname(&from);
770 logger(DEBUG_PROTOCOL, LOG_WARNING, "Received UDP packet from unknown source %s", hostname);
778 n->sock = (intptr_t)data;
780 receive_udppacket(n, &pkt);
783 void handle_device_data(int sock, short events, void *data) {
788 if(devops.read(&packet)) {
789 myself->in_packets++;
790 myself->in_bytes += packet.len;
791 route(myself, &packet);