2 net_packet.c -- Handles in- and outgoing VPN packets
3 Copyright (C) 1998-2005 Ivo Timmermans,
4 2000-2010 Guus Sliepen <guus@tinc-vpn.org>
5 2010 Timothy Redaelli <timothy@redaelli.eu>
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License along
18 with this program; if not, write to the Free Software Foundation, Inc.,
19 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24 #include <openssl/rand.h>
25 #include <openssl/err.h>
26 #include <openssl/evp.h>
27 #include <openssl/pem.h>
28 #include <openssl/hmac.h>
40 #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;
65 #define MAX_SEQNO 1073741824
67 // mtuprobes == 1..30: initial discovery, send bursts with 1 second interval
68 // mtuprobes == 31: sleep pinginterval seconds
69 // mtuprobes == 32: send 1 burst, sleep pingtimeout second
70 // mtuprobes == 33: no response from other side, restart PMTU discovery process
72 void send_mtu_probe(node_t *n) {
80 if(!n->status.reachable || !n->status.validkey) {
81 ifdebug(TRAFFIC) logger(LOG_INFO, "Trying to send MTU probe to unreachable or rekeying node %s (%s)", n->name, n->hostname);
86 if(n->mtuprobes > 32) {
87 ifdebug(TRAFFIC) logger(LOG_INFO, "%s (%s) did not respond to UDP ping, restarting PMTU discovery", n->name, n->hostname);
93 if(n->mtuprobes >= 10 && !n->minmtu) {
94 ifdebug(TRAFFIC) logger(LOG_INFO, "No response to MTU probes from %s (%s)", n->name, n->hostname);
99 if(n->mtuprobes == 30 || (n->mtuprobes < 30 && n->minmtu >= n->maxmtu)) {
100 if(n->minmtu > n->maxmtu)
101 n->minmtu = n->maxmtu;
103 n->maxmtu = n->minmtu;
105 ifdebug(TRAFFIC) logger(LOG_INFO, "Fixing MTU of %s (%s) to %d after %d probes", n->name, n->hostname, n->mtu, n->mtuprobes);
109 if(n->mtuprobes == 31) {
110 timeout = pinginterval;
112 } else if(n->mtuprobes == 32) {
113 timeout = pingtimeout;
116 for(i = 0; i < 3; i++) {
117 if(n->maxmtu <= n->minmtu)
120 len = n->minmtu + 1 + rand() % (n->maxmtu - n->minmtu);
125 memset(packet.data, 0, 14);
126 RAND_pseudo_bytes(packet.data + 14, len - 14);
130 ifdebug(TRAFFIC) logger(LOG_INFO, "Sending MTU probe length %d to %s (%s)", len, n->name, n->hostname);
132 send_udppacket(n, &packet);
136 n->mtuevent = new_event();
137 n->mtuevent->handler = (event_handler_t)send_mtu_probe;
138 n->mtuevent->data = n;
139 n->mtuevent->time = now + timeout;
140 event_add(n->mtuevent);
143 void mtu_probe_h(node_t *n, vpn_packet_t *packet, length_t len) {
144 ifdebug(TRAFFIC) logger(LOG_INFO, "Got MTU probe length %d from %s (%s)", packet->len, n->name, n->hostname);
146 if(!packet->data[0]) {
148 send_udppacket(n, packet);
154 if(n->mtuprobes > 30)
159 static length_t compress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level) {
161 memcpy(dest, source, len);
163 } else if(level == 10) {
165 lzo_uint lzolen = MAXSIZE;
166 lzo1x_1_compress(source, len, dest, &lzolen, lzo_wrkmem);
171 } else if(level < 10) {
173 unsigned long destlen = MAXSIZE;
174 if(compress2(dest, &destlen, source, len, level) == Z_OK)
181 lzo_uint lzolen = MAXSIZE;
182 lzo1x_999_compress(source, len, dest, &lzolen, lzo_wrkmem);
192 static length_t uncompress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level) {
194 memcpy(dest, source, len);
196 } else if(level > 9) {
198 lzo_uint lzolen = MAXSIZE;
199 if(lzo1x_decompress_safe(source, len, dest, &lzolen, NULL) == LZO_E_OK)
207 unsigned long destlen = MAXSIZE;
208 if(uncompress(dest, &destlen, source, len) == Z_OK)
220 static void receive_packet(node_t *n, vpn_packet_t *packet) {
221 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Received packet of %d bytes from %s (%s)",
222 packet->len, n->name, n->hostname);
227 static bool try_mac(const node_t *n, const vpn_packet_t *inpkt) {
228 unsigned char hmac[EVP_MAX_MD_SIZE];
230 if(!n->indigest || !n->inmaclength || !n->inkey || inpkt->len < sizeof inpkt->seqno + n->inmaclength)
233 HMAC(n->indigest, n->inkey, n->inkeylength, (unsigned char *) &inpkt->seqno, inpkt->len - n->inmaclength, (unsigned char *)hmac, NULL);
235 return !memcmp(hmac, (char *) &inpkt->seqno + inpkt->len - n->inmaclength, n->inmaclength);
238 static void receive_udppacket(node_t *n, vpn_packet_t *inpkt) {
239 vpn_packet_t pkt1, pkt2;
240 vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
242 vpn_packet_t *outpkt = pkt[0];
244 unsigned char hmac[EVP_MAX_MD_SIZE];
248 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Got packet from %s (%s) but he hasn't got our key yet",
249 n->name, n->hostname);
253 /* Check packet length */
255 if(inpkt->len < sizeof(inpkt->seqno) + n->inmaclength) {
256 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Got too short packet from %s (%s)",
257 n->name, n->hostname);
261 /* Check the message authentication code */
263 if(n->indigest && n->inmaclength) {
264 inpkt->len -= n->inmaclength;
265 HMAC(n->indigest, n->inkey, n->inkeylength,
266 (unsigned char *) &inpkt->seqno, inpkt->len, (unsigned char *)hmac, NULL);
268 if(memcmp(hmac, (char *) &inpkt->seqno + inpkt->len, n->inmaclength)) {
269 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Got unauthenticated packet from %s (%s)",
270 n->name, n->hostname);
275 /* Decrypt the packet */
278 outpkt = pkt[nextpkt++];
280 if(!EVP_DecryptInit_ex(&n->inctx, NULL, NULL, NULL, NULL)
281 || !EVP_DecryptUpdate(&n->inctx, (unsigned char *) &outpkt->seqno, &outlen,
282 (unsigned char *) &inpkt->seqno, inpkt->len)
283 || !EVP_DecryptFinal_ex(&n->inctx, (unsigned char *) &outpkt->seqno + outlen, &outpad)) {
284 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Error decrypting packet from %s (%s): %s",
285 n->name, n->hostname, ERR_error_string(ERR_get_error(), NULL));
289 outpkt->len = outlen + outpad;
293 /* Check the sequence number */
295 inpkt->len -= sizeof(inpkt->seqno);
296 inpkt->seqno = ntohl(inpkt->seqno);
299 if(inpkt->seqno != n->received_seqno + 1) {
300 if(inpkt->seqno >= n->received_seqno + replaywin * 8) {
301 logger(LOG_WARNING, "Lost %d packets from %s (%s)",
302 inpkt->seqno - n->received_seqno - 1, n->name, n->hostname);
304 memset(n->late, 0, replaywin);
305 } else if (inpkt->seqno <= n->received_seqno) {
306 if((n->received_seqno >= replaywin * 8 && inpkt->seqno <= n->received_seqno - replaywin * 8) || !(n->late[(inpkt->seqno / 8) % replaywin] & (1 << inpkt->seqno % 8))) {
307 logger(LOG_WARNING, "Got late or replayed packet from %s (%s), seqno %d, last received %d",
308 n->name, n->hostname, inpkt->seqno, n->received_seqno);
312 for(i = n->received_seqno + 1; i < inpkt->seqno; i++)
313 n->late[(i / 8) % replaywin] |= 1 << i % 8;
317 n->late[(inpkt->seqno / 8) % replaywin] &= ~(1 << inpkt->seqno % 8);
320 if(inpkt->seqno > n->received_seqno)
321 n->received_seqno = inpkt->seqno;
323 if(n->received_seqno > MAX_SEQNO)
326 /* Decompress the packet */
328 length_t origlen = inpkt->len;
330 if(n->incompression) {
331 outpkt = pkt[nextpkt++];
333 if((outpkt->len = uncompress_packet(outpkt->data, inpkt->data, inpkt->len, n->incompression)) < 0) {
334 ifdebug(TRAFFIC) logger(LOG_ERR, "Error while uncompressing packet from %s (%s)",
335 n->name, n->hostname);
341 origlen -= MTU/64 + 20;
346 if(!inpkt->data[12] && !inpkt->data[13])
347 mtu_probe_h(n, inpkt, origlen);
349 receive_packet(n, inpkt);
352 void receive_tcppacket(connection_t *c, char *buffer, int len) {
356 if(c->options & OPTION_TCPONLY)
359 outpkt.priority = -1;
360 memcpy(outpkt.data, buffer, len);
362 receive_packet(c->node, &outpkt);
365 static void send_udppacket(node_t *n, vpn_packet_t *origpkt) {
366 vpn_packet_t pkt1, pkt2;
367 vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
368 vpn_packet_t *inpkt = origpkt;
370 vpn_packet_t *outpkt;
373 #if defined(SOL_IP) && defined(IP_TOS)
374 static int priority = 0;
379 if(!n->status.reachable) {
380 ifdebug(TRAFFIC) logger(LOG_INFO, "Trying to send UDP packet to unreachable node %s (%s)", n->name, n->hostname);
384 /* Make sure we have a valid key */
386 if(!n->status.validkey) {
387 ifdebug(TRAFFIC) logger(LOG_INFO,
388 "No valid key known yet for %s (%s), forwarding via TCP",
389 n->name, n->hostname);
391 if(n->last_req_key + 10 < now) {
393 n->last_req_key = now;
396 send_tcppacket(n->nexthop->connection, origpkt);
401 if(n->options & OPTION_PMTU_DISCOVERY && inpkt->len > n->minmtu && (inpkt->data[12] | inpkt->data[13])) {
402 ifdebug(TRAFFIC) logger(LOG_INFO,
403 "Packet for %s (%s) larger than minimum MTU, forwarding via %s",
404 n->name, n->hostname, n != n->nexthop ? n->nexthop->name : "TCP");
407 send_packet(n->nexthop, origpkt);
409 send_tcppacket(n->nexthop->connection, origpkt);
414 origlen = inpkt->len;
415 origpriority = inpkt->priority;
417 /* Compress the packet */
419 if(n->outcompression) {
420 outpkt = pkt[nextpkt++];
422 if((outpkt->len = compress_packet(outpkt->data, inpkt->data, inpkt->len, n->outcompression)) < 0) {
423 ifdebug(TRAFFIC) logger(LOG_ERR, "Error while compressing packet to %s (%s)",
424 n->name, n->hostname);
431 /* Add sequence number */
433 inpkt->seqno = htonl(++(n->sent_seqno));
434 inpkt->len += sizeof(inpkt->seqno);
436 /* Encrypt the packet */
439 outpkt = pkt[nextpkt++];
441 if(!EVP_EncryptInit_ex(&n->outctx, NULL, NULL, NULL, NULL)
442 || !EVP_EncryptUpdate(&n->outctx, (unsigned char *) &outpkt->seqno, &outlen,
443 (unsigned char *) &inpkt->seqno, inpkt->len)
444 || !EVP_EncryptFinal_ex(&n->outctx, (unsigned char *) &outpkt->seqno + outlen, &outpad)) {
445 ifdebug(TRAFFIC) logger(LOG_ERR, "Error while encrypting packet to %s (%s): %s",
446 n->name, n->hostname, ERR_error_string(ERR_get_error(), NULL));
450 outpkt->len = outlen + outpad;
454 /* Add the message authentication code */
456 if(n->outdigest && n->outmaclength) {
457 HMAC(n->outdigest, n->outkey, n->outkeylength, (unsigned char *) &inpkt->seqno,
458 inpkt->len, (unsigned char *) &inpkt->seqno + inpkt->len, NULL);
459 inpkt->len += n->outmaclength;
462 /* Determine which socket we have to use */
464 for(sock = 0; sock < listen_sockets; sock++)
465 if(n->address.sa.sa_family == listen_socket[sock].sa.sa.sa_family)
468 if(sock >= listen_sockets)
469 sock = 0; /* If none is available, just use the first and hope for the best. */
471 /* Send the packet */
473 #if defined(SOL_IP) && defined(IP_TOS)
474 if(priorityinheritance && origpriority != priority
475 && listen_socket[sock].sa.sa.sa_family == AF_INET) {
476 priority = origpriority;
477 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Setting outgoing packet priority to %d", priority);
478 if(setsockopt(listen_socket[sock].udp, SOL_IP, IP_TOS, &priority, sizeof(priority))) /* SO_PRIORITY doesn't seem to work */
479 logger(LOG_ERR, "System call `%s' failed: %s", "setsockopt", strerror(errno));
483 if(sendto(listen_socket[sock].udp, (char *) &inpkt->seqno, inpkt->len, 0, &(n->address.sa), SALEN(n->address.sa)) < 0 && !sockwouldblock(sockerrno)) {
484 if(sockmsgsize(sockerrno)) {
485 if(n->maxmtu >= origlen)
486 n->maxmtu = origlen - 1;
487 if(n->mtu >= origlen)
488 n->mtu = origlen - 1;
490 logger(LOG_ERR, "Error sending packet to %s (%s): %s", n->name, n->hostname, sockstrerror(sockerrno));
494 origpkt->len = origlen;
498 send a packet to the given vpn ip.
500 void send_packet(const node_t *n, vpn_packet_t *packet) {
505 memcpy(packet->data, mymac.x, ETH_ALEN);
506 write_packet(packet);
510 ifdebug(TRAFFIC) logger(LOG_ERR, "Sending packet of %d bytes to %s (%s)",
511 packet->len, n->name, n->hostname);
513 if(!n->status.reachable) {
514 ifdebug(TRAFFIC) logger(LOG_INFO, "Node %s (%s) is not reachable",
515 n->name, n->hostname);
519 via = (packet->priority == -1 || n->via == myself) ? n->nexthop : n->via;
522 ifdebug(TRAFFIC) logger(LOG_INFO, "Sending packet to %s via %s (%s)",
523 n->name, via->name, n->via->hostname);
525 if(packet->priority == -1 || ((myself->options | via->options) & OPTION_TCPONLY)) {
526 if(!send_tcppacket(via->connection, packet))
527 terminate_connection(via->connection, true);
529 send_udppacket(via, packet);
532 /* Broadcast a packet using the minimum spanning tree */
534 void broadcast_packet(const node_t *from, vpn_packet_t *packet) {
538 ifdebug(TRAFFIC) logger(LOG_INFO, "Broadcasting packet of %d bytes from %s (%s)",
539 packet->len, from->name, from->hostname);
542 send_packet(myself, packet);
544 // In TunnelServer mode, do not forward broadcast packets.
545 // The MST might not be valid and create loops.
550 for(node = connection_tree->head; node; node = node->next) {
553 if(c->status.active && c->status.mst && c != from->nexthop->connection)
554 send_packet(c->node, packet);
558 static node_t *try_harder(const sockaddr_t *from, const vpn_packet_t *pkt) {
562 static time_t last_hard_try = 0;
564 for(node = edge_weight_tree->head; node; node = node->next) {
567 if(sockaddrcmp_noport(from, &e->address)) {
568 if(last_hard_try == now)
576 if(!try_mac(e->to, pkt))
586 void handle_incoming_vpn_data(int sock) {
590 socklen_t fromlen = sizeof(from);
593 pkt.len = recvfrom(sock, (char *) &pkt.seqno, MAXSIZE, 0, &from.sa, &fromlen);
596 if(!sockwouldblock(sockerrno))
597 logger(LOG_ERR, "Receiving packet failed: %s", sockstrerror(sockerrno));
601 sockaddrunmap(&from); /* Some braindead IPv6 implementations do stupid things. */
603 n = lookup_node_udp(&from);
606 n = try_harder(&from, &pkt);
608 update_node_udp(n, &from);
609 else ifdebug(PROTOCOL) {
610 hostname = sockaddr2hostname(&from);
611 logger(LOG_WARNING, "Received UDP packet from unknown source %s", hostname);
619 receive_udppacket(n, &pkt);