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>
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2 of the License, or
9 (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License along
17 with this program; if not, write to the Free Software Foundation, Inc.,
18 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23 #include <openssl/rand.h>
24 #include <openssl/err.h>
25 #include <openssl/evp.h>
26 #include <openssl/pem.h>
27 #include <openssl/hmac.h>
39 #include "connection.h"
57 static char lzo_wrkmem[LZO1X_999_MEM_COMPRESS > LZO1X_1_MEM_COMPRESS ? LZO1X_999_MEM_COMPRESS : LZO1X_1_MEM_COMPRESS];
60 static void send_udppacket(node_t *, vpn_packet_t *);
62 #define MAX_SEQNO 1073741824
64 // mtuprobes == 1..30: initial discovery, send bursts with 1 second interval
65 // mtuprobes == 31: sleep pinginterval seconds
66 // mtuprobes == 32: send 1 burst, sleep pingtimeout second
67 // mtuprobes == 33: no response from other side, restart PMTU discovery process
69 void send_mtu_probe(node_t *n) {
77 if(!n->status.reachable || !n->status.validkey) {
78 ifdebug(TRAFFIC) logger(LOG_INFO, "Trying to send MTU probe to unreachable or rekeying node %s (%s)", n->name, n->hostname);
83 if(n->mtuprobes > 32) {
84 ifdebug(TRAFFIC) logger(LOG_INFO, "%s (%s) did not respond to UDP ping, restarting PMTU discovery", n->name, n->hostname);
90 if(n->mtuprobes >= 10 && !n->minmtu) {
91 ifdebug(TRAFFIC) logger(LOG_INFO, "No response to MTU probes from %s (%s)", n->name, n->hostname);
96 if(n->mtuprobes == 30 || (n->mtuprobes < 30 && n->minmtu >= n->maxmtu)) {
97 if(n->minmtu > n->maxmtu)
98 n->minmtu = n->maxmtu;
100 n->maxmtu = n->minmtu;
102 ifdebug(TRAFFIC) logger(LOG_INFO, "Fixing MTU of %s (%s) to %d after %d probes", n->name, n->hostname, n->mtu, n->mtuprobes);
106 if(n->mtuprobes == 31) {
107 timeout = pinginterval;
109 } else if(n->mtuprobes == 32) {
110 timeout = pingtimeout;
113 for(i = 0; i < 3; i++) {
114 if(n->maxmtu <= n->minmtu)
117 len = n->minmtu + 1 + rand() % (n->maxmtu - n->minmtu);
122 memset(packet.data, 0, 14);
123 RAND_pseudo_bytes(packet.data + 14, len - 14);
127 ifdebug(TRAFFIC) logger(LOG_INFO, "Sending MTU probe length %d to %s (%s)", len, n->name, n->hostname);
129 send_udppacket(n, &packet);
133 n->mtuevent = new_event();
134 n->mtuevent->handler = (event_handler_t)send_mtu_probe;
135 n->mtuevent->data = n;
136 n->mtuevent->time = now + timeout;
137 event_add(n->mtuevent);
140 void mtu_probe_h(node_t *n, vpn_packet_t *packet, length_t len) {
141 ifdebug(TRAFFIC) logger(LOG_INFO, "Got MTU probe length %d from %s (%s)", packet->len, n->name, n->hostname);
143 if(!packet->data[0]) {
145 send_udppacket(n, packet);
151 if(n->mtuprobes > 30)
156 static length_t compress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level) {
158 memcpy(dest, source, len);
160 } else if(level == 10) {
162 lzo_uint lzolen = MAXSIZE;
163 lzo1x_1_compress(source, len, dest, &lzolen, lzo_wrkmem);
168 } else if(level < 10) {
170 unsigned long destlen = MAXSIZE;
171 if(compress2(dest, &destlen, source, len, level) == Z_OK)
178 lzo_uint lzolen = MAXSIZE;
179 lzo1x_999_compress(source, len, dest, &lzolen, lzo_wrkmem);
189 static length_t uncompress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level) {
191 memcpy(dest, source, len);
193 } else if(level > 9) {
195 lzo_uint lzolen = MAXSIZE;
196 if(lzo1x_decompress_safe(source, len, dest, &lzolen, NULL) == LZO_E_OK)
204 unsigned long destlen = MAXSIZE;
205 if(uncompress(dest, &destlen, source, len) == Z_OK)
217 static void receive_packet(node_t *n, vpn_packet_t *packet) {
218 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Received packet of %d bytes from %s (%s)",
219 packet->len, n->name, n->hostname);
224 static bool try_mac(const node_t *n, const vpn_packet_t *inpkt) {
225 unsigned char hmac[EVP_MAX_MD_SIZE];
227 if(!n->indigest || !n->inmaclength || !n->inkey || inpkt->len < sizeof inpkt->seqno + n->inmaclength)
230 HMAC(n->indigest, n->inkey, n->inkeylength, (unsigned char *) &inpkt->seqno, inpkt->len - n->inmaclength, (unsigned char *)hmac, NULL);
232 return !memcmp(hmac, (char *) &inpkt->seqno + inpkt->len - n->inmaclength, n->inmaclength);
235 static void receive_udppacket(node_t *n, vpn_packet_t *inpkt) {
236 vpn_packet_t pkt1, pkt2;
237 vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
239 vpn_packet_t *outpkt = pkt[0];
241 unsigned char hmac[EVP_MAX_MD_SIZE];
245 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Got packet from %s (%s) but he hasn't got our key yet",
246 n->name, n->hostname);
250 /* Check packet length */
252 if(inpkt->len < sizeof(inpkt->seqno) + n->inmaclength) {
253 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Got too short packet from %s (%s)",
254 n->name, n->hostname);
258 /* Check the message authentication code */
260 if(n->indigest && n->inmaclength) {
261 inpkt->len -= n->inmaclength;
262 HMAC(n->indigest, n->inkey, n->inkeylength,
263 (unsigned char *) &inpkt->seqno, inpkt->len, (unsigned char *)hmac, NULL);
265 if(memcmp(hmac, (char *) &inpkt->seqno + inpkt->len, n->inmaclength)) {
266 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Got unauthenticated packet from %s (%s)",
267 n->name, n->hostname);
272 /* Decrypt the packet */
275 outpkt = pkt[nextpkt++];
277 if(!EVP_DecryptInit_ex(&n->inctx, NULL, NULL, NULL, NULL)
278 || !EVP_DecryptUpdate(&n->inctx, (unsigned char *) &outpkt->seqno, &outlen,
279 (unsigned char *) &inpkt->seqno, inpkt->len)
280 || !EVP_DecryptFinal_ex(&n->inctx, (unsigned char *) &outpkt->seqno + outlen, &outpad)) {
281 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Error decrypting packet from %s (%s): %s",
282 n->name, n->hostname, ERR_error_string(ERR_get_error(), NULL));
286 outpkt->len = outlen + outpad;
290 /* Check the sequence number */
292 inpkt->len -= sizeof(inpkt->seqno);
293 inpkt->seqno = ntohl(inpkt->seqno);
295 if(inpkt->seqno != n->received_seqno + 1) {
296 if(inpkt->seqno >= n->received_seqno + sizeof(n->late) * 8) {
297 logger(LOG_WARNING, "Lost %d packets from %s (%s)",
298 inpkt->seqno - n->received_seqno - 1, n->name, n->hostname);
300 memset(n->late, 0, sizeof(n->late));
301 } else if (inpkt->seqno <= n->received_seqno) {
302 if((n->received_seqno >= sizeof(n->late) * 8 && inpkt->seqno <= n->received_seqno - sizeof(n->late) * 8) || !(n->late[(inpkt->seqno / 8) % sizeof(n->late)] & (1 << inpkt->seqno % 8))) {
303 logger(LOG_WARNING, "Got late or replayed packet from %s (%s), seqno %d, last received %d",
304 n->name, n->hostname, inpkt->seqno, n->received_seqno);
308 for(i = n->received_seqno + 1; i < inpkt->seqno; i++)
309 n->late[(i / 8) % sizeof(n->late)] |= 1 << i % 8;
313 n->late[(inpkt->seqno / 8) % sizeof(n->late)] &= ~(1 << inpkt->seqno % 8);
315 if(inpkt->seqno > n->received_seqno)
316 n->received_seqno = inpkt->seqno;
318 if(n->received_seqno > MAX_SEQNO)
321 /* Decompress the packet */
323 length_t origlen = inpkt->len;
325 if(n->incompression) {
326 outpkt = pkt[nextpkt++];
328 if((outpkt->len = uncompress_packet(outpkt->data, inpkt->data, inpkt->len, n->incompression)) < 0) {
329 ifdebug(TRAFFIC) logger(LOG_ERR, "Error while uncompressing packet from %s (%s)",
330 n->name, n->hostname);
336 origlen -= MTU/64 + 20;
341 if(!inpkt->data[12] && !inpkt->data[13])
342 mtu_probe_h(n, inpkt, origlen);
344 receive_packet(n, inpkt);
347 void receive_tcppacket(connection_t *c, char *buffer, int len) {
351 if(c->options & OPTION_TCPONLY)
354 outpkt.priority = -1;
355 memcpy(outpkt.data, buffer, len);
357 receive_packet(c->node, &outpkt);
360 static void send_udppacket(node_t *n, vpn_packet_t *origpkt) {
361 vpn_packet_t pkt1, pkt2;
362 vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
363 vpn_packet_t *inpkt = origpkt;
365 vpn_packet_t *outpkt;
368 static int priority = 0;
372 if(!n->status.reachable) {
373 ifdebug(TRAFFIC) logger(LOG_INFO, "Trying to send UDP packet to unreachable node %s (%s)", n->name, n->hostname);
377 /* Make sure we have a valid key */
379 if(!n->status.validkey) {
380 ifdebug(TRAFFIC) logger(LOG_INFO,
381 "No valid key known yet for %s (%s), forwarding via TCP",
382 n->name, n->hostname);
384 if(n->last_req_key + 10 < now) {
386 n->last_req_key = now;
389 send_tcppacket(n->nexthop->connection, origpkt);
394 if(n->options & OPTION_PMTU_DISCOVERY && inpkt->len > n->minmtu && (inpkt->data[12] | inpkt->data[13])) {
395 ifdebug(TRAFFIC) logger(LOG_INFO,
396 "Packet for %s (%s) larger than minimum MTU, forwarding via %s",
397 n->name, n->hostname, n != n->nexthop ? n->nexthop->name : "TCP");
400 send_packet(n->nexthop, origpkt);
402 send_tcppacket(n->nexthop->connection, origpkt);
407 origlen = inpkt->len;
408 origpriority = inpkt->priority;
410 /* Compress the packet */
412 if(n->outcompression) {
413 outpkt = pkt[nextpkt++];
415 if((outpkt->len = compress_packet(outpkt->data, inpkt->data, inpkt->len, n->outcompression)) < 0) {
416 ifdebug(TRAFFIC) logger(LOG_ERR, "Error while compressing packet to %s (%s)",
417 n->name, n->hostname);
424 /* Add sequence number */
426 inpkt->seqno = htonl(++(n->sent_seqno));
427 inpkt->len += sizeof(inpkt->seqno);
429 /* Encrypt the packet */
432 outpkt = pkt[nextpkt++];
434 if(!EVP_EncryptInit_ex(&n->outctx, NULL, NULL, NULL, NULL)
435 || !EVP_EncryptUpdate(&n->outctx, (unsigned char *) &outpkt->seqno, &outlen,
436 (unsigned char *) &inpkt->seqno, inpkt->len)
437 || !EVP_EncryptFinal_ex(&n->outctx, (unsigned char *) &outpkt->seqno + outlen, &outpad)) {
438 ifdebug(TRAFFIC) logger(LOG_ERR, "Error while encrypting packet to %s (%s): %s",
439 n->name, n->hostname, ERR_error_string(ERR_get_error(), NULL));
443 outpkt->len = outlen + outpad;
447 /* Add the message authentication code */
449 if(n->outdigest && n->outmaclength) {
450 HMAC(n->outdigest, n->outkey, n->outkeylength, (unsigned char *) &inpkt->seqno,
451 inpkt->len, (unsigned char *) &inpkt->seqno + inpkt->len, NULL);
452 inpkt->len += n->outmaclength;
455 /* Determine which socket we have to use */
457 for(sock = 0; sock < listen_sockets; sock++)
458 if(n->address.sa.sa_family == listen_socket[sock].sa.sa.sa_family)
461 if(sock >= listen_sockets)
462 sock = 0; /* If none is available, just use the first and hope for the best. */
464 /* Send the packet */
466 #if defined(SOL_IP) && defined(IP_TOS)
467 if(priorityinheritance && origpriority != priority
468 && listen_socket[sock].sa.sa.sa_family == AF_INET) {
469 priority = origpriority;
470 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Setting outgoing packet priority to %d", priority);
471 if(setsockopt(listen_socket[sock].udp, SOL_IP, IP_TOS, &priority, sizeof(priority))) /* SO_PRIORITY doesn't seem to work */
472 logger(LOG_ERR, "System call `%s' failed: %s", "setsockopt", strerror(errno));
476 if(sendto(listen_socket[sock].udp, (char *) &inpkt->seqno, inpkt->len, 0, &(n->address.sa), SALEN(n->address.sa)) < 0 && !sockwouldblock(sockerrno)) {
477 if(sockmsgsize(sockerrno)) {
478 if(n->maxmtu >= origlen)
479 n->maxmtu = origlen - 1;
480 if(n->mtu >= origlen)
481 n->mtu = origlen - 1;
483 logger(LOG_ERR, "Error sending packet to %s (%s): %s", n->name, n->hostname, sockstrerror(sockerrno));
487 origpkt->len = origlen;
491 send a packet to the given vpn ip.
493 void send_packet(const node_t *n, vpn_packet_t *packet) {
498 memcpy(packet->data, mymac.x, ETH_ALEN);
499 write_packet(packet);
503 ifdebug(TRAFFIC) logger(LOG_ERR, "Sending packet of %d bytes to %s (%s)",
504 packet->len, n->name, n->hostname);
506 if(!n->status.reachable) {
507 ifdebug(TRAFFIC) logger(LOG_INFO, "Node %s (%s) is not reachable",
508 n->name, n->hostname);
512 via = (packet->priority == -1 || n->via == myself) ? n->nexthop : n->via;
515 ifdebug(TRAFFIC) logger(LOG_INFO, "Sending packet to %s via %s (%s)",
516 n->name, via->name, n->via->hostname);
518 if(packet->priority == -1 || ((myself->options | via->options) & OPTION_TCPONLY)) {
519 if(!send_tcppacket(via->connection, packet))
520 terminate_connection(via->connection, true);
522 send_udppacket(via, packet);
525 /* Broadcast a packet using the minimum spanning tree */
527 void broadcast_packet(const node_t *from, vpn_packet_t *packet) {
531 ifdebug(TRAFFIC) logger(LOG_INFO, "Broadcasting packet of %d bytes from %s (%s)",
532 packet->len, from->name, from->hostname);
535 send_packet(myself, packet);
537 // In TunnelServer mode, do not forward broadcast packets.
538 // The MST might not be valid and create loops.
543 for(node = connection_tree->head; node; node = node->next) {
546 if(c->status.active && c->status.mst && c != from->nexthop->connection)
547 send_packet(c->node, packet);
551 static node_t *try_harder(const sockaddr_t *from, const vpn_packet_t *pkt) {
555 static time_t last_hard_try = 0;
557 for(node = edge_weight_tree->head; node; node = node->next) {
560 if(sockaddrcmp_noport(from, &e->address)) {
561 if(last_hard_try == now)
569 if(!try_mac(e->to, pkt))
579 void handle_incoming_vpn_data(int sock) {
583 socklen_t fromlen = sizeof(from);
586 pkt.len = recvfrom(sock, (char *) &pkt.seqno, MAXSIZE, 0, &from.sa, &fromlen);
589 if(!sockwouldblock(sockerrno))
590 logger(LOG_ERR, "Receiving packet failed: %s", sockstrerror(sockerrno));
594 sockaddrunmap(&from); /* Some braindead IPv6 implementations do stupid things. */
596 n = lookup_node_udp(&from);
599 n = try_harder(&from, &pkt);
601 update_node_udp(n, &from);
602 else ifdebug(PROTOCOL) {
603 hostname = sockaddr2hostname(&from);
604 logger(LOG_WARNING, "Received UDP packet from unknown source %s", hostname);
612 receive_udppacket(n, &pkt);