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
17 along with this program; if not, write to the Free Software
18 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, 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>
36 #include "connection.h"
52 #define EMSGSIZE WSAEMSGSIZE
57 static char lzo_wrkmem[LZO1X_999_MEM_COMPRESS > LZO1X_1_MEM_COMPRESS ? LZO1X_999_MEM_COMPRESS : LZO1X_1_MEM_COMPRESS];
59 static void send_udppacket(node_t *, vpn_packet_t *);
61 #define MAX_SEQNO 1073741824
63 void send_mtu_probe(node_t *n)
73 if(!n->status.reachable) {
74 ifdebug(TRAFFIC) logger(LOG_INFO, _("Trying to send MTU probe to unreachable node %s (%s)"), n->name, n->hostname);
78 if(n->mtuprobes >= 10 && !n->minmtu) {
79 ifdebug(TRAFFIC) logger(LOG_INFO, _("No response to MTU probes from %s (%s)"), n->name, n->hostname);
83 for(i = 0; i < 3; i++) {
84 if(n->mtuprobes >= 30 || n->minmtu >= n->maxmtu) {
86 ifdebug(TRAFFIC) logger(LOG_INFO, _("Fixing MTU of %s (%s) to %d after %d probes"), n->name, n->hostname, n->mtu, n->mtuprobes);
90 len = n->minmtu + 1 + random() % (n->maxmtu - n->minmtu);
94 memset(packet.data, 0, 14);
95 RAND_pseudo_bytes(packet.data + 14, len - 14);
99 ifdebug(TRAFFIC) logger(LOG_INFO, _("Sending MTU probe length %d to %s (%s)"), len, n->name, n->hostname);
101 send_udppacket(n, &packet);
104 n->mtuevent = new_event();
105 n->mtuevent->handler = (event_handler_t)send_mtu_probe;
106 n->mtuevent->data = n;
107 n->mtuevent->time = now + 1;
108 event_add(n->mtuevent);
111 void mtu_probe_h(node_t *n, vpn_packet_t *packet, length_t len) {
112 ifdebug(TRAFFIC) logger(LOG_INFO, _("Got MTU probe length %d from %s (%s)"), packet->len, n->name, n->hostname);
114 if(!packet->data[0]) {
116 send_packet(n, packet);
123 static length_t compress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level)
126 lzo_uint lzolen = MAXSIZE;
127 lzo1x_1_compress(source, len, dest, &lzolen, lzo_wrkmem);
129 } else if(level < 10) {
130 unsigned long destlen = MAXSIZE;
131 if(compress2(dest, &destlen, source, len, level) == Z_OK)
136 lzo_uint lzolen = MAXSIZE;
137 lzo1x_999_compress(source, len, dest, &lzolen, lzo_wrkmem);
144 static length_t uncompress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level)
147 lzo_uint lzolen = MAXSIZE;
148 if(lzo1x_decompress_safe(source, len, dest, &lzolen, NULL) == LZO_E_OK)
153 unsigned long destlen = MAXSIZE;
154 if(uncompress(dest, &destlen, source, len) == Z_OK)
165 static void receive_packet(node_t *n, vpn_packet_t *packet)
169 ifdebug(TRAFFIC) logger(LOG_DEBUG, _("Received packet of %d bytes from %s (%s)"),
170 packet->len, n->name, n->hostname);
175 static bool try_mac(const node_t *n, const vpn_packet_t *inpkt)
177 unsigned char hmac[EVP_MAX_MD_SIZE];
179 if(!n->indigest || !n->inmaclength || !n->inkey || inpkt->len < sizeof inpkt->seqno + n->inmaclength)
182 HMAC(n->indigest, n->inkey, n->inkeylength, (unsigned char *) &inpkt->seqno, inpkt->len - n->inmaclength, (unsigned char *)hmac, NULL);
184 return !memcmp(hmac, (char *) &inpkt->seqno + inpkt->len - n->inmaclength, n->inmaclength);
187 static void receive_udppacket(node_t *n, vpn_packet_t *inpkt)
189 vpn_packet_t pkt1, pkt2;
190 vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
192 vpn_packet_t *outpkt = pkt[0];
194 unsigned char hmac[EVP_MAX_MD_SIZE];
200 ifdebug(TRAFFIC) logger(LOG_DEBUG, _("Got packet from %s (%s) but he hasn't got our key yet"),
201 n->name, n->hostname);
205 /* Check packet length */
207 if(inpkt->len < sizeof(inpkt->seqno) + n->inmaclength) {
208 ifdebug(TRAFFIC) logger(LOG_DEBUG, _("Got too short packet from %s (%s)"),
209 n->name, n->hostname);
213 /* Check the message authentication code */
215 if(n->indigest && n->inmaclength) {
216 inpkt->len -= n->inmaclength;
217 HMAC(n->indigest, n->inkey, n->inkeylength,
218 (unsigned char *) &inpkt->seqno, inpkt->len, (unsigned char *)hmac, NULL);
220 if(memcmp(hmac, (char *) &inpkt->seqno + inpkt->len, n->inmaclength)) {
221 ifdebug(TRAFFIC) logger(LOG_DEBUG, _("Got unauthenticated packet from %s (%s)"),
222 n->name, n->hostname);
227 /* Decrypt the packet */
230 outpkt = pkt[nextpkt++];
232 if(!EVP_DecryptInit_ex(&n->inctx, NULL, NULL, NULL, NULL)
233 || !EVP_DecryptUpdate(&n->inctx, (unsigned char *) &outpkt->seqno, &outlen,
234 (unsigned char *) &inpkt->seqno, inpkt->len)
235 || !EVP_DecryptFinal_ex(&n->inctx, (unsigned char *) &outpkt->seqno + outlen, &outpad)) {
236 ifdebug(TRAFFIC) logger(LOG_DEBUG, _("Error decrypting packet from %s (%s): %s"),
237 n->name, n->hostname, ERR_error_string(ERR_get_error(), NULL));
241 outpkt->len = outlen + outpad;
245 /* Check the sequence number */
247 inpkt->len -= sizeof(inpkt->seqno);
248 inpkt->seqno = ntohl(inpkt->seqno);
250 if(inpkt->seqno != n->received_seqno + 1) {
251 if(inpkt->seqno >= n->received_seqno + sizeof(n->late) * 8) {
252 logger(LOG_WARNING, _("Lost %d packets from %s (%s)"),
253 inpkt->seqno - n->received_seqno - 1, n->name, n->hostname);
255 memset(n->late, 0, sizeof(n->late));
256 } else if (inpkt->seqno <= n->received_seqno) {
257 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))) {
258 logger(LOG_WARNING, _("Got late or replayed packet from %s (%s), seqno %d, last received %d"),
259 n->name, n->hostname, inpkt->seqno, n->received_seqno);
263 for(i = n->received_seqno + 1; i < inpkt->seqno; i++)
264 n->late[(i / 8) % sizeof(n->late)] |= 1 << i % 8;
268 n->late[(inpkt->seqno / 8) % sizeof(n->late)] &= ~(1 << inpkt->seqno % 8);
270 if(inpkt->seqno > n->received_seqno)
271 n->received_seqno = inpkt->seqno;
273 if(n->received_seqno > MAX_SEQNO)
276 /* Decompress the packet */
278 length_t origlen = inpkt->len;
280 if(n->incompression) {
281 outpkt = pkt[nextpkt++];
283 if((outpkt->len = uncompress_packet(outpkt->data, inpkt->data, inpkt->len, n->incompression)) < 0) {
284 ifdebug(TRAFFIC) logger(LOG_ERR, _("Error while uncompressing packet from %s (%s)"),
285 n->name, n->hostname);
291 origlen -= MTU/64 + 20;
297 n->connection->last_ping_time = now;
299 if(!inpkt->data[12] && !inpkt->data[13])
300 mtu_probe_h(n, inpkt, origlen);
302 receive_packet(n, inpkt);
305 void receive_tcppacket(connection_t *c, char *buffer, int len)
312 if(c->options & OPTION_TCPONLY)
315 outpkt.priority = -1;
316 memcpy(outpkt.data, buffer, len);
318 receive_packet(c->node, &outpkt);
321 static void send_udppacket(node_t *n, vpn_packet_t *origpkt)
323 vpn_packet_t pkt1, pkt2;
324 vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
325 vpn_packet_t *inpkt = origpkt;
327 vpn_packet_t *outpkt;
330 static int priority = 0;
336 if(!n->status.reachable) {
337 ifdebug(TRAFFIC) logger(LOG_INFO, _("Trying to send UDP packet to unreachable node %s (%s)"), n->name, n->hostname);
341 /* Make sure we have a valid key */
343 if(!n->status.validkey) {
344 ifdebug(TRAFFIC) logger(LOG_INFO,
345 _("No valid key known yet for %s (%s), forwarding via TCP"),
346 n->name, n->hostname);
348 if(!n->status.waitingforkey)
351 n->status.waitingforkey = true;
353 send_tcppacket(n->nexthop->connection, origpkt);
358 if(n->options & OPTION_PMTU_DISCOVERY && !n->minmtu && (inpkt->data[12] | inpkt->data[13])) {
359 ifdebug(TRAFFIC) logger(LOG_INFO,
360 _("No minimum MTU established yet for %s (%s), forwarding via TCP"),
361 n->name, n->hostname);
363 send_tcppacket(n->nexthop->connection, origpkt);
368 origlen = inpkt->len;
369 origpriority = inpkt->priority;
371 /* Compress the packet */
373 if(n->outcompression) {
374 outpkt = pkt[nextpkt++];
376 if((outpkt->len = compress_packet(outpkt->data, inpkt->data, inpkt->len, n->outcompression)) < 0) {
377 ifdebug(TRAFFIC) logger(LOG_ERR, _("Error while compressing packet to %s (%s)"),
378 n->name, n->hostname);
385 /* Add sequence number */
387 inpkt->seqno = htonl(++(n->sent_seqno));
388 inpkt->len += sizeof(inpkt->seqno);
390 /* Encrypt the packet */
393 outpkt = pkt[nextpkt++];
395 if(!EVP_EncryptInit_ex(&n->outctx, NULL, NULL, NULL, NULL)
396 || !EVP_EncryptUpdate(&n->outctx, (unsigned char *) &outpkt->seqno, &outlen,
397 (unsigned char *) &inpkt->seqno, inpkt->len)
398 || !EVP_EncryptFinal_ex(&n->outctx, (unsigned char *) &outpkt->seqno + outlen, &outpad)) {
399 ifdebug(TRAFFIC) logger(LOG_ERR, _("Error while encrypting packet to %s (%s): %s"),
400 n->name, n->hostname, ERR_error_string(ERR_get_error(), NULL));
404 outpkt->len = outlen + outpad;
408 /* Add the message authentication code */
410 if(n->outdigest && n->outmaclength) {
411 HMAC(n->outdigest, n->outkey, n->outkeylength, (unsigned char *) &inpkt->seqno,
412 inpkt->len, (unsigned char *) &inpkt->seqno + inpkt->len, NULL);
413 inpkt->len += n->outmaclength;
416 /* Determine which socket we have to use */
418 for(sock = 0; sock < listen_sockets; sock++)
419 if(n->address.sa.sa_family == listen_socket[sock].sa.sa.sa_family)
422 if(sock >= listen_sockets)
423 sock = 0; /* If none is available, just use the first and hope for the best. */
425 /* Send the packet */
427 #if defined(SOL_IP) && defined(IP_TOS)
428 if(priorityinheritance && origpriority != priority
429 && listen_socket[sock].sa.sa.sa_family == AF_INET) {
430 priority = origpriority;
431 ifdebug(TRAFFIC) logger(LOG_DEBUG, _("Setting outgoing packet priority to %d"), priority);
432 if(setsockopt(listen_socket[sock].udp, SOL_IP, IP_TOS, &priority, sizeof(priority))) /* SO_PRIORITY doesn't seem to work */
433 logger(LOG_ERR, _("System call `%s' failed: %s"), "setsockopt", strerror(errno));
437 if((sendto(listen_socket[sock].udp, (char *) &inpkt->seqno, inpkt->len, 0, &(n->address.sa), SALEN(n->address.sa))) < 0) {
438 if(errno == EMSGSIZE) {
439 if(n->maxmtu >= origlen)
440 n->maxmtu = origlen - 1;
441 if(n->mtu >= origlen)
442 n->mtu = origlen - 1;
444 logger(LOG_ERR, _("Error sending packet to %s (%s): %s"), n->name, n->hostname, strerror(errno));
448 origpkt->len = origlen;
452 send a packet to the given vpn ip.
454 void send_packet(const node_t *n, vpn_packet_t *packet)
462 memcpy(packet->data, mymac.x, ETH_ALEN);
463 write_packet(packet);
467 ifdebug(TRAFFIC) logger(LOG_ERR, _("Sending packet of %d bytes to %s (%s)"),
468 packet->len, n->name, n->hostname);
470 if(!n->status.reachable) {
471 ifdebug(TRAFFIC) logger(LOG_INFO, _("Node %s (%s) is not reachable"),
472 n->name, n->hostname);
476 via = (packet->priority == -1 || n->via == myself) ? n->nexthop : n->via;
479 ifdebug(TRAFFIC) logger(LOG_INFO, _("Sending packet to %s via %s (%s)"),
480 n->name, via->name, n->via->hostname);
482 if(packet->priority == -1 || ((myself->options | via->options) & OPTION_TCPONLY)) {
483 if(!send_tcppacket(via->connection, packet))
484 terminate_connection(via->connection, true);
486 send_udppacket(via, packet);
489 /* Broadcast a packet using the minimum spanning tree */
491 void broadcast_packet(const node_t *from, vpn_packet_t *packet)
498 ifdebug(TRAFFIC) logger(LOG_INFO, _("Broadcasting packet of %d bytes from %s (%s)"),
499 packet->len, from->name, from->hostname);
502 send_packet(myself, packet);
504 // In TunnelServer mode, do not forward broadcast packets.
505 // The MST might not be valid and create loops.
510 for(node = connection_tree->head; node; node = node->next) {
513 if(c->status.active && c->status.mst && c != from->nexthop->connection)
514 send_packet(c->node, packet);
518 static node_t *try_harder(const sockaddr_t *from, const vpn_packet_t *pkt) {
523 for(node = edge_weight_tree->head; node; node = node->next) {
526 if(sockaddrcmp_noport(from, &e->address))
532 if(!try_mac(e->to, pkt))
542 void handle_incoming_vpn_data(int sock)
547 socklen_t fromlen = sizeof(from);
552 pkt.len = recvfrom(sock, (char *) &pkt.seqno, MAXSIZE, 0, &from.sa, &fromlen);
555 if(errno != EAGAIN && errno != EINTR)
556 logger(LOG_ERR, _("Receiving packet failed: %s"), strerror(errno));
560 sockaddrunmap(&from); /* Some braindead IPv6 implementations do stupid things. */
562 n = lookup_node_udp(&from);
565 n = try_harder(&from, &pkt);
567 update_node_udp(n, &from);
568 else ifdebug(PROTOCOL) {
569 hostname = sockaddr2hostname(&from);
570 logger(LOG_WARNING, _("Received UDP packet from unknown source %s"), hostname);
578 receive_udppacket(n, &pkt);