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>
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;
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) {
89 timeout = pinginterval;
93 ifdebug(TRAFFIC) logger(LOG_INFO, "%s (%s) did not respond to UDP ping, restarting PMTU discovery", n->name, n->hostname);
99 if(n->mtuprobes >= 10 && n->mtuprobes < 32 && !n->minmtu) {
100 ifdebug(TRAFFIC) logger(LOG_INFO, "No response to MTU probes from %s (%s)", n->name, n->hostname);
104 if(n->mtuprobes == 30 || (n->mtuprobes < 30 && n->minmtu >= n->maxmtu)) {
105 if(n->minmtu > n->maxmtu)
106 n->minmtu = n->maxmtu;
108 n->maxmtu = n->minmtu;
110 ifdebug(TRAFFIC) logger(LOG_INFO, "Fixing MTU of %s (%s) to %d after %d probes", n->name, n->hostname, n->mtu, n->mtuprobes);
114 if(n->mtuprobes == 31) {
115 timeout = pinginterval;
117 } else if(n->mtuprobes == 32) {
118 timeout = pingtimeout;
121 for(i = 0; i < 3; i++) {
122 if(n->maxmtu <= n->minmtu)
125 len = n->minmtu + 1 + rand() % (n->maxmtu - n->minmtu);
130 memset(packet.data, 0, 14);
131 RAND_pseudo_bytes(packet.data + 14, len - 14);
135 ifdebug(TRAFFIC) logger(LOG_INFO, "Sending MTU probe length %d to %s (%s)", len, n->name, n->hostname);
137 send_udppacket(n, &packet);
141 n->mtuevent = new_event();
142 n->mtuevent->handler = (event_handler_t)send_mtu_probe;
143 n->mtuevent->data = n;
144 n->mtuevent->time = now + timeout;
145 event_add(n->mtuevent);
148 void mtu_probe_h(node_t *n, vpn_packet_t *packet, length_t len) {
149 ifdebug(TRAFFIC) logger(LOG_INFO, "Got MTU probe length %d from %s (%s)", packet->len, n->name, n->hostname);
151 if(!packet->data[0]) {
153 send_udppacket(n, packet);
155 if(n->mtuprobes > 30) {
169 static length_t compress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level) {
171 memcpy(dest, source, len);
173 } else if(level == 10) {
175 lzo_uint lzolen = MAXSIZE;
176 lzo1x_1_compress(source, len, dest, &lzolen, lzo_wrkmem);
181 } else if(level < 10) {
183 unsigned long destlen = MAXSIZE;
184 if(compress2(dest, &destlen, source, len, level) == Z_OK)
191 lzo_uint lzolen = MAXSIZE;
192 lzo1x_999_compress(source, len, dest, &lzolen, lzo_wrkmem);
202 static length_t uncompress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level) {
204 memcpy(dest, source, len);
206 } else if(level > 9) {
208 lzo_uint lzolen = MAXSIZE;
209 if(lzo1x_decompress_safe(source, len, dest, &lzolen, NULL) == LZO_E_OK)
217 unsigned long destlen = MAXSIZE;
218 if(uncompress(dest, &destlen, source, len) == Z_OK)
230 static void receive_packet(node_t *n, vpn_packet_t *packet) {
231 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Received packet of %d bytes from %s (%s)",
232 packet->len, n->name, n->hostname);
237 static bool try_mac(const node_t *n, const vpn_packet_t *inpkt) {
238 unsigned char hmac[EVP_MAX_MD_SIZE];
240 if(!n->indigest || !n->inmaclength || !n->inkey || inpkt->len < sizeof inpkt->seqno + n->inmaclength)
243 HMAC(n->indigest, n->inkey, n->inkeylength, (unsigned char *) &inpkt->seqno, inpkt->len - n->inmaclength, (unsigned char *)hmac, NULL);
245 return !memcmp(hmac, (char *) &inpkt->seqno + inpkt->len - n->inmaclength, n->inmaclength);
248 static void receive_udppacket(node_t *n, vpn_packet_t *inpkt) {
249 vpn_packet_t pkt1, pkt2;
250 vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
252 vpn_packet_t *outpkt = pkt[0];
254 unsigned char hmac[EVP_MAX_MD_SIZE];
258 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Got packet from %s (%s) but he hasn't got our key yet",
259 n->name, n->hostname);
263 /* Check packet length */
265 if(inpkt->len < sizeof(inpkt->seqno) + n->inmaclength) {
266 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Got too short packet from %s (%s)",
267 n->name, n->hostname);
271 /* Check the message authentication code */
273 if(n->indigest && n->inmaclength) {
274 inpkt->len -= n->inmaclength;
275 HMAC(n->indigest, n->inkey, n->inkeylength,
276 (unsigned char *) &inpkt->seqno, inpkt->len, (unsigned char *)hmac, NULL);
278 if(memcmp(hmac, (char *) &inpkt->seqno + inpkt->len, n->inmaclength)) {
279 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Got unauthenticated packet from %s (%s)",
280 n->name, n->hostname);
285 /* Decrypt the packet */
288 outpkt = pkt[nextpkt++];
290 if(!EVP_DecryptInit_ex(&n->inctx, NULL, NULL, NULL, NULL)
291 || !EVP_DecryptUpdate(&n->inctx, (unsigned char *) &outpkt->seqno, &outlen,
292 (unsigned char *) &inpkt->seqno, inpkt->len)
293 || !EVP_DecryptFinal_ex(&n->inctx, (unsigned char *) &outpkt->seqno + outlen, &outpad)) {
294 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Error decrypting packet from %s (%s): %s",
295 n->name, n->hostname, ERR_error_string(ERR_get_error(), NULL));
299 outpkt->len = outlen + outpad;
303 /* Check the sequence number */
305 inpkt->len -= sizeof(inpkt->seqno);
306 inpkt->seqno = ntohl(inpkt->seqno);
309 if(inpkt->seqno != n->received_seqno + 1) {
310 if(inpkt->seqno >= n->received_seqno + replaywin * 8) {
311 if(n->farfuture++ < replaywin >> 2) {
312 logger(LOG_WARNING, "Packet from %s (%s) is %d seqs in the future, dropped (%u)",
313 n->name, n->hostname, inpkt->seqno - n->received_seqno - 1, n->farfuture);
316 logger(LOG_WARNING, "Lost %d packets from %s (%s)",
317 inpkt->seqno - n->received_seqno - 1, n->name, n->hostname);
318 memset(n->late, 0, replaywin);
319 } else if (inpkt->seqno <= n->received_seqno) {
320 if((n->received_seqno >= replaywin * 8 && inpkt->seqno <= n->received_seqno - replaywin * 8) || !(n->late[(inpkt->seqno / 8) % replaywin] & (1 << inpkt->seqno % 8))) {
321 logger(LOG_WARNING, "Got late or replayed packet from %s (%s), seqno %d, last received %d",
322 n->name, n->hostname, inpkt->seqno, n->received_seqno);
326 for(i = n->received_seqno + 1; i < inpkt->seqno; i++)
327 n->late[(i / 8) % replaywin] |= 1 << i % 8;
332 n->late[(inpkt->seqno / 8) % replaywin] &= ~(1 << inpkt->seqno % 8);
335 if(inpkt->seqno > n->received_seqno)
336 n->received_seqno = inpkt->seqno;
338 if(n->received_seqno > MAX_SEQNO)
341 /* Decompress the packet */
343 length_t origlen = inpkt->len;
345 if(n->incompression) {
346 outpkt = pkt[nextpkt++];
348 if((outpkt->len = uncompress_packet(outpkt->data, inpkt->data, inpkt->len, n->incompression)) < 0) {
349 ifdebug(TRAFFIC) logger(LOG_ERR, "Error while uncompressing packet from %s (%s)",
350 n->name, n->hostname);
356 origlen -= MTU/64 + 20;
361 if(!inpkt->data[12] && !inpkt->data[13])
362 mtu_probe_h(n, inpkt, origlen);
364 receive_packet(n, inpkt);
367 void receive_tcppacket(connection_t *c, const char *buffer, int len) {
371 if(c->options & OPTION_TCPONLY)
374 outpkt.priority = -1;
375 memcpy(outpkt.data, buffer, len);
377 receive_packet(c->node, &outpkt);
380 static void send_udppacket(node_t *n, vpn_packet_t *origpkt) {
381 vpn_packet_t pkt1, pkt2;
382 vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
383 vpn_packet_t *inpkt = origpkt;
385 vpn_packet_t *outpkt;
388 #if defined(SOL_IP) && defined(IP_TOS)
389 static int priority = 0;
393 if(!n->status.reachable) {
394 ifdebug(TRAFFIC) logger(LOG_INFO, "Trying to send UDP packet to unreachable node %s (%s)", n->name, n->hostname);
398 /* Make sure we have a valid key */
400 if(!n->status.validkey) {
401 ifdebug(TRAFFIC) logger(LOG_INFO,
402 "No valid key known yet for %s (%s), forwarding via TCP",
403 n->name, n->hostname);
405 if(n->last_req_key + 10 <= now) {
407 n->last_req_key = now;
410 send_tcppacket(n->nexthop->connection, origpkt);
415 if(n->options & OPTION_PMTU_DISCOVERY && inpkt->len > n->minmtu && (inpkt->data[12] | inpkt->data[13])) {
416 ifdebug(TRAFFIC) logger(LOG_INFO,
417 "Packet for %s (%s) larger than minimum MTU, forwarding via %s",
418 n->name, n->hostname, n != n->nexthop ? n->nexthop->name : "TCP");
421 send_packet(n->nexthop, origpkt);
423 send_tcppacket(n->nexthop->connection, origpkt);
428 origlen = inpkt->len;
429 origpriority = inpkt->priority;
431 /* Compress the packet */
433 if(n->outcompression) {
434 outpkt = pkt[nextpkt++];
436 if((outpkt->len = compress_packet(outpkt->data, inpkt->data, inpkt->len, n->outcompression)) < 0) {
437 ifdebug(TRAFFIC) logger(LOG_ERR, "Error while compressing packet to %s (%s)",
438 n->name, n->hostname);
445 /* Add sequence number */
447 inpkt->seqno = htonl(++(n->sent_seqno));
448 inpkt->len += sizeof(inpkt->seqno);
450 /* Encrypt the packet */
453 outpkt = pkt[nextpkt++];
455 if(!EVP_EncryptInit_ex(&n->outctx, NULL, NULL, NULL, NULL)
456 || !EVP_EncryptUpdate(&n->outctx, (unsigned char *) &outpkt->seqno, &outlen,
457 (unsigned char *) &inpkt->seqno, inpkt->len)
458 || !EVP_EncryptFinal_ex(&n->outctx, (unsigned char *) &outpkt->seqno + outlen, &outpad)) {
459 ifdebug(TRAFFIC) logger(LOG_ERR, "Error while encrypting packet to %s (%s): %s",
460 n->name, n->hostname, ERR_error_string(ERR_get_error(), NULL));
464 outpkt->len = outlen + outpad;
468 /* Add the message authentication code */
470 if(n->outdigest && n->outmaclength) {
471 HMAC(n->outdigest, n->outkey, n->outkeylength, (unsigned char *) &inpkt->seqno,
472 inpkt->len, (unsigned char *) &inpkt->seqno + inpkt->len, NULL);
473 inpkt->len += n->outmaclength;
476 /* Determine which socket we have to use */
478 if(n->address.sa.sa_family != listen_socket[n->sock].sa.sa.sa_family) {
479 for(int sock = 0; sock < listen_sockets; sock++) {
480 if(n->address.sa.sa_family == listen_socket[sock].sa.sa.sa_family) {
487 /* Send the packet */
489 #if defined(SOL_IP) && defined(IP_TOS)
490 if(priorityinheritance && origpriority != priority
491 && listen_socket[n->sock].sa.sa.sa_family == AF_INET) {
492 priority = origpriority;
493 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Setting outgoing packet priority to %d", priority);
494 if(setsockopt(listen_socket[n->sock].udp, SOL_IP, IP_TOS, &priority, sizeof(priority))) /* SO_PRIORITY doesn't seem to work */
495 logger(LOG_ERR, "System call `%s' failed: %s", "setsockopt", strerror(errno));
499 if(sendto(listen_socket[n->sock].udp, (char *) &inpkt->seqno, inpkt->len, 0, &(n->address.sa), SALEN(n->address.sa)) < 0 && !sockwouldblock(sockerrno)) {
500 if(sockmsgsize(sockerrno)) {
501 if(n->maxmtu >= origlen)
502 n->maxmtu = origlen - 1;
503 if(n->mtu >= origlen)
504 n->mtu = origlen - 1;
506 logger(LOG_ERR, "Error sending packet to %s (%s): %s", n->name, n->hostname, sockstrerror(sockerrno));
510 origpkt->len = origlen;
514 send a packet to the given vpn ip.
516 void send_packet(const node_t *n, vpn_packet_t *packet) {
521 memcpy(packet->data, mymac.x, ETH_ALEN);
522 devops.write(packet);
526 ifdebug(TRAFFIC) logger(LOG_ERR, "Sending packet of %d bytes to %s (%s)",
527 packet->len, n->name, n->hostname);
529 if(!n->status.reachable) {
530 ifdebug(TRAFFIC) logger(LOG_INFO, "Node %s (%s) is not reachable",
531 n->name, n->hostname);
535 via = (packet->priority == -1 || n->via == myself) ? n->nexthop : n->via;
538 ifdebug(TRAFFIC) logger(LOG_INFO, "Sending packet to %s via %s (%s)",
539 n->name, via->name, n->via->hostname);
541 if(packet->priority == -1 || ((myself->options | via->options) & OPTION_TCPONLY)) {
542 if(!send_tcppacket(via->connection, packet))
543 terminate_connection(via->connection, true);
545 send_udppacket(via, packet);
548 /* Broadcast a packet using the minimum spanning tree */
550 void broadcast_packet(const node_t *from, vpn_packet_t *packet) {
554 ifdebug(TRAFFIC) logger(LOG_INFO, "Broadcasting packet of %d bytes from %s (%s)",
555 packet->len, from->name, from->hostname);
558 send_packet(myself, packet);
560 // In TunnelServer mode, do not forward broadcast packets.
561 // The MST might not be valid and create loops.
566 for(node = connection_tree->head; node; node = node->next) {
569 if(c->status.active && c->status.mst && c != from->nexthop->connection)
570 send_packet(c->node, packet);
574 static node_t *try_harder(const sockaddr_t *from, const vpn_packet_t *pkt) {
579 static time_t last_hard_try = 0;
581 for(node = edge_weight_tree->head; node; node = node->next) {
587 if(sockaddrcmp_noport(from, &e->address)) {
588 if(last_hard_try == now)
593 if(!try_mac(e->to, pkt))
606 void handle_incoming_vpn_data(int sock) {
610 socklen_t fromlen = sizeof(from);
613 pkt.len = recvfrom(listen_socket[sock].udp, (char *) &pkt.seqno, MAXSIZE, 0, &from.sa, &fromlen);
616 if(!sockwouldblock(sockerrno))
617 logger(LOG_ERR, "Receiving packet failed: %s", sockstrerror(sockerrno));
621 sockaddrunmap(&from); /* Some braindead IPv6 implementations do stupid things. */
623 n = lookup_node_udp(&from);
626 n = try_harder(&from, &pkt);
628 update_node_udp(n, &from);
629 else ifdebug(PROTOCOL) {
630 hostname = sockaddr2hostname(&from);
631 logger(LOG_WARNING, "Received UDP packet from unknown source %s", hostname);
641 receive_udppacket(n, &pkt);