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)) {
94 if(n->minmtu > n->maxmtu)
95 n->minmtu = n->maxmtu;
97 n->maxmtu = n->minmtu;
99 ifdebug(TRAFFIC) logger(LOG_INFO, "Fixing MTU of %s (%s) to %d after %d probes", n->name, n->hostname, n->mtu, n->mtuprobes);
103 if(n->mtuprobes == 31) {
104 timeout = pinginterval;
106 } else if(n->mtuprobes == 32) {
107 timeout = pingtimeout;
110 for(i = 0; i < 3; i++) {
111 if(n->maxmtu <= n->minmtu)
114 len = n->minmtu + 1 + rand() % (n->maxmtu - n->minmtu);
119 memset(packet.data, 0, 14);
120 RAND_pseudo_bytes(packet.data + 14, len - 14);
124 ifdebug(TRAFFIC) logger(LOG_INFO, "Sending MTU probe length %d to %s (%s)", len, n->name, n->hostname);
126 send_udppacket(n, &packet);
130 n->mtuevent = new_event();
131 n->mtuevent->handler = (event_handler_t)send_mtu_probe;
132 n->mtuevent->data = n;
133 n->mtuevent->time = now + timeout;
134 event_add(n->mtuevent);
137 void mtu_probe_h(node_t *n, vpn_packet_t *packet, length_t len) {
138 ifdebug(TRAFFIC) logger(LOG_INFO, "Got MTU probe length %d from %s (%s)", packet->len, n->name, n->hostname);
140 if(!packet->data[0]) {
142 send_udppacket(n, packet);
148 if(n->mtuprobes > 30)
153 static length_t compress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level) {
155 lzo_uint lzolen = MAXSIZE;
156 lzo1x_1_compress(source, len, dest, &lzolen, lzo_wrkmem);
158 } else if(level < 10) {
159 unsigned long destlen = MAXSIZE;
160 if(compress2(dest, &destlen, source, len, level) == Z_OK)
165 lzo_uint lzolen = MAXSIZE;
166 lzo1x_999_compress(source, len, dest, &lzolen, lzo_wrkmem);
173 static length_t uncompress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level) {
175 lzo_uint lzolen = MAXSIZE;
176 if(lzo1x_decompress_safe(source, len, dest, &lzolen, NULL) == LZO_E_OK)
181 unsigned long destlen = MAXSIZE;
182 if(uncompress(dest, &destlen, source, len) == Z_OK)
193 static void receive_packet(node_t *n, vpn_packet_t *packet) {
194 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Received packet of %d bytes from %s (%s)",
195 packet->len, n->name, n->hostname);
200 static bool try_mac(const node_t *n, const vpn_packet_t *inpkt) {
201 unsigned char hmac[EVP_MAX_MD_SIZE];
203 if(!n->indigest || !n->inmaclength || !n->inkey || inpkt->len < sizeof inpkt->seqno + n->inmaclength)
206 HMAC(n->indigest, n->inkey, n->inkeylength, (unsigned char *) &inpkt->seqno, inpkt->len - n->inmaclength, (unsigned char *)hmac, NULL);
208 return !memcmp(hmac, (char *) &inpkt->seqno + inpkt->len - n->inmaclength, n->inmaclength);
211 static void receive_udppacket(node_t *n, vpn_packet_t *inpkt) {
212 vpn_packet_t pkt1, pkt2;
213 vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
215 vpn_packet_t *outpkt = pkt[0];
217 unsigned char hmac[EVP_MAX_MD_SIZE];
221 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Got packet from %s (%s) but he hasn't got our key yet",
222 n->name, n->hostname);
226 /* Check packet length */
228 if(inpkt->len < sizeof(inpkt->seqno) + n->inmaclength) {
229 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Got too short packet from %s (%s)",
230 n->name, n->hostname);
234 /* Check the message authentication code */
236 if(n->indigest && n->inmaclength) {
237 inpkt->len -= n->inmaclength;
238 HMAC(n->indigest, n->inkey, n->inkeylength,
239 (unsigned char *) &inpkt->seqno, inpkt->len, (unsigned char *)hmac, NULL);
241 if(memcmp(hmac, (char *) &inpkt->seqno + inpkt->len, n->inmaclength)) {
242 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Got unauthenticated packet from %s (%s)",
243 n->name, n->hostname);
248 /* Decrypt the packet */
251 outpkt = pkt[nextpkt++];
253 if(!EVP_DecryptInit_ex(&n->inctx, NULL, NULL, NULL, NULL)
254 || !EVP_DecryptUpdate(&n->inctx, (unsigned char *) &outpkt->seqno, &outlen,
255 (unsigned char *) &inpkt->seqno, inpkt->len)
256 || !EVP_DecryptFinal_ex(&n->inctx, (unsigned char *) &outpkt->seqno + outlen, &outpad)) {
257 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Error decrypting packet from %s (%s): %s",
258 n->name, n->hostname, ERR_error_string(ERR_get_error(), NULL));
262 outpkt->len = outlen + outpad;
266 /* Check the sequence number */
268 inpkt->len -= sizeof(inpkt->seqno);
269 inpkt->seqno = ntohl(inpkt->seqno);
271 if(inpkt->seqno != n->received_seqno + 1) {
272 if(inpkt->seqno >= n->received_seqno + sizeof(n->late) * 8) {
273 logger(LOG_WARNING, "Lost %d packets from %s (%s)",
274 inpkt->seqno - n->received_seqno - 1, n->name, n->hostname);
276 memset(n->late, 0, sizeof(n->late));
277 } else if (inpkt->seqno <= n->received_seqno) {
278 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))) {
279 logger(LOG_WARNING, "Got late or replayed packet from %s (%s), seqno %d, last received %d",
280 n->name, n->hostname, inpkt->seqno, n->received_seqno);
284 for(i = n->received_seqno + 1; i < inpkt->seqno; i++)
285 n->late[(i / 8) % sizeof(n->late)] |= 1 << i % 8;
289 n->late[(inpkt->seqno / 8) % sizeof(n->late)] &= ~(1 << inpkt->seqno % 8);
291 if(inpkt->seqno > n->received_seqno)
292 n->received_seqno = inpkt->seqno;
294 if(n->received_seqno > MAX_SEQNO)
297 /* Decompress the packet */
299 length_t origlen = inpkt->len;
301 if(n->incompression) {
302 outpkt = pkt[nextpkt++];
304 if((outpkt->len = uncompress_packet(outpkt->data, inpkt->data, inpkt->len, n->incompression)) < 0) {
305 ifdebug(TRAFFIC) logger(LOG_ERR, "Error while uncompressing packet from %s (%s)",
306 n->name, n->hostname);
312 origlen -= MTU/64 + 20;
317 if(!inpkt->data[12] && !inpkt->data[13])
318 mtu_probe_h(n, inpkt, origlen);
320 receive_packet(n, inpkt);
323 void receive_tcppacket(connection_t *c, char *buffer, int len) {
327 if(c->options & OPTION_TCPONLY)
330 outpkt.priority = -1;
331 memcpy(outpkt.data, buffer, len);
333 receive_packet(c->node, &outpkt);
336 static void send_udppacket(node_t *n, vpn_packet_t *origpkt) {
337 vpn_packet_t pkt1, pkt2;
338 vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
339 vpn_packet_t *inpkt = origpkt;
341 vpn_packet_t *outpkt;
344 static int priority = 0;
348 if(!n->status.reachable) {
349 ifdebug(TRAFFIC) logger(LOG_INFO, "Trying to send UDP packet to unreachable node %s (%s)", n->name, n->hostname);
353 /* Make sure we have a valid key */
355 if(!n->status.validkey) {
356 ifdebug(TRAFFIC) logger(LOG_INFO,
357 "No valid key known yet for %s (%s), forwarding via TCP",
358 n->name, n->hostname);
360 if(!n->status.waitingforkey)
363 n->status.waitingforkey = true;
365 send_tcppacket(n->nexthop->connection, origpkt);
370 if(n->options & OPTION_PMTU_DISCOVERY && inpkt->len > n->minmtu && (inpkt->data[12] | inpkt->data[13])) {
371 ifdebug(TRAFFIC) logger(LOG_INFO,
372 "Packet for %s (%s) larger than minimum MTU, forwarding via %s",
373 n->name, n->hostname, n != n->nexthop ? n->nexthop->name : "TCP");
376 send_packet(n->nexthop, origpkt);
378 send_tcppacket(n->nexthop->connection, origpkt);
383 origlen = inpkt->len;
384 origpriority = inpkt->priority;
386 /* Compress the packet */
388 if(n->outcompression) {
389 outpkt = pkt[nextpkt++];
391 if((outpkt->len = compress_packet(outpkt->data, inpkt->data, inpkt->len, n->outcompression)) < 0) {
392 ifdebug(TRAFFIC) logger(LOG_ERR, "Error while compressing packet to %s (%s)",
393 n->name, n->hostname);
400 /* Add sequence number */
402 inpkt->seqno = htonl(++(n->sent_seqno));
403 inpkt->len += sizeof(inpkt->seqno);
405 /* Encrypt the packet */
408 outpkt = pkt[nextpkt++];
410 if(!EVP_EncryptInit_ex(&n->outctx, NULL, NULL, NULL, NULL)
411 || !EVP_EncryptUpdate(&n->outctx, (unsigned char *) &outpkt->seqno, &outlen,
412 (unsigned char *) &inpkt->seqno, inpkt->len)
413 || !EVP_EncryptFinal_ex(&n->outctx, (unsigned char *) &outpkt->seqno + outlen, &outpad)) {
414 ifdebug(TRAFFIC) logger(LOG_ERR, "Error while encrypting packet to %s (%s): %s",
415 n->name, n->hostname, ERR_error_string(ERR_get_error(), NULL));
419 outpkt->len = outlen + outpad;
423 /* Add the message authentication code */
425 if(n->outdigest && n->outmaclength) {
426 HMAC(n->outdigest, n->outkey, n->outkeylength, (unsigned char *) &inpkt->seqno,
427 inpkt->len, (unsigned char *) &inpkt->seqno + inpkt->len, NULL);
428 inpkt->len += n->outmaclength;
431 /* Determine which socket we have to use */
433 for(sock = 0; sock < listen_sockets; sock++)
434 if(n->address.sa.sa_family == listen_socket[sock].sa.sa.sa_family)
437 if(sock >= listen_sockets)
438 sock = 0; /* If none is available, just use the first and hope for the best. */
440 /* Send the packet */
442 #if defined(SOL_IP) && defined(IP_TOS)
443 if(priorityinheritance && origpriority != priority
444 && listen_socket[sock].sa.sa.sa_family == AF_INET) {
445 priority = origpriority;
446 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Setting outgoing packet priority to %d", priority);
447 if(setsockopt(listen_socket[sock].udp, SOL_IP, IP_TOS, &priority, sizeof(priority))) /* SO_PRIORITY doesn't seem to work */
448 logger(LOG_ERR, "System call `%s' failed: %s", "setsockopt", strerror(errno));
452 if((sendto(listen_socket[sock].udp, (char *) &inpkt->seqno, inpkt->len, 0, &(n->address.sa), SALEN(n->address.sa))) < 0) {
453 if(errno == EMSGSIZE) {
454 if(n->maxmtu >= origlen)
455 n->maxmtu = origlen - 1;
456 if(n->mtu >= origlen)
457 n->mtu = origlen - 1;
459 logger(LOG_ERR, "Error sending packet to %s (%s): %s", n->name, n->hostname, strerror(errno));
463 origpkt->len = origlen;
467 send a packet to the given vpn ip.
469 void send_packet(const node_t *n, vpn_packet_t *packet) {
474 memcpy(packet->data, mymac.x, ETH_ALEN);
475 write_packet(packet);
479 ifdebug(TRAFFIC) logger(LOG_ERR, "Sending packet of %d bytes to %s (%s)",
480 packet->len, n->name, n->hostname);
482 if(!n->status.reachable) {
483 ifdebug(TRAFFIC) logger(LOG_INFO, "Node %s (%s) is not reachable",
484 n->name, n->hostname);
488 via = (packet->priority == -1 || n->via == myself) ? n->nexthop : n->via;
491 ifdebug(TRAFFIC) logger(LOG_INFO, "Sending packet to %s via %s (%s)",
492 n->name, via->name, n->via->hostname);
494 if(packet->priority == -1 || ((myself->options | via->options) & OPTION_TCPONLY)) {
495 if(!send_tcppacket(via->connection, packet))
496 terminate_connection(via->connection, true);
498 send_udppacket(via, packet);
501 /* Broadcast a packet using the minimum spanning tree */
503 void broadcast_packet(const node_t *from, vpn_packet_t *packet) {
507 ifdebug(TRAFFIC) logger(LOG_INFO, "Broadcasting packet of %d bytes from %s (%s)",
508 packet->len, from->name, from->hostname);
511 send_packet(myself, packet);
513 // In TunnelServer mode, do not forward broadcast packets.
514 // The MST might not be valid and create loops.
519 for(node = connection_tree->head; node; node = node->next) {
522 if(c->status.active && c->status.mst && c != from->nexthop->connection)
523 send_packet(c->node, packet);
527 static node_t *try_harder(const sockaddr_t *from, const vpn_packet_t *pkt) {
531 static time_t last_hard_try = 0;
533 for(node = edge_weight_tree->head; node; node = node->next) {
536 if(sockaddrcmp_noport(from, &e->address)) {
537 if(last_hard_try == now)
545 if(!try_mac(e->to, pkt))
555 void handle_incoming_vpn_data(int sock) {
559 socklen_t fromlen = sizeof(from);
562 pkt.len = recvfrom(sock, (char *) &pkt.seqno, MAXSIZE, 0, &from.sa, &fromlen);
565 if(errno != EAGAIN && errno != EINTR)
566 logger(LOG_ERR, "Receiving packet failed: %s", strerror(errno));
570 sockaddrunmap(&from); /* Some braindead IPv6 implementations do stupid things. */
572 n = lookup_node_udp(&from);
575 n = try_harder(&from, &pkt);
577 update_node_udp(n, &from);
578 else ifdebug(PROTOCOL) {
579 hostname = sockaddr2hostname(&from);
580 logger(LOG_WARNING, "Received UDP packet from unknown source %s", hostname);
588 receive_udppacket(n, &pkt);