2 net_packet.c -- Handles in- and outgoing VPN packets
3 Copyright (C) 1998-2005 Ivo Timmermans,
4 2000-2009 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>
34 #include "connection.h"
50 #define EMSGSIZE WSAEMSGSIZE
55 static char lzo_wrkmem[LZO1X_999_MEM_COMPRESS > LZO1X_1_MEM_COMPRESS ? LZO1X_999_MEM_COMPRESS : LZO1X_1_MEM_COMPRESS];
57 static void send_udppacket(node_t *, vpn_packet_t *);
59 #define MAX_SEQNO 1073741824
61 // mtuprobes == 1..30: initial discovery, send bursts with 1 second interval
62 // mtuprobes == 31: sleep pinginterval seconds
63 // mtuprobes == 32: send 1 burst, sleep pingtimeout second
64 // mtuprobes == 33: no response from other side, restart PMTU discovery process
66 void send_mtu_probe(node_t *n) {
74 if(!n->status.reachable || !n->status.validkey) {
75 ifdebug(TRAFFIC) logger(LOG_INFO, "Trying to send MTU probe to unreachable or rekeying node %s (%s)", n->name, n->hostname);
80 if(n->mtuprobes > 32) {
81 ifdebug(TRAFFIC) logger(LOG_INFO, "%s (%s) did not respond to UDP ping, restarting PMTU discovery", n->name, n->hostname);
87 if(n->mtuprobes >= 10 && !n->minmtu) {
88 ifdebug(TRAFFIC) logger(LOG_INFO, "No response to MTU probes from %s (%s)", n->name, n->hostname);
93 if(n->mtuprobes == 30 || (n->mtuprobes < 30 && n->minmtu >= n->maxmtu)) {
95 ifdebug(TRAFFIC) logger(LOG_INFO, "Fixing MTU of %s (%s) to %d after %d probes", n->name, n->hostname, n->mtu, n->mtuprobes);
99 if(n->mtuprobes == 31) {
100 timeout = pinginterval;
102 } else if(n->mtuprobes == 32) {
103 timeout = pingtimeout;
106 for(i = 0; i < 3; i++) {
107 if(n->maxmtu <= n->minmtu)
110 len = n->minmtu + 1 + rand() % (n->maxmtu - n->minmtu);
115 memset(packet.data, 0, 14);
116 RAND_pseudo_bytes(packet.data + 14, len - 14);
120 ifdebug(TRAFFIC) logger(LOG_INFO, "Sending MTU probe length %d to %s (%s)", len, n->name, n->hostname);
122 send_udppacket(n, &packet);
126 n->mtuevent = new_event();
127 n->mtuevent->handler = (event_handler_t)send_mtu_probe;
128 n->mtuevent->data = n;
129 n->mtuevent->time = now + timeout;
130 event_add(n->mtuevent);
133 void mtu_probe_h(node_t *n, vpn_packet_t *packet, length_t len) {
134 ifdebug(TRAFFIC) logger(LOG_INFO, "Got MTU probe length %d from %s (%s)", packet->len, n->name, n->hostname);
136 if(!packet->data[0]) {
138 send_packet(n, packet);
144 if(n->mtuprobes > 30)
149 static length_t compress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level) {
151 lzo_uint lzolen = MAXSIZE;
152 lzo1x_1_compress(source, len, dest, &lzolen, lzo_wrkmem);
154 } else if(level < 10) {
155 unsigned long destlen = MAXSIZE;
156 if(compress2(dest, &destlen, source, len, level) == Z_OK)
161 lzo_uint lzolen = MAXSIZE;
162 lzo1x_999_compress(source, len, dest, &lzolen, lzo_wrkmem);
169 static length_t uncompress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level) {
171 lzo_uint lzolen = MAXSIZE;
172 if(lzo1x_decompress_safe(source, len, dest, &lzolen, NULL) == LZO_E_OK)
177 unsigned long destlen = MAXSIZE;
178 if(uncompress(dest, &destlen, source, len) == Z_OK)
189 static void receive_packet(node_t *n, vpn_packet_t *packet) {
190 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Received packet of %d bytes from %s (%s)",
191 packet->len, n->name, n->hostname);
196 static bool try_mac(const node_t *n, const vpn_packet_t *inpkt) {
197 unsigned char hmac[EVP_MAX_MD_SIZE];
199 if(!n->indigest || !n->inmaclength || !n->inkey || inpkt->len < sizeof inpkt->seqno + n->inmaclength)
202 HMAC(n->indigest, n->inkey, n->inkeylength, (unsigned char *) &inpkt->seqno, inpkt->len - n->inmaclength, (unsigned char *)hmac, NULL);
204 return !memcmp(hmac, (char *) &inpkt->seqno + inpkt->len - n->inmaclength, n->inmaclength);
207 static void receive_udppacket(node_t *n, vpn_packet_t *inpkt) {
208 vpn_packet_t pkt1, pkt2;
209 vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
211 vpn_packet_t *outpkt = pkt[0];
213 unsigned char hmac[EVP_MAX_MD_SIZE];
217 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Got packet from %s (%s) but he hasn't got our key yet",
218 n->name, n->hostname);
222 /* Check packet length */
224 if(inpkt->len < sizeof(inpkt->seqno) + n->inmaclength) {
225 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Got too short packet from %s (%s)",
226 n->name, n->hostname);
230 /* Check the message authentication code */
232 if(n->indigest && n->inmaclength) {
233 inpkt->len -= n->inmaclength;
234 HMAC(n->indigest, n->inkey, n->inkeylength,
235 (unsigned char *) &inpkt->seqno, inpkt->len, (unsigned char *)hmac, NULL);
237 if(memcmp(hmac, (char *) &inpkt->seqno + inpkt->len, n->inmaclength)) {
238 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Got unauthenticated packet from %s (%s)",
239 n->name, n->hostname);
244 /* Decrypt the packet */
247 outpkt = pkt[nextpkt++];
249 if(!EVP_DecryptInit_ex(&n->inctx, NULL, NULL, NULL, NULL)
250 || !EVP_DecryptUpdate(&n->inctx, (unsigned char *) &outpkt->seqno, &outlen,
251 (unsigned char *) &inpkt->seqno, inpkt->len)
252 || !EVP_DecryptFinal_ex(&n->inctx, (unsigned char *) &outpkt->seqno + outlen, &outpad)) {
253 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Error decrypting packet from %s (%s): %s",
254 n->name, n->hostname, ERR_error_string(ERR_get_error(), NULL));
258 outpkt->len = outlen + outpad;
262 /* Check the sequence number */
264 inpkt->len -= sizeof(inpkt->seqno);
265 inpkt->seqno = ntohl(inpkt->seqno);
267 if(inpkt->seqno != n->received_seqno + 1) {
268 if(inpkt->seqno >= n->received_seqno + sizeof(n->late) * 8) {
269 logger(LOG_WARNING, "Lost %d packets from %s (%s)",
270 inpkt->seqno - n->received_seqno - 1, n->name, n->hostname);
272 memset(n->late, 0, sizeof(n->late));
273 } else if (inpkt->seqno <= n->received_seqno) {
274 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))) {
275 logger(LOG_WARNING, "Got late or replayed packet from %s (%s), seqno %d, last received %d",
276 n->name, n->hostname, inpkt->seqno, n->received_seqno);
280 for(i = n->received_seqno + 1; i < inpkt->seqno; i++)
281 n->late[(i / 8) % sizeof(n->late)] |= 1 << i % 8;
285 n->late[(inpkt->seqno / 8) % sizeof(n->late)] &= ~(1 << inpkt->seqno % 8);
287 if(inpkt->seqno > n->received_seqno)
288 n->received_seqno = inpkt->seqno;
290 if(n->received_seqno > MAX_SEQNO)
293 /* Decompress the packet */
295 length_t origlen = inpkt->len;
297 if(n->incompression) {
298 outpkt = pkt[nextpkt++];
300 if((outpkt->len = uncompress_packet(outpkt->data, inpkt->data, inpkt->len, n->incompression)) < 0) {
301 ifdebug(TRAFFIC) logger(LOG_ERR, "Error while uncompressing packet from %s (%s)",
302 n->name, n->hostname);
308 origlen -= MTU/64 + 20;
313 if(!inpkt->data[12] && !inpkt->data[13])
314 mtu_probe_h(n, inpkt, origlen);
316 receive_packet(n, inpkt);
319 void receive_tcppacket(connection_t *c, char *buffer, int len) {
323 if(c->options & OPTION_TCPONLY)
326 outpkt.priority = -1;
327 memcpy(outpkt.data, buffer, len);
329 receive_packet(c->node, &outpkt);
332 static void send_udppacket(node_t *n, vpn_packet_t *origpkt) {
333 vpn_packet_t pkt1, pkt2;
334 vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
335 vpn_packet_t *inpkt = origpkt;
337 vpn_packet_t *outpkt;
340 static int priority = 0;
344 if(!n->status.reachable) {
345 ifdebug(TRAFFIC) logger(LOG_INFO, "Trying to send UDP packet to unreachable node %s (%s)", n->name, n->hostname);
349 /* Make sure we have a valid key */
351 if(!n->status.validkey) {
352 ifdebug(TRAFFIC) logger(LOG_INFO,
353 "No valid key known yet for %s (%s), forwarding via TCP",
354 n->name, n->hostname);
356 if(!n->status.waitingforkey)
359 n->status.waitingforkey = true;
361 send_tcppacket(n->nexthop->connection, origpkt);
366 if(n->options & OPTION_PMTU_DISCOVERY && inpkt->len > n->minmtu && (inpkt->data[12] | inpkt->data[13])) {
367 ifdebug(TRAFFIC) logger(LOG_INFO,
368 "Packet for %s (%s) larger than minimum MTU, forwarding via TCP",
369 n->name, n->hostname);
371 send_tcppacket(n->nexthop->connection, origpkt);
376 origlen = inpkt->len;
377 origpriority = inpkt->priority;
379 /* Compress the packet */
381 if(n->outcompression) {
382 outpkt = pkt[nextpkt++];
384 if((outpkt->len = compress_packet(outpkt->data, inpkt->data, inpkt->len, n->outcompression)) < 0) {
385 ifdebug(TRAFFIC) logger(LOG_ERR, "Error while compressing packet to %s (%s)",
386 n->name, n->hostname);
393 /* Add sequence number */
395 inpkt->seqno = htonl(++(n->sent_seqno));
396 inpkt->len += sizeof(inpkt->seqno);
398 /* Encrypt the packet */
401 outpkt = pkt[nextpkt++];
403 if(!EVP_EncryptInit_ex(&n->outctx, NULL, NULL, NULL, NULL)
404 || !EVP_EncryptUpdate(&n->outctx, (unsigned char *) &outpkt->seqno, &outlen,
405 (unsigned char *) &inpkt->seqno, inpkt->len)
406 || !EVP_EncryptFinal_ex(&n->outctx, (unsigned char *) &outpkt->seqno + outlen, &outpad)) {
407 ifdebug(TRAFFIC) logger(LOG_ERR, "Error while encrypting packet to %s (%s): %s",
408 n->name, n->hostname, ERR_error_string(ERR_get_error(), NULL));
412 outpkt->len = outlen + outpad;
416 /* Add the message authentication code */
418 if(n->outdigest && n->outmaclength) {
419 HMAC(n->outdigest, n->outkey, n->outkeylength, (unsigned char *) &inpkt->seqno,
420 inpkt->len, (unsigned char *) &inpkt->seqno + inpkt->len, NULL);
421 inpkt->len += n->outmaclength;
424 /* Determine which socket we have to use */
426 for(sock = 0; sock < listen_sockets; sock++)
427 if(n->address.sa.sa_family == listen_socket[sock].sa.sa.sa_family)
430 if(sock >= listen_sockets)
431 sock = 0; /* If none is available, just use the first and hope for the best. */
433 /* Send the packet */
435 #if defined(SOL_IP) && defined(IP_TOS)
436 if(priorityinheritance && origpriority != priority
437 && listen_socket[sock].sa.sa.sa_family == AF_INET) {
438 priority = origpriority;
439 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Setting outgoing packet priority to %d", priority);
440 if(setsockopt(listen_socket[sock].udp, SOL_IP, IP_TOS, &priority, sizeof(priority))) /* SO_PRIORITY doesn't seem to work */
441 logger(LOG_ERR, "System call `%s' failed: %s", "setsockopt", strerror(errno));
445 if((sendto(listen_socket[sock].udp, (char *) &inpkt->seqno, inpkt->len, 0, &(n->address.sa), SALEN(n->address.sa))) < 0) {
446 if(errno == EMSGSIZE) {
447 if(n->maxmtu >= origlen)
448 n->maxmtu = origlen - 1;
449 if(n->mtu >= origlen)
450 n->mtu = origlen - 1;
452 logger(LOG_ERR, "Error sending packet to %s (%s): %s", n->name, n->hostname, strerror(errno));
456 origpkt->len = origlen;
460 send a packet to the given vpn ip.
462 void send_packet(const node_t *n, vpn_packet_t *packet) {
467 memcpy(packet->data, mymac.x, ETH_ALEN);
468 write_packet(packet);
472 ifdebug(TRAFFIC) logger(LOG_ERR, "Sending packet of %d bytes to %s (%s)",
473 packet->len, n->name, n->hostname);
475 if(!n->status.reachable) {
476 ifdebug(TRAFFIC) logger(LOG_INFO, "Node %s (%s) is not reachable",
477 n->name, n->hostname);
481 via = (packet->priority == -1 || n->via == myself) ? n->nexthop : n->via;
484 ifdebug(TRAFFIC) logger(LOG_INFO, "Sending packet to %s via %s (%s)",
485 n->name, via->name, n->via->hostname);
487 if(packet->priority == -1 || ((myself->options | via->options) & OPTION_TCPONLY)) {
488 if(!send_tcppacket(via->connection, packet))
489 terminate_connection(via->connection, true);
491 send_udppacket(via, packet);
494 /* Broadcast a packet using the minimum spanning tree */
496 void broadcast_packet(const node_t *from, vpn_packet_t *packet) {
500 ifdebug(TRAFFIC) logger(LOG_INFO, "Broadcasting packet of %d bytes from %s (%s)",
501 packet->len, from->name, from->hostname);
504 send_packet(myself, packet);
506 // In TunnelServer mode, do not forward broadcast packets.
507 // The MST might not be valid and create loops.
512 for(node = connection_tree->head; node; node = node->next) {
515 if(c->status.active && c->status.mst && c != from->nexthop->connection)
516 send_packet(c->node, packet);
520 static node_t *try_harder(const sockaddr_t *from, const vpn_packet_t *pkt) {
525 for(node = edge_weight_tree->head; node; node = node->next) {
528 if(sockaddrcmp_noport(from, &e->address))
534 if(!try_mac(e->to, pkt))
544 void handle_incoming_vpn_data(int sock) {
548 socklen_t fromlen = sizeof(from);
551 pkt.len = recvfrom(sock, (char *) &pkt.seqno, MAXSIZE, 0, &from.sa, &fromlen);
554 if(errno != EAGAIN && errno != EINTR)
555 logger(LOG_ERR, "Receiving packet failed: %s", strerror(errno));
559 sockaddrunmap(&from); /* Some braindead IPv6 implementations do stupid things. */
561 n = lookup_node_udp(&from);
564 n = try_harder(&from, &pkt);
566 update_node_udp(n, &from);
567 else ifdebug(PROTOCOL) {
568 hostname = sockaddr2hostname(&from);
569 logger(LOG_WARNING, "Received UDP packet from unknown source %s", hostname);
577 receive_udppacket(n, &pkt);