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>
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"
60 static char lzo_wrkmem[LZO1X_999_MEM_COMPRESS > LZO1X_1_MEM_COMPRESS ? LZO1X_999_MEM_COMPRESS : LZO1X_1_MEM_COMPRESS];
63 static void send_udppacket(node_t *, vpn_packet_t *);
65 unsigned replaywin = 16;
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 static void send_mtu_probe_handler(int fd, short events, void *data) {
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);
88 if(n->mtuprobes > 32) {
91 timeout = pinginterval;
95 ifdebug(TRAFFIC) logger(LOG_INFO, "%s (%s) did not respond to UDP ping, restarting PMTU discovery", n->name, n->hostname);
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);
106 if(n->mtuprobes == 30 || (n->mtuprobes < 30 && n->minmtu >= n->maxmtu)) {
107 if(n->minmtu > n->maxmtu)
108 n->minmtu = n->maxmtu;
110 n->maxmtu = 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);
116 if(n->mtuprobes == 31) {
117 timeout = pinginterval;
119 } else if(n->mtuprobes == 32) {
120 timeout = pingtimeout;
123 for(i = 0; i < 3; i++) {
124 if(n->maxmtu <= n->minmtu)
127 len = n->minmtu + 1 + rand() % (n->maxmtu - n->minmtu);
132 memset(packet.data, 0, 14);
133 randomize(packet.data + 14, len - 14);
137 ifdebug(TRAFFIC) logger(LOG_INFO, "Sending MTU probe length %d to %s (%s)", len, n->name, n->hostname);
139 send_udppacket(n, &packet);
143 event_add(&n->mtuevent, &(struct timeval){timeout, 0});
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);
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);
155 if(!packet->data[0]) {
157 send_udppacket(n, packet);
159 if(n->mtuprobes > 30) {
173 static length_t compress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level) {
175 memcpy(dest, source, len);
177 } else if(level == 10) {
179 lzo_uint lzolen = MAXSIZE;
180 lzo1x_1_compress(source, len, dest, &lzolen, lzo_wrkmem);
185 } else if(level < 10) {
187 unsigned long destlen = MAXSIZE;
188 if(compress2(dest, &destlen, source, len, level) == Z_OK)
195 lzo_uint lzolen = MAXSIZE;
196 lzo1x_999_compress(source, len, dest, &lzolen, lzo_wrkmem);
206 static length_t uncompress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level) {
208 memcpy(dest, source, len);
210 } else if(level > 9) {
212 lzo_uint lzolen = MAXSIZE;
213 if(lzo1x_decompress_safe(source, len, dest, &lzolen, NULL) == LZO_E_OK)
221 unsigned long destlen = MAXSIZE;
222 if(uncompress(dest, &destlen, source, len) == Z_OK)
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);
239 n->in_bytes += packet->len;
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))
248 return digest_verify(&n->indigest, &inpkt->seqno, inpkt->len - n->indigest.maclength, (const char *)&inpkt->seqno + inpkt->len - n->indigest.maclength);
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 };
255 vpn_packet_t *outpkt = pkt[0];
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);
264 /* Check packet length */
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);
272 /* Check the message authentication code */
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);
281 /* Decrypt the packet */
283 if(cipher_active(&n->incipher)) {
284 outpkt = pkt[nextpkt++];
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);
292 outpkt->len = outlen;
296 /* Check the sequence number */
298 inpkt->len -= sizeof inpkt->seqno;
299 inpkt->seqno = ntohl(inpkt->seqno);
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);
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);
319 for(int i = n->received_seqno + 1; i < inpkt->seqno; i++)
320 n->late[(i / 8) % replaywin] |= 1 << i % 8;
325 n->late[(inpkt->seqno / 8) % replaywin] &= ~(1 << inpkt->seqno % 8);
328 if(inpkt->seqno > n->received_seqno)
329 n->received_seqno = inpkt->seqno;
331 if(n->received_seqno > MAX_SEQNO)
334 /* Decompress the packet */
336 length_t origlen = inpkt->len;
338 if(n->incompression) {
339 outpkt = pkt[nextpkt++];
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);
349 origlen -= MTU/64 + 20;
354 if(!inpkt->data[12] && !inpkt->data[13])
355 mtu_probe_h(n, inpkt, origlen);
357 receive_packet(n, inpkt);
360 void receive_tcppacket(connection_t *c, char *buffer, int len) {
364 if(c->options & OPTION_TCPONLY)
367 outpkt.priority = -1;
368 memcpy(outpkt.data, buffer, len);
370 receive_packet(c->node, &outpkt);
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;
378 vpn_packet_t *outpkt;
379 int origlen = origpkt->len;
381 #if defined(SOL_IP) && defined(IP_TOS)
382 static int priority = 0;
383 int origpriority = origpkt->priority;
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);
392 /* Make sure we have a valid key */
394 if(!n->status.validkey) {
395 time_t now = time(NULL);
397 ifdebug(TRAFFIC) logger(LOG_INFO,
398 "No valid key known yet for %s (%s), forwarding via TCP",
399 n->name, n->hostname);
401 if(n->last_req_key + 10 < now) {
403 n->last_req_key = now;
406 send_tcppacket(n->nexthop->connection, origpkt);
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");
417 send_packet(n->nexthop, origpkt);
419 send_tcppacket(n->nexthop->connection, origpkt);
424 /* Compress the packet */
426 if(n->outcompression) {
427 outpkt = pkt[nextpkt++];
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);
438 /* Add sequence number */
440 inpkt->seqno = htonl(++(n->sent_seqno));
441 inpkt->len += sizeof inpkt->seqno;
443 /* Encrypt the packet */
445 if(cipher_active(&n->outcipher)) {
446 outpkt = pkt[nextpkt++];
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);
454 outpkt->len = outlen;
458 /* Add the message authentication code */
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);
465 /* Determine which socket we have to use */
467 for(sock = 0; sock < listen_sockets; sock++)
468 if(n->address.sa.sa_family == listen_socket[sock].sa.sa.sa_family)
471 if(sock >= listen_sockets)
472 sock = 0; /* If none is available, just use the first and hope for the best. */
474 /* Send the packet */
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));
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;
493 logger(LOG_ERR, "Error sending packet to %s (%s): %s", n->name, n->hostname, sockstrerror(sockerrno));
497 origpkt->len = origlen;
501 send a packet to the given vpn ip.
503 void send_packet(node_t *n, vpn_packet_t *packet) {
508 memcpy(packet->data, mymac.x, ETH_ALEN);
510 n->out_bytes += packet->len;
511 write_packet(packet);
515 ifdebug(TRAFFIC) logger(LOG_ERR, "Sending packet of %d bytes to %s (%s)",
516 packet->len, n->name, n->hostname);
518 if(!n->status.reachable) {
519 ifdebug(TRAFFIC) logger(LOG_INFO, "Node %s (%s) is not reachable",
520 n->name, n->hostname);
525 n->out_bytes += packet->len;
527 via = (packet->priority == -1 || n->via == myself) ? n->nexthop : n->via;
530 ifdebug(TRAFFIC) logger(LOG_INFO, "Sending packet to %s via %s (%s)",
531 n->name, via->name, n->via->hostname);
533 if(packet->priority == -1 || ((myself->options | via->options) & OPTION_TCPONLY)) {
534 if(!send_tcppacket(via->connection, packet))
535 terminate_connection(via->connection, true);
537 send_udppacket(via, packet);
540 /* Broadcast a packet using the minimum spanning tree */
542 void broadcast_packet(const node_t *from, vpn_packet_t *packet) {
546 ifdebug(TRAFFIC) logger(LOG_INFO, "Broadcasting packet of %d bytes from %s (%s)",
547 packet->len, from->name, from->hostname);
550 send_packet(myself, packet);
552 // In TunnelServer mode, do not forward broadcast packets.
553 // The MST might not be valid and create loops.
558 for(node = connection_tree->head; node; node = node->next) {
561 if(c->status.active && c->status.mst && c != from->nexthop->connection)
562 send_packet(c->node, packet);
566 static node_t *try_harder(const sockaddr_t *from, const vpn_packet_t *pkt) {
571 static time_t last_hard_try = 0;
572 time_t now = time(NULL);
574 if(last_hard_try == now)
579 for(node = edge_weight_tree->head; node; node = node->next) {
585 if(sockaddrcmp_noport(from, &e->address)) {
586 if(last_hard_try == now)
591 if(!try_mac(e->to, pkt))
604 void handle_incoming_vpn_data(int sock, short events, void *data) {
608 socklen_t fromlen = sizeof from;
612 len = recvfrom(sock, (char *) &pkt.seqno, MAXSIZE, 0, &from.sa, &fromlen);
614 if(len <= 0 || len > MAXSIZE) {
615 if(!sockwouldblock(sockerrno))
616 logger(LOG_ERR, "Receiving packet failed: %s", sockstrerror(sockerrno));
622 sockaddrunmap(&from); /* Some braindead IPv6 implementations do stupid things. */
624 n = lookup_node_udp(&from);
627 n = try_harder(&from, &pkt);
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);
640 receive_udppacket(n, &pkt);
643 void handle_device_data(int sock, short events, void *data) {
648 if(read_packet(&packet)) {
649 myself->in_packets++;
650 myself->in_bytes += packet.len;
651 route(myself, &packet);