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>
37 #include "splay_tree.h"
40 #include "connection.h"
59 static char lzo_wrkmem[LZO1X_999_MEM_COMPRESS > LZO1X_1_MEM_COMPRESS ? LZO1X_999_MEM_COMPRESS : LZO1X_1_MEM_COMPRESS];
62 static void send_udppacket(node_t *, vpn_packet_t *);
64 #define MAX_SEQNO 1073741824
66 // mtuprobes == 1..30: initial discovery, send bursts with 1 second interval
67 // mtuprobes == 31: sleep pinginterval seconds
68 // mtuprobes == 32: send 1 burst, sleep pingtimeout second
69 // mtuprobes == 33: no response from other side, restart PMTU discovery process
71 static void send_mtu_probe_handler(int fd, short events, void *data) {
79 if(!n->status.reachable || !n->status.validkey) {
80 ifdebug(TRAFFIC) logger(LOG_INFO, "Trying to send MTU probe to unreachable or rekeying node %s (%s)", n->name, n->hostname);
85 if(n->mtuprobes > 32) {
86 ifdebug(TRAFFIC) logger(LOG_INFO, "%s (%s) did not respond to UDP ping, restarting PMTU discovery", n->name, n->hostname);
92 if(n->mtuprobes >= 10 && !n->minmtu) {
93 ifdebug(TRAFFIC) logger(LOG_INFO, "No response to MTU probes from %s (%s)", n->name, n->hostname);
98 if(n->mtuprobes == 30 || (n->mtuprobes < 30 && n->minmtu >= n->maxmtu)) {
99 if(n->minmtu > n->maxmtu)
100 n->minmtu = n->maxmtu;
102 n->maxmtu = n->minmtu;
104 ifdebug(TRAFFIC) logger(LOG_INFO, "Fixing MTU of %s (%s) to %d after %d probes", n->name, n->hostname, n->mtu, n->mtuprobes);
108 if(n->mtuprobes == 31) {
109 timeout = pinginterval;
111 } else if(n->mtuprobes == 32) {
112 timeout = pingtimeout;
115 for(i = 0; i < 3; i++) {
116 if(n->maxmtu <= n->minmtu)
119 len = n->minmtu + 1 + rand() % (n->maxmtu - n->minmtu);
124 memset(packet.data, 0, 14);
125 randomize(packet.data + 14, len - 14);
129 ifdebug(TRAFFIC) logger(LOG_INFO, "Sending MTU probe length %d to %s (%s)", len, n->name, n->hostname);
131 send_udppacket(n, &packet);
135 event_add(&n->mtuevent, &(struct timeval){timeout, 0});
138 void send_mtu_probe(node_t *n) {
139 if(!timeout_initialized(&n->mtuevent))
140 timeout_set(&n->mtuevent, send_mtu_probe_handler, n);
141 send_mtu_probe_handler(0, 0, n);
144 void mtu_probe_h(node_t *n, vpn_packet_t *packet, length_t len) {
145 ifdebug(TRAFFIC) logger(LOG_INFO, "Got MTU probe length %d from %s (%s)", packet->len, n->name, n->hostname);
147 if(!packet->data[0]) {
149 send_udppacket(n, packet);
155 if(n->mtuprobes > 30)
160 static length_t compress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level) {
162 memcpy(dest, source, len);
164 } else if(level == 10) {
166 lzo_uint lzolen = MAXSIZE;
167 lzo1x_1_compress(source, len, dest, &lzolen, lzo_wrkmem);
172 } else if(level < 10) {
174 unsigned long destlen = MAXSIZE;
175 if(compress2(dest, &destlen, source, len, level) == Z_OK)
182 lzo_uint lzolen = MAXSIZE;
183 lzo1x_999_compress(source, len, dest, &lzolen, lzo_wrkmem);
193 static length_t uncompress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level) {
195 memcpy(dest, source, len);
197 } else if(level > 9) {
199 lzo_uint lzolen = MAXSIZE;
200 if(lzo1x_decompress_safe(source, len, dest, &lzolen, NULL) == LZO_E_OK)
208 unsigned long destlen = MAXSIZE;
209 if(uncompress(dest, &destlen, source, len) == Z_OK)
221 static void receive_packet(node_t *n, vpn_packet_t *packet) {
222 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Received packet of %d bytes from %s (%s)",
223 packet->len, n->name, n->hostname);
228 static bool try_mac(node_t *n, const vpn_packet_t *inpkt) {
229 if(!digest_active(&n->indigest) || inpkt->len < sizeof inpkt->seqno + digest_length(&n->indigest))
232 return digest_verify(&n->indigest, &inpkt->seqno, inpkt->len - n->indigest.maclength, (const char *)&inpkt->seqno + inpkt->len - n->indigest.maclength);
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];
243 if(!cipher_active(&n->incipher)) {
244 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Got packet from %s (%s) but he hasn't got our key yet",
245 n->name, n->hostname);
249 /* Check packet length */
251 if(inpkt->len < sizeof inpkt->seqno + digest_length(&n->indigest)) {
252 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Got too short packet from %s (%s)",
253 n->name, n->hostname);
257 /* Check the message authentication code */
259 if(digest_active(&n->indigest)) {
260 inpkt->len -= n->indigest.maclength;
261 if(!digest_verify(&n->indigest, &inpkt->seqno, inpkt->len, (const char *)&inpkt->seqno + inpkt->len)) {
262 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Got unauthenticated packet from %s (%s)", n->name, n->hostname);
266 /* Decrypt the packet */
268 if(cipher_active(&n->incipher)) {
269 outpkt = pkt[nextpkt++];
272 if(!cipher_decrypt(&n->incipher, &inpkt->seqno, inpkt->len, &outpkt->seqno, &outlen, true)) {
273 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Error decrypting packet from %s (%s)", n->name, n->hostname);
277 outpkt->len = outlen;
281 /* Check the sequence number */
283 inpkt->len -= sizeof inpkt->seqno;
284 inpkt->seqno = ntohl(inpkt->seqno);
286 if(inpkt->seqno != n->received_seqno + 1) {
287 if(inpkt->seqno >= n->received_seqno + sizeof n->late * 8) {
288 logger(LOG_WARNING, "Lost %d packets from %s (%s)",
289 inpkt->seqno - n->received_seqno - 1, n->name, n->hostname);
291 memset(n->late, 0, sizeof n->late);
292 } else if (inpkt->seqno <= n->received_seqno) {
293 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))) {
294 logger(LOG_WARNING, "Got late or replayed packet from %s (%s), seqno %d, last received %d",
295 n->name, n->hostname, inpkt->seqno, n->received_seqno);
299 for(i = n->received_seqno + 1; i < inpkt->seqno; i++)
300 n->late[(i / 8) % sizeof n->late] |= 1 << i % 8;
304 n->late[(inpkt->seqno / 8) % sizeof n->late] &= ~(1 << inpkt->seqno % 8);
306 if(inpkt->seqno > n->received_seqno)
307 n->received_seqno = inpkt->seqno;
309 if(n->received_seqno > MAX_SEQNO)
312 /* Decompress the packet */
314 length_t origlen = inpkt->len;
316 if(n->incompression) {
317 outpkt = pkt[nextpkt++];
319 if((outpkt->len = uncompress_packet(outpkt->data, inpkt->data, inpkt->len, n->incompression)) < 0) {
320 ifdebug(TRAFFIC) logger(LOG_ERR, "Error while uncompressing packet from %s (%s)",
321 n->name, n->hostname);
327 origlen -= MTU/64 + 20;
332 if(!inpkt->data[12] && !inpkt->data[13])
333 mtu_probe_h(n, inpkt, origlen);
335 receive_packet(n, inpkt);
338 void receive_tcppacket(connection_t *c, char *buffer, int len) {
342 if(c->options & OPTION_TCPONLY)
345 outpkt.priority = -1;
346 memcpy(outpkt.data, buffer, len);
348 receive_packet(c->node, &outpkt);
351 static void send_udppacket(node_t *n, vpn_packet_t *origpkt) {
352 vpn_packet_t pkt1, pkt2;
353 vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
354 vpn_packet_t *inpkt = origpkt;
356 vpn_packet_t *outpkt;
359 static int priority = 0;
363 if(!n->status.reachable) {
364 ifdebug(TRAFFIC) logger(LOG_INFO, "Trying to send UDP packet to unreachable node %s (%s)", n->name, n->hostname);
368 /* Make sure we have a valid key */
370 if(!n->status.validkey) {
371 time_t now = time(NULL);
373 ifdebug(TRAFFIC) logger(LOG_INFO,
374 "No valid key known yet for %s (%s), forwarding via TCP",
375 n->name, n->hostname);
377 if(n->last_req_key + 10 < now) {
379 n->last_req_key = now;
382 send_tcppacket(n->nexthop->connection, origpkt);
387 if(n->options & OPTION_PMTU_DISCOVERY && inpkt->len > n->minmtu && (inpkt->data[12] | inpkt->data[13])) {
388 ifdebug(TRAFFIC) logger(LOG_INFO,
389 "Packet for %s (%s) larger than minimum MTU, forwarding via %s",
390 n->name, n->hostname, n != n->nexthop ? n->nexthop->name : "TCP");
393 send_packet(n->nexthop, origpkt);
395 send_tcppacket(n->nexthop->connection, origpkt);
400 origlen = inpkt->len;
401 origpriority = inpkt->priority;
403 /* Compress the packet */
405 if(n->outcompression) {
406 outpkt = pkt[nextpkt++];
408 if((outpkt->len = compress_packet(outpkt->data, inpkt->data, inpkt->len, n->outcompression)) < 0) {
409 ifdebug(TRAFFIC) logger(LOG_ERR, "Error while compressing packet to %s (%s)",
410 n->name, n->hostname);
417 /* Add sequence number */
419 inpkt->seqno = htonl(++(n->sent_seqno));
420 inpkt->len += sizeof inpkt->seqno;
422 /* Encrypt the packet */
424 if(cipher_active(&n->outcipher)) {
425 outpkt = pkt[nextpkt++];
428 if(!cipher_encrypt(&n->outcipher, &inpkt->seqno, inpkt->len, &outpkt->seqno, &outlen, true)) {
429 ifdebug(TRAFFIC) logger(LOG_ERR, "Error while encrypting packet to %s (%s)", n->name, n->hostname);
433 outpkt->len = outlen;
437 /* Add the message authentication code */
439 if(digest_active(&n->outdigest)) {
440 digest_create(&n->outdigest, &inpkt->seqno, inpkt->len, (char *)&inpkt->seqno + inpkt->len);
441 inpkt->len += digest_length(&n->outdigest);
444 /* Determine which socket we have to use */
446 for(sock = 0; sock < listen_sockets; sock++)
447 if(n->address.sa.sa_family == listen_socket[sock].sa.sa.sa_family)
450 if(sock >= listen_sockets)
451 sock = 0; /* If none is available, just use the first and hope for the best. */
453 /* Send the packet */
455 #if defined(SOL_IP) && defined(IP_TOS)
456 if(priorityinheritance && origpriority != priority
457 && listen_socket[sock].sa.sa.sa_family == AF_INET) {
458 priority = origpriority;
459 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Setting outgoing packet priority to %d", priority);
460 if(setsockopt(listen_socket[sock].udp, SOL_IP, IP_TOS, &priority, sizeof priority)) /* SO_PRIORITY doesn't seem to work */
461 logger(LOG_ERR, "System call `%s' failed: %s", "setsockopt", strerror(errno));
465 if(sendto(listen_socket[sock].udp, (char *) &inpkt->seqno, inpkt->len, 0, &(n->address.sa), SALEN(n->address.sa)) < 0 && !sockwouldblock(sockerrno)) {
466 if(sockmsgsize(sockerrno)) {
467 if(n->maxmtu >= origlen)
468 n->maxmtu = origlen - 1;
469 if(n->mtu >= origlen)
470 n->mtu = origlen - 1;
472 logger(LOG_ERR, "Error sending packet to %s (%s): %s", n->name, n->hostname, sockstrerror(sockerrno));
476 origpkt->len = origlen;
480 send a packet to the given vpn ip.
482 void send_packet(const node_t *n, vpn_packet_t *packet) {
487 memcpy(packet->data, mymac.x, ETH_ALEN);
488 write_packet(packet);
492 ifdebug(TRAFFIC) logger(LOG_ERR, "Sending packet of %d bytes to %s (%s)",
493 packet->len, n->name, n->hostname);
495 if(!n->status.reachable) {
496 ifdebug(TRAFFIC) logger(LOG_INFO, "Node %s (%s) is not reachable",
497 n->name, n->hostname);
501 via = (packet->priority == -1 || n->via == myself) ? n->nexthop : n->via;
504 ifdebug(TRAFFIC) logger(LOG_INFO, "Sending packet to %s via %s (%s)",
505 n->name, via->name, n->via->hostname);
507 if(packet->priority == -1 || ((myself->options | via->options) & OPTION_TCPONLY)) {
508 if(!send_tcppacket(via->connection, packet))
509 terminate_connection(via->connection, true);
511 send_udppacket(via, packet);
514 /* Broadcast a packet using the minimum spanning tree */
516 void broadcast_packet(const node_t *from, vpn_packet_t *packet) {
520 ifdebug(TRAFFIC) logger(LOG_INFO, "Broadcasting packet of %d bytes from %s (%s)",
521 packet->len, from->name, from->hostname);
524 send_packet(myself, packet);
526 // In TunnelServer mode, do not forward broadcast packets.
527 // The MST might not be valid and create loops.
532 for(node = connection_tree->head; node; node = node->next) {
535 if(c->status.active && c->status.mst && c != from->nexthop->connection)
536 send_packet(c->node, packet);
540 static node_t *try_harder(const sockaddr_t *from, const vpn_packet_t *pkt) {
542 node_t *n, *found = NULL;
543 static time_t last_hard_try = 0;
544 time_t now = time(NULL);
546 if(last_hard_try == now)
551 for(node = node_tree->head; node; node = node->next) {
554 if(n == myself || !n->status.reachable || !digest_active(&n->indigest))
557 if(try_mac(n, pkt)) {
566 void handle_incoming_vpn_data(int sock, short events, void *data) {
570 socklen_t fromlen = sizeof from;
574 len = recvfrom(sock, (char *) &pkt.seqno, MAXSIZE, 0, &from.sa, &fromlen);
576 if(len <= 0 || len > MAXSIZE) {
577 if(!sockwouldblock(sockerrno))
578 logger(LOG_ERR, "Receiving packet failed: %s", sockstrerror(sockerrno));
584 sockaddrunmap(&from); /* Some braindead IPv6 implementations do stupid things. */
586 n = lookup_node_udp(&from);
589 n = try_harder(&from, &pkt);
591 update_node_udp(n, &from);
592 else ifdebug(PROTOCOL) {
593 hostname = sockaddr2hostname(&from);
594 logger(LOG_WARNING, "Received UDP packet from unknown source %s", hostname);
602 receive_udppacket(n, &pkt);
605 void handle_device_data(int sock, short events, void *data) {
608 if(read_packet(&packet))
609 route(myself, &packet);