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"
61 static char lzo_wrkmem[LZO1X_999_MEM_COMPRESS > LZO1X_1_MEM_COMPRESS ? LZO1X_999_MEM_COMPRESS : LZO1X_1_MEM_COMPRESS];
64 static void send_udppacket(node_t *, vpn_packet_t *);
66 unsigned replaywin = 16;
68 #define MAX_SEQNO 1073741824
70 // mtuprobes == 1..30: initial discovery, send bursts with 1 second interval
71 // mtuprobes == 31: sleep pinginterval seconds
72 // mtuprobes == 32: send 1 burst, sleep pingtimeout second
73 // mtuprobes == 33: no response from other side, restart PMTU discovery process
75 static void send_mtu_probe_handler(int fd, short events, void *data) {
83 if(!n->status.reachable || !n->status.validkey) {
84 ifdebug(TRAFFIC) logger(LOG_INFO, "Trying to send MTU probe to unreachable or rekeying node %s (%s)", n->name, n->hostname);
89 if(n->mtuprobes > 32) {
92 timeout = pinginterval;
96 ifdebug(TRAFFIC) logger(LOG_INFO, "%s (%s) did not respond to UDP ping, restarting PMTU discovery", n->name, n->hostname);
102 if(n->mtuprobes >= 10 && n->mtuprobes < 32 && !n->minmtu) {
103 ifdebug(TRAFFIC) logger(LOG_INFO, "No response to MTU probes from %s (%s)", n->name, n->hostname);
107 if(n->mtuprobes == 30 || (n->mtuprobes < 30 && n->minmtu >= n->maxmtu)) {
108 if(n->minmtu > n->maxmtu)
109 n->minmtu = n->maxmtu;
111 n->maxmtu = n->minmtu;
113 ifdebug(TRAFFIC) logger(LOG_INFO, "Fixing MTU of %s (%s) to %d after %d probes", n->name, n->hostname, n->mtu, n->mtuprobes);
117 if(n->mtuprobes == 31) {
118 timeout = pinginterval;
120 } else if(n->mtuprobes == 32) {
121 timeout = pingtimeout;
124 for(i = 0; i < 3; i++) {
125 if(n->maxmtu <= n->minmtu)
128 len = n->minmtu + 1 + rand() % (n->maxmtu - n->minmtu);
133 memset(packet.data, 0, 14);
134 randomize(packet.data + 14, len - 14);
138 ifdebug(TRAFFIC) logger(LOG_INFO, "Sending MTU probe length %d to %s (%s)", len, n->name, n->hostname);
140 send_udppacket(n, &packet);
144 event_add(&n->mtuevent, &(struct timeval){timeout, 0});
147 void send_mtu_probe(node_t *n) {
148 if(!timeout_initialized(&n->mtuevent))
149 timeout_set(&n->mtuevent, send_mtu_probe_handler, n);
150 send_mtu_probe_handler(0, 0, n);
153 void mtu_probe_h(node_t *n, vpn_packet_t *packet, length_t len) {
154 ifdebug(TRAFFIC) logger(LOG_INFO, "Got MTU probe length %d from %s (%s)", packet->len, n->name, n->hostname);
156 if(!packet->data[0]) {
158 send_udppacket(n, packet);
160 if(n->mtuprobes > 30) {
174 static length_t compress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level) {
176 memcpy(dest, source, len);
178 } else if(level == 10) {
180 lzo_uint lzolen = MAXSIZE;
181 lzo1x_1_compress(source, len, dest, &lzolen, lzo_wrkmem);
186 } else if(level < 10) {
188 unsigned long destlen = MAXSIZE;
189 if(compress2(dest, &destlen, source, len, level) == Z_OK)
196 lzo_uint lzolen = MAXSIZE;
197 lzo1x_999_compress(source, len, dest, &lzolen, lzo_wrkmem);
207 static length_t uncompress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level) {
209 memcpy(dest, source, len);
211 } else if(level > 9) {
213 lzo_uint lzolen = MAXSIZE;
214 if(lzo1x_decompress_safe(source, len, dest, &lzolen, NULL) == LZO_E_OK)
222 unsigned long destlen = MAXSIZE;
223 if(uncompress(dest, &destlen, source, len) == Z_OK)
235 static void receive_packet(node_t *n, vpn_packet_t *packet) {
236 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Received packet of %d bytes from %s (%s)",
237 packet->len, n->name, n->hostname);
240 n->in_bytes += packet->len;
245 static bool try_mac(node_t *n, const vpn_packet_t *inpkt) {
246 if(!digest_active(&n->indigest) || inpkt->len < sizeof inpkt->seqno + digest_length(&n->indigest))
249 return digest_verify(&n->indigest, &inpkt->seqno, inpkt->len - n->indigest.maclength, (const char *)&inpkt->seqno + inpkt->len - n->indigest.maclength);
252 static void receive_udppacket(node_t *n, vpn_packet_t *inpkt) {
253 vpn_packet_t pkt1, pkt2;
254 vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
256 vpn_packet_t *outpkt = pkt[0];
260 if(!cipher_active(&n->incipher)) {
261 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Got packet from %s (%s) but he hasn't got our key yet",
262 n->name, n->hostname);
266 /* Check packet length */
268 if(inpkt->len < sizeof inpkt->seqno + digest_length(&n->indigest)) {
269 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Got too short packet from %s (%s)",
270 n->name, n->hostname);
274 /* Check the message authentication code */
276 if(digest_active(&n->indigest)) {
277 inpkt->len -= n->indigest.maclength;
278 if(!digest_verify(&n->indigest, &inpkt->seqno, inpkt->len, (const char *)&inpkt->seqno + inpkt->len)) {
279 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Got unauthenticated packet from %s (%s)", n->name, n->hostname);
283 /* Decrypt the packet */
285 if(cipher_active(&n->incipher)) {
286 outpkt = pkt[nextpkt++];
289 if(!cipher_decrypt(&n->incipher, &inpkt->seqno, inpkt->len, &outpkt->seqno, &outlen, true)) {
290 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Error decrypting packet from %s (%s)", n->name, n->hostname);
294 outpkt->len = outlen;
298 /* Check the sequence number */
300 inpkt->len -= sizeof inpkt->seqno;
301 inpkt->seqno = ntohl(inpkt->seqno);
304 if(inpkt->seqno != n->received_seqno + 1) {
305 if(inpkt->seqno >= n->received_seqno + replaywin * 8) {
306 if(n->farfuture++ < replaywin >> 2) {
307 logger(LOG_WARNING, "Packet from %s (%s) is %d seqs in the future, dropped (%u)",
308 n->name, n->hostname, inpkt->seqno - n->received_seqno - 1, n->farfuture);
311 logger(LOG_WARNING, "Lost %d packets from %s (%s)",
312 inpkt->seqno - n->received_seqno - 1, n->name, n->hostname);
313 memset(n->late, 0, replaywin);
314 } else if (inpkt->seqno <= n->received_seqno) {
315 if((n->received_seqno >= replaywin * 8 && inpkt->seqno <= n->received_seqno - replaywin * 8) || !(n->late[(inpkt->seqno / 8) % replaywin] & (1 << inpkt->seqno % 8))) {
316 logger(LOG_WARNING, "Got late or replayed packet from %s (%s), seqno %d, last received %d",
317 n->name, n->hostname, inpkt->seqno, n->received_seqno);
321 for(i = n->received_seqno + 1; i < inpkt->seqno; i++)
322 n->late[(i / 8) % replaywin] |= 1 << i % 8;
327 n->late[(inpkt->seqno / 8) % replaywin] &= ~(1 << inpkt->seqno % 8);
330 if(inpkt->seqno > n->received_seqno)
331 n->received_seqno = inpkt->seqno;
333 if(n->received_seqno > MAX_SEQNO)
336 /* Decompress the packet */
338 length_t origlen = inpkt->len;
340 if(n->incompression) {
341 outpkt = pkt[nextpkt++];
343 if((outpkt->len = uncompress_packet(outpkt->data, inpkt->data, inpkt->len, n->incompression)) < 0) {
344 ifdebug(TRAFFIC) logger(LOG_ERR, "Error while uncompressing packet from %s (%s)",
345 n->name, n->hostname);
351 origlen -= MTU/64 + 20;
356 if(!inpkt->data[12] && !inpkt->data[13])
357 mtu_probe_h(n, inpkt, origlen);
359 receive_packet(n, inpkt);
362 void receive_tcppacket(connection_t *c, char *buffer, int len) {
366 if(c->options & OPTION_TCPONLY)
369 outpkt.priority = -1;
370 memcpy(outpkt.data, buffer, len);
372 receive_packet(c->node, &outpkt);
375 static void send_udppacket(node_t *n, vpn_packet_t *origpkt) {
376 vpn_packet_t pkt1, pkt2;
377 vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
378 vpn_packet_t *inpkt = origpkt;
380 vpn_packet_t *outpkt;
383 #if defined(SOL_IP) && defined(IP_TOS)
384 static int priority = 0;
389 if(!n->status.reachable) {
390 ifdebug(TRAFFIC) logger(LOG_INFO, "Trying to send UDP packet to unreachable node %s (%s)", n->name, n->hostname);
394 /* Make sure we have a valid key */
396 if(!n->status.validkey) {
397 time_t now = time(NULL);
399 ifdebug(TRAFFIC) logger(LOG_INFO,
400 "No valid key known yet for %s (%s), forwarding via TCP",
401 n->name, n->hostname);
403 if(n->last_req_key + 10 < now) {
405 n->last_req_key = now;
408 send_tcppacket(n->nexthop->connection, origpkt);
413 if(n->options & OPTION_PMTU_DISCOVERY && inpkt->len > n->minmtu && (inpkt->data[12] | inpkt->data[13])) {
414 ifdebug(TRAFFIC) logger(LOG_INFO,
415 "Packet for %s (%s) larger than minimum MTU, forwarding via %s",
416 n->name, n->hostname, n != n->nexthop ? n->nexthop->name : "TCP");
419 send_packet(n->nexthop, origpkt);
421 send_tcppacket(n->nexthop->connection, origpkt);
426 origlen = inpkt->len;
427 origpriority = inpkt->priority;
429 /* Compress the packet */
431 if(n->outcompression) {
432 outpkt = pkt[nextpkt++];
434 if((outpkt->len = compress_packet(outpkt->data, inpkt->data, inpkt->len, n->outcompression)) < 0) {
435 ifdebug(TRAFFIC) logger(LOG_ERR, "Error while compressing packet to %s (%s)",
436 n->name, n->hostname);
443 /* Add sequence number */
445 inpkt->seqno = htonl(++(n->sent_seqno));
446 inpkt->len += sizeof inpkt->seqno;
448 /* Encrypt the packet */
450 if(cipher_active(&n->outcipher)) {
451 outpkt = pkt[nextpkt++];
454 if(!cipher_encrypt(&n->outcipher, &inpkt->seqno, inpkt->len, &outpkt->seqno, &outlen, true)) {
455 ifdebug(TRAFFIC) logger(LOG_ERR, "Error while encrypting packet to %s (%s)", n->name, n->hostname);
459 outpkt->len = outlen;
463 /* Add the message authentication code */
465 if(digest_active(&n->outdigest)) {
466 digest_create(&n->outdigest, &inpkt->seqno, inpkt->len, (char *)&inpkt->seqno + inpkt->len);
467 inpkt->len += digest_length(&n->outdigest);
470 /* Determine which socket we have to use */
472 for(sock = 0; sock < listen_sockets; sock++)
473 if(n->address.sa.sa_family == listen_socket[sock].sa.sa.sa_family)
476 if(sock >= listen_sockets)
477 sock = 0; /* If none is available, just use the first and hope for the best. */
479 /* Send the packet */
481 #if defined(SOL_IP) && defined(IP_TOS)
482 if(priorityinheritance && origpriority != priority
483 && listen_socket[sock].sa.sa.sa_family == AF_INET) {
484 priority = origpriority;
485 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Setting outgoing packet priority to %d", priority);
486 if(setsockopt(listen_socket[sock].udp, SOL_IP, IP_TOS, &priority, sizeof priority)) /* SO_PRIORITY doesn't seem to work */
487 logger(LOG_ERR, "System call `%s' failed: %s", "setsockopt", strerror(errno));
491 if(sendto(listen_socket[sock].udp, (char *) &inpkt->seqno, inpkt->len, 0, &(n->address.sa), SALEN(n->address.sa)) < 0 && !sockwouldblock(sockerrno)) {
492 if(sockmsgsize(sockerrno)) {
493 if(n->maxmtu >= origlen)
494 n->maxmtu = origlen - 1;
495 if(n->mtu >= origlen)
496 n->mtu = origlen - 1;
498 logger(LOG_ERR, "Error sending packet to %s (%s): %s", n->name, n->hostname, sockstrerror(sockerrno));
502 origpkt->len = origlen;
506 send a packet to the given vpn ip.
508 void send_packet(node_t *n, vpn_packet_t *packet) {
513 memcpy(packet->data, mymac.x, ETH_ALEN);
515 n->out_bytes += packet->len;
516 write_packet(packet);
520 ifdebug(TRAFFIC) logger(LOG_ERR, "Sending packet of %d bytes to %s (%s)",
521 packet->len, n->name, n->hostname);
523 if(!n->status.reachable) {
524 ifdebug(TRAFFIC) logger(LOG_INFO, "Node %s (%s) is not reachable",
525 n->name, n->hostname);
530 n->out_bytes += packet->len;
532 via = (packet->priority == -1 || n->via == myself) ? n->nexthop : n->via;
535 ifdebug(TRAFFIC) logger(LOG_INFO, "Sending packet to %s via %s (%s)",
536 n->name, via->name, n->via->hostname);
538 if(packet->priority == -1 || ((myself->options | via->options) & OPTION_TCPONLY)) {
539 if(!send_tcppacket(via->connection, packet))
540 terminate_connection(via->connection, true);
542 send_udppacket(via, packet);
545 /* Broadcast a packet using the minimum spanning tree */
547 void broadcast_packet(const node_t *from, vpn_packet_t *packet) {
551 ifdebug(TRAFFIC) logger(LOG_INFO, "Broadcasting packet of %d bytes from %s (%s)",
552 packet->len, from->name, from->hostname);
555 send_packet(myself, packet);
557 // In TunnelServer mode, do not forward broadcast packets.
558 // The MST might not be valid and create loops.
563 for(node = connection_tree->head; node; node = node->next) {
566 if(c->status.active && c->status.mst && c != from->nexthop->connection)
567 send_packet(c->node, packet);
571 static node_t *try_harder(const sockaddr_t *from, const vpn_packet_t *pkt) {
576 static time_t last_hard_try = 0;
577 time_t now = time(NULL);
579 if(last_hard_try == now)
584 for(node = edge_weight_tree->head; node; node = node->next) {
590 if(sockaddrcmp_noport(from, &e->address)) {
591 if(last_hard_try == now)
596 if(!try_mac(e->to, pkt))
609 void handle_incoming_vpn_data(int sock, short events, void *data) {
613 socklen_t fromlen = sizeof from;
617 len = recvfrom(sock, (char *) &pkt.seqno, MAXSIZE, 0, &from.sa, &fromlen);
619 if(len <= 0 || len > MAXSIZE) {
620 if(!sockwouldblock(sockerrno))
621 logger(LOG_ERR, "Receiving packet failed: %s", sockstrerror(sockerrno));
627 sockaddrunmap(&from); /* Some braindead IPv6 implementations do stupid things. */
629 n = lookup_node_udp(&from);
632 n = try_harder(&from, &pkt);
634 update_node_udp(n, &from);
635 else ifdebug(PROTOCOL) {
636 hostname = sockaddr2hostname(&from);
637 logger(LOG_WARNING, "Received UDP packet from unknown source %s", hostname);
645 receive_udppacket(n, &pkt);
648 void handle_device_data(int sock, short events, void *data) {
651 if(read_packet(&packet)) {
652 myself->in_packets++;
653 myself->in_bytes += packet.len;
654 route(myself, &packet);