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>
38 #include "splay_tree.h"
41 #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 #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 static void send_mtu_probe_handler(int fd, short events, void *data) {
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 randomize(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 event_add(&n->mtuevent, &(struct timeval){timeout, 0});
139 void send_mtu_probe(node_t *n) {
140 if(!timeout_initialized(&n->mtuevent))
141 timeout_set(&n->mtuevent, send_mtu_probe_handler, n);
142 send_mtu_probe_handler(0, 0, n);
145 void mtu_probe_h(node_t *n, vpn_packet_t *packet, length_t len) {
146 ifdebug(TRAFFIC) logger(LOG_INFO, "Got MTU probe length %d from %s (%s)", packet->len, n->name, n->hostname);
148 if(!packet->data[0]) {
150 send_udppacket(n, packet);
156 if(n->mtuprobes > 30)
161 static length_t compress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level) {
163 memcpy(dest, source, len);
165 } else if(level == 10) {
167 lzo_uint lzolen = MAXSIZE;
168 lzo1x_1_compress(source, len, dest, &lzolen, lzo_wrkmem);
173 } else if(level < 10) {
175 unsigned long destlen = MAXSIZE;
176 if(compress2(dest, &destlen, source, len, level) == Z_OK)
183 lzo_uint lzolen = MAXSIZE;
184 lzo1x_999_compress(source, len, dest, &lzolen, lzo_wrkmem);
194 static length_t uncompress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level) {
196 memcpy(dest, source, len);
198 } else if(level > 9) {
200 lzo_uint lzolen = MAXSIZE;
201 if(lzo1x_decompress_safe(source, len, dest, &lzolen, NULL) == LZO_E_OK)
209 unsigned long destlen = MAXSIZE;
210 if(uncompress(dest, &destlen, source, len) == Z_OK)
222 static void receive_packet(node_t *n, vpn_packet_t *packet) {
223 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Received packet of %d bytes from %s (%s)",
224 packet->len, n->name, n->hostname);
229 static bool try_mac(node_t *n, const vpn_packet_t *inpkt) {
230 if(!digest_active(&n->indigest) || inpkt->len < sizeof inpkt->seqno + digest_length(&n->indigest))
233 return digest_verify(&n->indigest, &inpkt->seqno, inpkt->len - n->indigest.maclength, (const char *)&inpkt->seqno + inpkt->len - n->indigest.maclength);
236 static void receive_udppacket(node_t *n, vpn_packet_t *inpkt) {
237 vpn_packet_t pkt1, pkt2;
238 vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
240 vpn_packet_t *outpkt = pkt[0];
244 if(!cipher_active(&n->incipher)) {
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 + digest_length(&n->indigest)) {
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(digest_active(&n->indigest)) {
261 inpkt->len -= n->indigest.maclength;
262 if(!digest_verify(&n->indigest, &inpkt->seqno, inpkt->len, (const char *)&inpkt->seqno + inpkt->len)) {
263 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Got unauthenticated packet from %s (%s)", n->name, n->hostname);
267 /* Decrypt the packet */
269 if(cipher_active(&n->incipher)) {
270 outpkt = pkt[nextpkt++];
273 if(!cipher_decrypt(&n->incipher, &inpkt->seqno, inpkt->len, &outpkt->seqno, &outlen, true)) {
274 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Error decrypting packet from %s (%s)", n->name, n->hostname);
278 outpkt->len = outlen;
282 /* Check the sequence number */
284 inpkt->len -= sizeof inpkt->seqno;
285 inpkt->seqno = ntohl(inpkt->seqno);
287 if(inpkt->seqno != n->received_seqno + 1) {
288 if(inpkt->seqno >= n->received_seqno + sizeof n->late * 8) {
289 logger(LOG_WARNING, "Lost %d packets from %s (%s)",
290 inpkt->seqno - n->received_seqno - 1, n->name, n->hostname);
292 memset(n->late, 0, sizeof n->late);
293 } else if (inpkt->seqno <= n->received_seqno) {
294 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))) {
295 logger(LOG_WARNING, "Got late or replayed packet from %s (%s), seqno %d, last received %d",
296 n->name, n->hostname, inpkt->seqno, n->received_seqno);
300 for(i = n->received_seqno + 1; i < inpkt->seqno; i++)
301 n->late[(i / 8) % sizeof n->late] |= 1 << i % 8;
305 n->late[(inpkt->seqno / 8) % sizeof n->late] &= ~(1 << inpkt->seqno % 8);
307 if(inpkt->seqno > n->received_seqno)
308 n->received_seqno = inpkt->seqno;
310 if(n->received_seqno > MAX_SEQNO)
313 /* Decompress the packet */
315 length_t origlen = inpkt->len;
317 if(n->incompression) {
318 outpkt = pkt[nextpkt++];
320 if((outpkt->len = uncompress_packet(outpkt->data, inpkt->data, inpkt->len, n->incompression)) < 0) {
321 ifdebug(TRAFFIC) logger(LOG_ERR, "Error while uncompressing packet from %s (%s)",
322 n->name, n->hostname);
328 origlen -= MTU/64 + 20;
333 if(!inpkt->data[12] && !inpkt->data[13])
334 mtu_probe_h(n, inpkt, origlen);
336 receive_packet(n, inpkt);
339 void receive_tcppacket(connection_t *c, char *buffer, int len) {
343 if(c->options & OPTION_TCPONLY)
346 outpkt.priority = -1;
347 memcpy(outpkt.data, buffer, len);
349 receive_packet(c->node, &outpkt);
352 static void send_udppacket(node_t *n, vpn_packet_t *origpkt) {
353 vpn_packet_t pkt1, pkt2;
354 vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
355 vpn_packet_t *inpkt = origpkt;
357 vpn_packet_t *outpkt;
360 #if defined(SOL_IP) && defined(IP_TOS)
361 static int priority = 0;
366 if(!n->status.reachable) {
367 ifdebug(TRAFFIC) logger(LOG_INFO, "Trying to send UDP packet to unreachable node %s (%s)", n->name, n->hostname);
371 /* Make sure we have a valid key */
373 if(!n->status.validkey) {
374 time_t now = time(NULL);
376 ifdebug(TRAFFIC) logger(LOG_INFO,
377 "No valid key known yet for %s (%s), forwarding via TCP",
378 n->name, n->hostname);
380 if(n->last_req_key + 10 < now) {
382 n->last_req_key = now;
385 send_tcppacket(n->nexthop->connection, origpkt);
390 if(n->options & OPTION_PMTU_DISCOVERY && inpkt->len > n->minmtu && (inpkt->data[12] | inpkt->data[13])) {
391 ifdebug(TRAFFIC) logger(LOG_INFO,
392 "Packet for %s (%s) larger than minimum MTU, forwarding via %s",
393 n->name, n->hostname, n != n->nexthop ? n->nexthop->name : "TCP");
396 send_packet(n->nexthop, origpkt);
398 send_tcppacket(n->nexthop->connection, origpkt);
403 origlen = inpkt->len;
404 origpriority = inpkt->priority;
406 /* Compress the packet */
408 if(n->outcompression) {
409 outpkt = pkt[nextpkt++];
411 if((outpkt->len = compress_packet(outpkt->data, inpkt->data, inpkt->len, n->outcompression)) < 0) {
412 ifdebug(TRAFFIC) logger(LOG_ERR, "Error while compressing packet to %s (%s)",
413 n->name, n->hostname);
420 /* Add sequence number */
422 inpkt->seqno = htonl(++(n->sent_seqno));
423 inpkt->len += sizeof inpkt->seqno;
425 /* Encrypt the packet */
427 if(cipher_active(&n->outcipher)) {
428 outpkt = pkt[nextpkt++];
431 if(!cipher_encrypt(&n->outcipher, &inpkt->seqno, inpkt->len, &outpkt->seqno, &outlen, true)) {
432 ifdebug(TRAFFIC) logger(LOG_ERR, "Error while encrypting packet to %s (%s)", n->name, n->hostname);
436 outpkt->len = outlen;
440 /* Add the message authentication code */
442 if(digest_active(&n->outdigest)) {
443 digest_create(&n->outdigest, &inpkt->seqno, inpkt->len, (char *)&inpkt->seqno + inpkt->len);
444 inpkt->len += digest_length(&n->outdigest);
447 /* Determine which socket we have to use */
449 for(sock = 0; sock < listen_sockets; sock++)
450 if(n->address.sa.sa_family == listen_socket[sock].sa.sa.sa_family)
453 if(sock >= listen_sockets)
454 sock = 0; /* If none is available, just use the first and hope for the best. */
456 /* Send the packet */
458 #if defined(SOL_IP) && defined(IP_TOS)
459 if(priorityinheritance && origpriority != priority
460 && listen_socket[sock].sa.sa.sa_family == AF_INET) {
461 priority = origpriority;
462 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Setting outgoing packet priority to %d", priority);
463 if(setsockopt(listen_socket[sock].udp, SOL_IP, IP_TOS, &priority, sizeof priority)) /* SO_PRIORITY doesn't seem to work */
464 logger(LOG_ERR, "System call `%s' failed: %s", "setsockopt", strerror(errno));
468 if(sendto(listen_socket[sock].udp, (char *) &inpkt->seqno, inpkt->len, 0, &(n->address.sa), SALEN(n->address.sa)) < 0 && !sockwouldblock(sockerrno)) {
469 if(sockmsgsize(sockerrno)) {
470 if(n->maxmtu >= origlen)
471 n->maxmtu = origlen - 1;
472 if(n->mtu >= origlen)
473 n->mtu = origlen - 1;
475 logger(LOG_ERR, "Error sending packet to %s (%s): %s", n->name, n->hostname, sockstrerror(sockerrno));
479 origpkt->len = origlen;
483 send a packet to the given vpn ip.
485 void send_packet(const node_t *n, vpn_packet_t *packet) {
490 memcpy(packet->data, mymac.x, ETH_ALEN);
491 write_packet(packet);
495 ifdebug(TRAFFIC) logger(LOG_ERR, "Sending packet of %d bytes to %s (%s)",
496 packet->len, n->name, n->hostname);
498 if(!n->status.reachable) {
499 ifdebug(TRAFFIC) logger(LOG_INFO, "Node %s (%s) is not reachable",
500 n->name, n->hostname);
504 via = (packet->priority == -1 || n->via == myself) ? n->nexthop : n->via;
507 ifdebug(TRAFFIC) logger(LOG_INFO, "Sending packet to %s via %s (%s)",
508 n->name, via->name, n->via->hostname);
510 if(packet->priority == -1 || ((myself->options | via->options) & OPTION_TCPONLY)) {
511 if(!send_tcppacket(via->connection, packet))
512 terminate_connection(via->connection, true);
514 send_udppacket(via, packet);
517 /* Broadcast a packet using the minimum spanning tree */
519 void broadcast_packet(const node_t *from, vpn_packet_t *packet) {
523 ifdebug(TRAFFIC) logger(LOG_INFO, "Broadcasting packet of %d bytes from %s (%s)",
524 packet->len, from->name, from->hostname);
527 send_packet(myself, packet);
529 // In TunnelServer mode, do not forward broadcast packets.
530 // The MST might not be valid and create loops.
535 for(node = connection_tree->head; node; node = node->next) {
538 if(c->status.active && c->status.mst && c != from->nexthop->connection)
539 send_packet(c->node, packet);
543 static node_t *try_harder(const sockaddr_t *from, const vpn_packet_t *pkt) {
545 node_t *n, *found = NULL;
546 static time_t last_hard_try = 0;
547 time_t now = time(NULL);
549 if(last_hard_try == now)
554 for(node = node_tree->head; node; node = node->next) {
557 if(n == myself || !n->status.reachable || !digest_active(&n->indigest))
560 if(try_mac(n, pkt)) {
569 void handle_incoming_vpn_data(int sock, short events, void *data) {
573 socklen_t fromlen = sizeof from;
577 len = recvfrom(sock, (char *) &pkt.seqno, MAXSIZE, 0, &from.sa, &fromlen);
579 if(len <= 0 || len > MAXSIZE) {
580 if(!sockwouldblock(sockerrno))
581 logger(LOG_ERR, "Receiving packet failed: %s", sockstrerror(sockerrno));
587 sockaddrunmap(&from); /* Some braindead IPv6 implementations do stupid things. */
589 n = lookup_node_udp(&from);
592 n = try_harder(&from, &pkt);
594 update_node_udp(n, &from);
595 else ifdebug(PROTOCOL) {
596 hostname = sockaddr2hostname(&from);
597 logger(LOG_WARNING, "Received UDP packet from unknown source %s", hostname);
605 receive_udppacket(n, &pkt);
608 void handle_device_data(int sock, short events, void *data) {
611 if(read_packet(&packet))
612 route(myself, &packet);