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 "connection.h"
55 static char lzo_wrkmem[LZO1X_999_MEM_COMPRESS > LZO1X_1_MEM_COMPRESS ? LZO1X_999_MEM_COMPRESS : LZO1X_1_MEM_COMPRESS];
58 static void send_udppacket(node_t *, vpn_packet_t *);
60 #define MAX_SEQNO 1073741824
62 // mtuprobes == 1..30: initial discovery, send bursts with 1 second interval
63 // mtuprobes == 31: sleep pinginterval seconds
64 // mtuprobes == 32: send 1 burst, sleep pingtimeout second
65 // mtuprobes == 33: no response from other side, restart PMTU discovery process
67 void send_mtu_probe(node_t *n) {
75 if(!n->status.reachable || !n->status.validkey) {
76 ifdebug(TRAFFIC) logger(LOG_INFO, "Trying to send MTU probe to unreachable or rekeying node %s (%s)", n->name, n->hostname);
81 if(n->mtuprobes > 32) {
82 ifdebug(TRAFFIC) logger(LOG_INFO, "%s (%s) did not respond to UDP ping, restarting PMTU discovery", n->name, n->hostname);
88 if(n->mtuprobes >= 10 && !n->minmtu) {
89 ifdebug(TRAFFIC) logger(LOG_INFO, "No response to MTU probes from %s (%s)", n->name, n->hostname);
94 if(n->mtuprobes == 30 || (n->mtuprobes < 30 && n->minmtu >= n->maxmtu)) {
95 if(n->minmtu > n->maxmtu)
96 n->minmtu = n->maxmtu;
98 n->maxmtu = n->minmtu;
100 ifdebug(TRAFFIC) logger(LOG_INFO, "Fixing MTU of %s (%s) to %d after %d probes", n->name, n->hostname, n->mtu, n->mtuprobes);
104 if(n->mtuprobes == 31) {
105 timeout = pinginterval;
107 } else if(n->mtuprobes == 32) {
108 timeout = pingtimeout;
111 for(i = 0; i < 3; i++) {
112 if(n->maxmtu <= n->minmtu)
115 len = n->minmtu + 1 + rand() % (n->maxmtu - n->minmtu);
120 memset(packet.data, 0, 14);
121 RAND_pseudo_bytes(packet.data + 14, len - 14);
125 ifdebug(TRAFFIC) logger(LOG_INFO, "Sending MTU probe length %d to %s (%s)", len, n->name, n->hostname);
127 send_udppacket(n, &packet);
131 n->mtuevent = new_event();
132 n->mtuevent->handler = (event_handler_t)send_mtu_probe;
133 n->mtuevent->data = n;
134 n->mtuevent->time = now + timeout;
135 event_add(n->mtuevent);
138 void mtu_probe_h(node_t *n, vpn_packet_t *packet, length_t len) {
139 ifdebug(TRAFFIC) logger(LOG_INFO, "Got MTU probe length %d from %s (%s)", packet->len, n->name, n->hostname);
141 if(!packet->data[0]) {
143 send_udppacket(n, packet);
149 if(n->mtuprobes > 30)
154 static length_t compress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level) {
157 lzo_uint lzolen = MAXSIZE;
158 lzo1x_1_compress(source, len, dest, &lzolen, lzo_wrkmem);
163 } else if(level < 10) {
164 unsigned long destlen = MAXSIZE;
165 if(compress2(dest, &destlen, source, len, level) == Z_OK)
171 lzo_uint lzolen = MAXSIZE;
172 lzo1x_999_compress(source, len, dest, &lzolen, lzo_wrkmem);
182 static length_t uncompress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level) {
185 lzo_uint lzolen = MAXSIZE;
186 if(lzo1x_decompress_safe(source, len, dest, &lzolen, NULL) == LZO_E_OK)
192 unsigned long destlen = MAXSIZE;
193 if(uncompress(dest, &destlen, source, len) == Z_OK)
204 static void receive_packet(node_t *n, vpn_packet_t *packet) {
205 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Received packet of %d bytes from %s (%s)",
206 packet->len, n->name, n->hostname);
211 static bool try_mac(const node_t *n, const vpn_packet_t *inpkt) {
212 unsigned char hmac[EVP_MAX_MD_SIZE];
214 if(!n->indigest || !n->inmaclength || !n->inkey || inpkt->len < sizeof inpkt->seqno + n->inmaclength)
217 HMAC(n->indigest, n->inkey, n->inkeylength, (unsigned char *) &inpkt->seqno, inpkt->len - n->inmaclength, (unsigned char *)hmac, NULL);
219 return !memcmp(hmac, (char *) &inpkt->seqno + inpkt->len - n->inmaclength, n->inmaclength);
222 static void receive_udppacket(node_t *n, vpn_packet_t *inpkt) {
223 vpn_packet_t pkt1, pkt2;
224 vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
226 vpn_packet_t *outpkt = pkt[0];
228 unsigned char hmac[EVP_MAX_MD_SIZE];
232 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Got packet from %s (%s) but he hasn't got our key yet",
233 n->name, n->hostname);
237 /* Check packet length */
239 if(inpkt->len < sizeof(inpkt->seqno) + n->inmaclength) {
240 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Got too short packet from %s (%s)",
241 n->name, n->hostname);
245 /* Check the message authentication code */
247 if(n->indigest && n->inmaclength) {
248 inpkt->len -= n->inmaclength;
249 HMAC(n->indigest, n->inkey, n->inkeylength,
250 (unsigned char *) &inpkt->seqno, inpkt->len, (unsigned char *)hmac, NULL);
252 if(memcmp(hmac, (char *) &inpkt->seqno + inpkt->len, n->inmaclength)) {
253 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Got unauthenticated packet from %s (%s)",
254 n->name, n->hostname);
259 /* Decrypt the packet */
262 outpkt = pkt[nextpkt++];
264 if(!EVP_DecryptInit_ex(&n->inctx, NULL, NULL, NULL, NULL)
265 || !EVP_DecryptUpdate(&n->inctx, (unsigned char *) &outpkt->seqno, &outlen,
266 (unsigned char *) &inpkt->seqno, inpkt->len)
267 || !EVP_DecryptFinal_ex(&n->inctx, (unsigned char *) &outpkt->seqno + outlen, &outpad)) {
268 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Error decrypting packet from %s (%s): %s",
269 n->name, n->hostname, ERR_error_string(ERR_get_error(), NULL));
273 outpkt->len = outlen + outpad;
277 /* Check the sequence number */
279 inpkt->len -= sizeof(inpkt->seqno);
280 inpkt->seqno = ntohl(inpkt->seqno);
282 if(inpkt->seqno != n->received_seqno + 1) {
283 if(inpkt->seqno >= n->received_seqno + sizeof(n->late) * 8) {
284 logger(LOG_WARNING, "Lost %d packets from %s (%s)",
285 inpkt->seqno - n->received_seqno - 1, n->name, n->hostname);
287 memset(n->late, 0, sizeof(n->late));
288 } else if (inpkt->seqno <= n->received_seqno) {
289 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))) {
290 logger(LOG_WARNING, "Got late or replayed packet from %s (%s), seqno %d, last received %d",
291 n->name, n->hostname, inpkt->seqno, n->received_seqno);
295 for(i = n->received_seqno + 1; i < inpkt->seqno; i++)
296 n->late[(i / 8) % sizeof(n->late)] |= 1 << i % 8;
300 n->late[(inpkt->seqno / 8) % sizeof(n->late)] &= ~(1 << inpkt->seqno % 8);
302 if(inpkt->seqno > n->received_seqno)
303 n->received_seqno = inpkt->seqno;
305 if(n->received_seqno > MAX_SEQNO)
308 /* Decompress the packet */
310 length_t origlen = inpkt->len;
312 if(n->incompression) {
313 outpkt = pkt[nextpkt++];
315 if((outpkt->len = uncompress_packet(outpkt->data, inpkt->data, inpkt->len, n->incompression)) < 0) {
316 ifdebug(TRAFFIC) logger(LOG_ERR, "Error while uncompressing packet from %s (%s)",
317 n->name, n->hostname);
323 origlen -= MTU/64 + 20;
328 if(!inpkt->data[12] && !inpkt->data[13])
329 mtu_probe_h(n, inpkt, origlen);
331 receive_packet(n, inpkt);
334 void receive_tcppacket(connection_t *c, char *buffer, int len) {
338 if(c->options & OPTION_TCPONLY)
341 outpkt.priority = -1;
342 memcpy(outpkt.data, buffer, len);
344 receive_packet(c->node, &outpkt);
347 static void send_udppacket(node_t *n, vpn_packet_t *origpkt) {
348 vpn_packet_t pkt1, pkt2;
349 vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
350 vpn_packet_t *inpkt = origpkt;
352 vpn_packet_t *outpkt;
355 static int priority = 0;
359 if(!n->status.reachable) {
360 ifdebug(TRAFFIC) logger(LOG_INFO, "Trying to send UDP packet to unreachable node %s (%s)", n->name, n->hostname);
364 /* Make sure we have a valid key */
366 if(!n->status.validkey) {
367 ifdebug(TRAFFIC) logger(LOG_INFO,
368 "No valid key known yet for %s (%s), forwarding via TCP",
369 n->name, n->hostname);
371 if(n->last_req_key + 10 < now) {
373 n->last_req_key = now;
376 send_tcppacket(n->nexthop->connection, origpkt);
381 if(n->options & OPTION_PMTU_DISCOVERY && inpkt->len > n->minmtu && (inpkt->data[12] | inpkt->data[13])) {
382 ifdebug(TRAFFIC) logger(LOG_INFO,
383 "Packet for %s (%s) larger than minimum MTU, forwarding via %s",
384 n->name, n->hostname, n != n->nexthop ? n->nexthop->name : "TCP");
387 send_packet(n->nexthop, origpkt);
389 send_tcppacket(n->nexthop->connection, origpkt);
394 origlen = inpkt->len;
395 origpriority = inpkt->priority;
397 /* Compress the packet */
399 if(n->outcompression) {
400 outpkt = pkt[nextpkt++];
402 if((outpkt->len = compress_packet(outpkt->data, inpkt->data, inpkt->len, n->outcompression)) < 0) {
403 ifdebug(TRAFFIC) logger(LOG_ERR, "Error while compressing packet to %s (%s)",
404 n->name, n->hostname);
411 /* Add sequence number */
413 inpkt->seqno = htonl(++(n->sent_seqno));
414 inpkt->len += sizeof(inpkt->seqno);
416 /* Encrypt the packet */
419 outpkt = pkt[nextpkt++];
421 if(!EVP_EncryptInit_ex(&n->outctx, NULL, NULL, NULL, NULL)
422 || !EVP_EncryptUpdate(&n->outctx, (unsigned char *) &outpkt->seqno, &outlen,
423 (unsigned char *) &inpkt->seqno, inpkt->len)
424 || !EVP_EncryptFinal_ex(&n->outctx, (unsigned char *) &outpkt->seqno + outlen, &outpad)) {
425 ifdebug(TRAFFIC) logger(LOG_ERR, "Error while encrypting packet to %s (%s): %s",
426 n->name, n->hostname, ERR_error_string(ERR_get_error(), NULL));
430 outpkt->len = outlen + outpad;
434 /* Add the message authentication code */
436 if(n->outdigest && n->outmaclength) {
437 HMAC(n->outdigest, n->outkey, n->outkeylength, (unsigned char *) &inpkt->seqno,
438 inpkt->len, (unsigned char *) &inpkt->seqno + inpkt->len, NULL);
439 inpkt->len += n->outmaclength;
442 /* Determine which socket we have to use */
444 for(sock = 0; sock < listen_sockets; sock++)
445 if(n->address.sa.sa_family == listen_socket[sock].sa.sa.sa_family)
448 if(sock >= listen_sockets)
449 sock = 0; /* If none is available, just use the first and hope for the best. */
451 /* Send the packet */
453 #if defined(SOL_IP) && defined(IP_TOS)
454 if(priorityinheritance && origpriority != priority
455 && listen_socket[sock].sa.sa.sa_family == AF_INET) {
456 priority = origpriority;
457 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Setting outgoing packet priority to %d", priority);
458 if(setsockopt(listen_socket[sock].udp, SOL_IP, IP_TOS, &priority, sizeof(priority))) /* SO_PRIORITY doesn't seem to work */
459 logger(LOG_ERR, "System call `%s' failed: %s", "setsockopt", strerror(errno));
463 if(sendto(listen_socket[sock].udp, (char *) &inpkt->seqno, inpkt->len, 0, &(n->address.sa), SALEN(n->address.sa)) < 0 && !sockwouldblock(sockerrno)) {
464 if(sockmsgsize(sockerrno)) {
465 if(n->maxmtu >= origlen)
466 n->maxmtu = origlen - 1;
467 if(n->mtu >= origlen)
468 n->mtu = origlen - 1;
470 logger(LOG_ERR, "Error sending packet to %s (%s): %s", n->name, n->hostname, sockstrerror(sockerrno));
474 origpkt->len = origlen;
478 send a packet to the given vpn ip.
480 void send_packet(const node_t *n, vpn_packet_t *packet) {
485 memcpy(packet->data, mymac.x, ETH_ALEN);
486 write_packet(packet);
490 ifdebug(TRAFFIC) logger(LOG_ERR, "Sending packet of %d bytes to %s (%s)",
491 packet->len, n->name, n->hostname);
493 if(!n->status.reachable) {
494 ifdebug(TRAFFIC) logger(LOG_INFO, "Node %s (%s) is not reachable",
495 n->name, n->hostname);
499 via = (packet->priority == -1 || n->via == myself) ? n->nexthop : n->via;
502 ifdebug(TRAFFIC) logger(LOG_INFO, "Sending packet to %s via %s (%s)",
503 n->name, via->name, n->via->hostname);
505 if(packet->priority == -1 || ((myself->options | via->options) & OPTION_TCPONLY)) {
506 if(!send_tcppacket(via->connection, packet))
507 terminate_connection(via->connection, true);
509 send_udppacket(via, packet);
512 /* Broadcast a packet using the minimum spanning tree */
514 void broadcast_packet(const node_t *from, vpn_packet_t *packet) {
518 ifdebug(TRAFFIC) logger(LOG_INFO, "Broadcasting packet of %d bytes from %s (%s)",
519 packet->len, from->name, from->hostname);
522 send_packet(myself, packet);
524 // In TunnelServer mode, do not forward broadcast packets.
525 // The MST might not be valid and create loops.
530 for(node = connection_tree->head; node; node = node->next) {
533 if(c->status.active && c->status.mst && c != from->nexthop->connection)
534 send_packet(c->node, packet);
538 static node_t *try_harder(const sockaddr_t *from, const vpn_packet_t *pkt) {
542 static time_t last_hard_try = 0;
544 for(node = edge_weight_tree->head; node; node = node->next) {
547 if(sockaddrcmp_noport(from, &e->address)) {
548 if(last_hard_try == now)
556 if(!try_mac(e->to, pkt))
566 void handle_incoming_vpn_data(int sock) {
570 socklen_t fromlen = sizeof(from);
573 pkt.len = recvfrom(sock, (char *) &pkt.seqno, MAXSIZE, 0, &from.sa, &fromlen);
576 if(!sockwouldblock(sockerrno))
577 logger(LOG_ERR, "Receiving packet failed: %s", sockstrerror(sockerrno));
581 sockaddrunmap(&from); /* Some braindead IPv6 implementations do stupid things. */
583 n = lookup_node_udp(&from);
586 n = try_harder(&from, &pkt);
588 update_node_udp(n, &from);
589 else ifdebug(PROTOCOL) {
590 hostname = sockaddr2hostname(&from);
591 logger(LOG_WARNING, "Received UDP packet from unknown source %s", hostname);
599 receive_udppacket(n, &pkt);