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>
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(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) {
90 ifdebug(TRAFFIC) logger(LOG_INFO, "%s (%s) did not respond to UDP ping, restarting PMTU discovery", n->name, n->hostname);
96 if(n->mtuprobes >= 10 && !n->minmtu) {
97 ifdebug(TRAFFIC) logger(LOG_INFO, "No response to MTU probes from %s (%s)", n->name, n->hostname);
102 if(n->mtuprobes == 30 || (n->mtuprobes < 30 && n->minmtu >= n->maxmtu)) {
103 if(n->minmtu > n->maxmtu)
104 n->minmtu = n->maxmtu;
106 n->maxmtu = n->minmtu;
108 ifdebug(TRAFFIC) logger(LOG_INFO, "Fixing MTU of %s (%s) to %d after %d probes", n->name, n->hostname, n->mtu, n->mtuprobes);
112 if(n->mtuprobes == 31) {
113 timeout = pinginterval;
115 } else if(n->mtuprobes == 32) {
116 timeout = pingtimeout;
119 for(i = 0; i < 3; i++) {
120 if(n->maxmtu <= n->minmtu)
123 len = n->minmtu + 1 + rand() % (n->maxmtu - n->minmtu);
128 memset(packet.data, 0, 14);
129 randomize(packet.data + 14, len - 14);
133 ifdebug(TRAFFIC) logger(LOG_INFO, "Sending MTU probe length %d to %s (%s)", len, n->name, n->hostname);
135 send_udppacket(n, &packet);
139 n->mtuevent.time = time(NULL) + timeout;
140 event_add(&n->mtuevent);
143 void send_mtu_probe(node_t *n) {
144 event_del(&n->mtuevent);
145 n->mtuevent.handler = send_mtu_probe_handler;
146 n->mtuevent.data = n;
147 send_mtu_probe_handler(n);
150 void mtu_probe_h(node_t *n, vpn_packet_t *packet, length_t len) {
151 ifdebug(TRAFFIC) logger(LOG_INFO, "Got MTU probe length %d from %s (%s)", packet->len, n->name, n->hostname);
153 if(!packet->data[0]) {
155 send_udppacket(n, packet);
161 if(n->mtuprobes > 30)
166 static length_t compress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level) {
168 memcpy(dest, source, len);
170 } else if(level == 10) {
172 lzo_uint lzolen = MAXSIZE;
173 lzo1x_1_compress(source, len, dest, &lzolen, lzo_wrkmem);
178 } else if(level < 10) {
180 unsigned long destlen = MAXSIZE;
181 if(compress2(dest, &destlen, source, len, level) == Z_OK)
188 lzo_uint lzolen = MAXSIZE;
189 lzo1x_999_compress(source, len, dest, &lzolen, lzo_wrkmem);
199 static length_t uncompress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level) {
201 memcpy(dest, source, len);
203 } else if(level > 9) {
205 lzo_uint lzolen = MAXSIZE;
206 if(lzo1x_decompress_safe(source, len, dest, &lzolen, NULL) == LZO_E_OK)
214 unsigned long destlen = MAXSIZE;
215 if(uncompress(dest, &destlen, source, len) == Z_OK)
227 static void receive_packet(node_t *n, vpn_packet_t *packet) {
228 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Received packet of %d bytes from %s (%s)",
229 packet->len, n->name, n->hostname);
234 static bool try_mac(node_t *n, const vpn_packet_t *inpkt) {
235 if(!digest_active(&n->indigest) || inpkt->len < sizeof inpkt->seqno + digest_length(&n->indigest))
238 return digest_verify(&n->indigest, &inpkt->seqno, inpkt->len - n->indigest.maclength, (const char *)&inpkt->seqno + inpkt->len - n->indigest.maclength);
241 static void receive_udppacket(node_t *n, vpn_packet_t *inpkt) {
242 vpn_packet_t pkt1, pkt2;
243 vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
245 vpn_packet_t *outpkt = pkt[0];
249 if(!cipher_active(&n->incipher)) {
250 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Got packet from %s (%s) but he hasn't got our key yet",
251 n->name, n->hostname);
255 /* Check packet length */
257 if(inpkt->len < sizeof inpkt->seqno + digest_length(&n->indigest)) {
258 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Got too short packet from %s (%s)",
259 n->name, n->hostname);
263 /* Check the message authentication code */
265 if(digest_active(&n->indigest)) {
266 inpkt->len -= n->indigest.maclength;
267 if(!digest_verify(&n->indigest, &inpkt->seqno, inpkt->len, (const char *)&inpkt->seqno + inpkt->len)) {
268 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Got unauthenticated packet from %s (%s)", n->name, n->hostname);
272 /* Decrypt the packet */
274 if(cipher_active(&n->incipher)) {
275 outpkt = pkt[nextpkt++];
278 if(!cipher_decrypt(&n->incipher, &inpkt->seqno, inpkt->len, &outpkt->seqno, &outlen, true)) {
279 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Error decrypting packet from %s (%s)", n->name, n->hostname);
283 outpkt->len = outlen;
287 /* Check the sequence number */
289 inpkt->len -= sizeof inpkt->seqno;
290 inpkt->seqno = ntohl(inpkt->seqno);
293 if(inpkt->seqno != n->received_seqno + 1) {
294 if(inpkt->seqno >= n->received_seqno + replaywin * 8) {
295 if(n->farfuture++ < replaywin >> 2) {
296 logger(LOG_WARNING, "Packet from %s (%s) is %d seqs in the future, dropped (%u)",
297 n->name, n->hostname, inpkt->seqno - n->received_seqno - 1, n->farfuture);
300 logger(LOG_WARNING, "Lost %d packets from %s (%s)",
301 inpkt->seqno - n->received_seqno - 1, n->name, n->hostname);
302 memset(n->late, 0, replaywin);
303 } else if (inpkt->seqno <= n->received_seqno) {
304 if((n->received_seqno >= replaywin * 8 && inpkt->seqno <= n->received_seqno - replaywin * 8) || !(n->late[(inpkt->seqno / 8) % replaywin] & (1 << inpkt->seqno % 8))) {
305 logger(LOG_WARNING, "Got late or replayed packet from %s (%s), seqno %d, last received %d",
306 n->name, n->hostname, inpkt->seqno, n->received_seqno);
310 for(i = n->received_seqno + 1; i < inpkt->seqno; i++)
311 n->late[(i / 8) % replaywin] |= 1 << i % 8;
316 n->late[(inpkt->seqno / 8) % replaywin] &= ~(1 << inpkt->seqno % 8);
319 if(inpkt->seqno > n->received_seqno)
320 n->received_seqno = inpkt->seqno;
322 if(n->received_seqno > MAX_SEQNO)
325 /* Decompress the packet */
327 length_t origlen = inpkt->len;
329 if(n->incompression) {
330 outpkt = pkt[nextpkt++];
332 if((outpkt->len = uncompress_packet(outpkt->data, inpkt->data, inpkt->len, n->incompression)) < 0) {
333 ifdebug(TRAFFIC) logger(LOG_ERR, "Error while uncompressing packet from %s (%s)",
334 n->name, n->hostname);
340 origlen -= MTU/64 + 20;
345 if(!inpkt->data[12] && !inpkt->data[13])
346 mtu_probe_h(n, inpkt, origlen);
348 receive_packet(n, inpkt);
351 void receive_tcppacket(connection_t *c, char *buffer, int len) {
355 if(c->options & OPTION_TCPONLY)
358 outpkt.priority = -1;
359 memcpy(outpkt.data, buffer, len);
361 receive_packet(c->node, &outpkt);
364 static void send_udppacket(node_t *n, vpn_packet_t *origpkt) {
365 vpn_packet_t pkt1, pkt2;
366 vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
367 vpn_packet_t *inpkt = origpkt;
369 vpn_packet_t *outpkt;
372 #if defined(SOL_IP) && defined(IP_TOS)
373 static int priority = 0;
378 if(!n->status.reachable) {
379 ifdebug(TRAFFIC) logger(LOG_INFO, "Trying to send UDP packet to unreachable node %s (%s)", n->name, n->hostname);
383 /* Make sure we have a valid key */
385 if(!n->status.validkey) {
386 time_t now = time(NULL);
388 ifdebug(TRAFFIC) logger(LOG_INFO,
389 "No valid key known yet for %s (%s), forwarding via TCP",
390 n->name, n->hostname);
392 if(n->last_req_key + 10 < now) {
394 n->last_req_key = now;
397 send_tcppacket(n->nexthop->connection, origpkt);
402 if(n->options & OPTION_PMTU_DISCOVERY && inpkt->len > n->minmtu && (inpkt->data[12] | inpkt->data[13])) {
403 ifdebug(TRAFFIC) logger(LOG_INFO,
404 "Packet for %s (%s) larger than minimum MTU, forwarding via %s",
405 n->name, n->hostname, n != n->nexthop ? n->nexthop->name : "TCP");
408 send_packet(n->nexthop, origpkt);
410 send_tcppacket(n->nexthop->connection, origpkt);
415 origlen = inpkt->len;
416 origpriority = inpkt->priority;
418 /* Compress the packet */
420 if(n->outcompression) {
421 outpkt = pkt[nextpkt++];
423 if((outpkt->len = compress_packet(outpkt->data, inpkt->data, inpkt->len, n->outcompression)) < 0) {
424 ifdebug(TRAFFIC) logger(LOG_ERR, "Error while compressing packet to %s (%s)",
425 n->name, n->hostname);
432 /* Add sequence number */
434 inpkt->seqno = htonl(++(n->sent_seqno));
435 inpkt->len += sizeof inpkt->seqno;
437 /* Encrypt the packet */
439 if(cipher_active(&n->outcipher)) {
440 outpkt = pkt[nextpkt++];
443 if(!cipher_encrypt(&n->outcipher, &inpkt->seqno, inpkt->len, &outpkt->seqno, &outlen, true)) {
444 ifdebug(TRAFFIC) logger(LOG_ERR, "Error while encrypting packet to %s (%s)", n->name, n->hostname);
448 outpkt->len = outlen;
452 /* Add the message authentication code */
454 if(digest_active(&n->outdigest)) {
455 digest_create(&n->outdigest, &inpkt->seqno, inpkt->len, (char *)&inpkt->seqno + inpkt->len);
456 inpkt->len += digest_length(&n->outdigest);
459 /* Determine which socket we have to use */
461 for(sock = 0; sock < listen_sockets; sock++)
462 if(n->address.sa.sa_family == listen_socket[sock].sa.sa.sa_family)
465 if(sock >= listen_sockets)
466 sock = 0; /* If none is available, just use the first and hope for the best. */
468 /* Send the packet */
470 #if defined(SOL_IP) && defined(IP_TOS)
471 if(priorityinheritance && origpriority != priority
472 && listen_socket[sock].sa.sa.sa_family == AF_INET) {
473 priority = origpriority;
474 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Setting outgoing packet priority to %d", priority);
475 if(setsockopt(listen_socket[sock].udp, SOL_IP, IP_TOS, &priority, sizeof priority)) /* SO_PRIORITY doesn't seem to work */
476 logger(LOG_ERR, "System call `%s' failed: %s", "setsockopt", strerror(errno));
480 if(sendto(listen_socket[sock].udp, (char *) &inpkt->seqno, inpkt->len, 0, &(n->address.sa), SALEN(n->address.sa)) < 0 && !sockwouldblock(sockerrno)) {
481 if(sockmsgsize(sockerrno)) {
482 if(n->maxmtu >= origlen)
483 n->maxmtu = origlen - 1;
484 if(n->mtu >= origlen)
485 n->mtu = origlen - 1;
487 logger(LOG_ERR, "Error sending packet to %s (%s): %s", n->name, n->hostname, sockstrerror(sockerrno));
491 origpkt->len = origlen;
495 send a packet to the given vpn ip.
497 void send_packet(const node_t *n, vpn_packet_t *packet) {
502 memcpy(packet->data, mymac.x, ETH_ALEN);
503 write_packet(packet);
507 ifdebug(TRAFFIC) logger(LOG_ERR, "Sending packet of %d bytes to %s (%s)",
508 packet->len, n->name, n->hostname);
510 if(!n->status.reachable) {
511 ifdebug(TRAFFIC) logger(LOG_INFO, "Node %s (%s) is not reachable",
512 n->name, n->hostname);
516 via = (packet->priority == -1 || n->via == myself) ? n->nexthop : n->via;
519 ifdebug(TRAFFIC) logger(LOG_INFO, "Sending packet to %s via %s (%s)",
520 n->name, via->name, n->via->hostname);
522 if(packet->priority == -1 || ((myself->options | via->options) & OPTION_TCPONLY)) {
523 if(!send_tcppacket(via->connection, packet))
524 terminate_connection(via->connection, true);
526 send_udppacket(via, packet);
529 /* Broadcast a packet using the minimum spanning tree */
531 void broadcast_packet(const node_t *from, vpn_packet_t *packet) {
535 ifdebug(TRAFFIC) logger(LOG_INFO, "Broadcasting packet of %d bytes from %s (%s)",
536 packet->len, from->name, from->hostname);
539 send_packet(myself, packet);
541 // In TunnelServer mode, do not forward broadcast packets.
542 // The MST might not be valid and create loops.
547 for(node = connection_tree->head; node; node = node->next) {
550 if(c->status.active && c->status.mst && c != from->nexthop->connection)
551 send_packet(c->node, packet);
555 static node_t *try_harder(const sockaddr_t *from, const vpn_packet_t *pkt) {
557 node_t *n, *found = NULL;
558 static time_t last_hard_try = 0;
559 time_t now = time(NULL);
561 if(last_hard_try == now)
566 for(node = node_tree->head; node; node = node->next) {
569 if(n == myself || !n->status.reachable || !digest_active(&n->indigest))
572 if(try_mac(n, pkt)) {
581 void handle_incoming_vpn_data(void *arg) {
582 listen_socket_t *l = arg;
586 socklen_t fromlen = sizeof from;
591 len = recvfrom(l->udp, (char *) &pkt.seqno, MAXSIZE, 0, &from.sa, &fromlen);
593 if(len <= 0 || len > MAXSIZE) {
594 logger(LOG_ERR, "Receiving packet failed: %s", sockstrerror(sockerrno));
600 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);
612 receive_udppacket(n, &pkt);
615 hostname = sockaddr2hostname(&from);
616 logger(LOG_WARNING, "Received UDP packet from unknown source %s", hostname);
621 mutex_unlock(&mutex);
625 void handle_device_data(int sock, short events, void *data) {
628 if(read_packet(&packet))
629 route(myself, &packet);