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.
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 void send_mtu_probe(node_t *n)
71 if(!n->status.reachable) {
72 logger(LOG_DEBUG, _("Trying to send MTU probe to unreachable node %s (%s)"), n->name, n->hostname);
76 if(n->mtuprobes >= 10 && !n->minmtu) {
77 ifdebug(TRAFFIC) logger(LOG_INFO, _("No response to MTU probes from %s (%s)"), n->name, n->hostname);
81 for(i = 0; i < 3; i++) {
82 if(n->mtuprobes >= 30 || n->minmtu >= n->maxmtu) {
84 ifdebug(TRAFFIC) logger(LOG_INFO, _("Fixing MTU of %s (%s) to %d after %d probes"), n->name, n->hostname, n->mtu, n->mtuprobes);
88 len = n->minmtu + 1 + rand() % (n->maxmtu - n->minmtu);
92 memset(packet.data, 0, 14);
93 RAND_pseudo_bytes(packet.data + 14, len - 14);
97 ifdebug(TRAFFIC) logger(LOG_INFO, _("Sending MTU probe length %d to %s (%s)"), len, n->name, n->hostname);
99 send_udppacket(n, &packet);
102 n->mtuevent = new_event();
103 n->mtuevent->handler = (event_handler_t)send_mtu_probe;
104 n->mtuevent->data = n;
105 n->mtuevent->time = now + 1;
106 event_add(n->mtuevent);
109 void mtu_probe_h(node_t *n, vpn_packet_t *packet, length_t len) {
110 ifdebug(TRAFFIC) logger(LOG_INFO, _("Got MTU probe length %d from %s (%s)"), packet->len, n->name, n->hostname);
112 if(!packet->data[0]) {
114 send_packet(n, packet);
121 static length_t compress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level)
124 lzo_uint lzolen = MAXSIZE;
125 lzo1x_1_compress(source, len, dest, &lzolen, lzo_wrkmem);
127 } else if(level < 10) {
128 unsigned long destlen = MAXSIZE;
129 if(compress2(dest, &destlen, source, len, level) == Z_OK)
134 lzo_uint lzolen = MAXSIZE;
135 lzo1x_999_compress(source, len, dest, &lzolen, lzo_wrkmem);
142 static length_t uncompress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level)
145 lzo_uint lzolen = MAXSIZE;
146 if(lzo1x_decompress_safe(source, len, dest, &lzolen, NULL) == LZO_E_OK)
151 unsigned long destlen = MAXSIZE;
152 if(uncompress(dest, &destlen, source, len) == Z_OK)
163 static void receive_packet(node_t *n, vpn_packet_t *packet)
167 ifdebug(TRAFFIC) logger(LOG_DEBUG, _("Received packet of %d bytes from %s (%s)"),
168 packet->len, n->name, n->hostname);
173 static bool try_mac(const node_t *n, const vpn_packet_t *inpkt)
175 unsigned char hmac[EVP_MAX_MD_SIZE];
177 if(!n->indigest || !n->inmaclength || !n->inkey || inpkt->len < sizeof inpkt->seqno + n->inmaclength)
180 HMAC(n->indigest, n->inkey, n->inkeylength, (unsigned char *) &inpkt->seqno, inpkt->len - n->inmaclength, (unsigned char *)hmac, NULL);
182 return !memcmp(hmac, (char *) &inpkt->seqno + inpkt->len - n->inmaclength, n->inmaclength);
185 static void receive_udppacket(node_t *n, vpn_packet_t *inpkt)
187 vpn_packet_t pkt1, pkt2;
188 vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
190 vpn_packet_t *outpkt = pkt[0];
192 unsigned char hmac[EVP_MAX_MD_SIZE];
198 ifdebug(TRAFFIC) logger(LOG_DEBUG, _("Got packet from %s (%s) but he hasn't got our key yet"),
199 n->name, n->hostname);
203 /* Check packet length */
205 if(inpkt->len < sizeof(inpkt->seqno) + n->inmaclength) {
206 ifdebug(TRAFFIC) logger(LOG_DEBUG, _("Got too short packet from %s (%s)"),
207 n->name, n->hostname);
211 /* Check the message authentication code */
213 if(n->indigest && n->inmaclength) {
214 inpkt->len -= n->inmaclength;
215 HMAC(n->indigest, n->inkey, n->inkeylength,
216 (unsigned char *) &inpkt->seqno, inpkt->len, (unsigned char *)hmac, NULL);
218 if(memcmp(hmac, (char *) &inpkt->seqno + inpkt->len, n->inmaclength)) {
219 ifdebug(TRAFFIC) logger(LOG_DEBUG, _("Got unauthenticated packet from %s (%s)"),
220 n->name, n->hostname);
225 /* Decrypt the packet */
228 outpkt = pkt[nextpkt++];
230 if(!EVP_DecryptInit_ex(&n->inctx, NULL, NULL, NULL, NULL)
231 || !EVP_DecryptUpdate(&n->inctx, (unsigned char *) &outpkt->seqno, &outlen,
232 (unsigned char *) &inpkt->seqno, inpkt->len)
233 || !EVP_DecryptFinal_ex(&n->inctx, (unsigned char *) &outpkt->seqno + outlen, &outpad)) {
234 ifdebug(TRAFFIC) logger(LOG_DEBUG, _("Error decrypting packet from %s (%s): %s"),
235 n->name, n->hostname, ERR_error_string(ERR_get_error(), NULL));
239 outpkt->len = outlen + outpad;
243 /* Check the sequence number */
245 inpkt->len -= sizeof(inpkt->seqno);
246 inpkt->seqno = ntohl(inpkt->seqno);
248 if(inpkt->seqno != n->received_seqno + 1) {
249 if(inpkt->seqno >= n->received_seqno + sizeof(n->late) * 8) {
250 logger(LOG_WARNING, _("Lost %d packets from %s (%s)"),
251 inpkt->seqno - n->received_seqno - 1, n->name, n->hostname);
253 memset(n->late, 0, sizeof(n->late));
254 } else if (inpkt->seqno <= n->received_seqno) {
255 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))) {
256 logger(LOG_WARNING, _("Got late or replayed packet from %s (%s), seqno %d, last received %d"),
257 n->name, n->hostname, inpkt->seqno, n->received_seqno);
261 for(i = n->received_seqno + 1; i < inpkt->seqno; i++)
262 n->late[(i / 8) % sizeof(n->late)] |= 1 << i % 8;
266 n->late[(inpkt->seqno / 8) % sizeof(n->late)] &= ~(1 << inpkt->seqno % 8);
268 if(inpkt->seqno > n->received_seqno)
269 n->received_seqno = inpkt->seqno;
271 if(n->received_seqno > MAX_SEQNO)
274 /* Decompress the packet */
276 length_t origlen = inpkt->len;
278 if(n->incompression) {
279 outpkt = pkt[nextpkt++];
281 if((outpkt->len = uncompress_packet(outpkt->data, inpkt->data, inpkt->len, n->incompression)) < 0) {
282 ifdebug(TRAFFIC) logger(LOG_ERR, _("Error while uncompressing packet from %s (%s)"),
283 n->name, n->hostname);
289 origlen -= MTU/64 + 20;
295 n->connection->last_ping_time = now;
297 if(!inpkt->data[12] && !inpkt->data[13])
298 mtu_probe_h(n, inpkt, origlen);
300 receive_packet(n, inpkt);
303 void receive_tcppacket(connection_t *c, char *buffer, int len)
310 if(c->options & OPTION_TCPONLY)
313 outpkt.priority = -1;
314 memcpy(outpkt.data, buffer, len);
316 receive_packet(c->node, &outpkt);
319 static void send_udppacket(node_t *n, vpn_packet_t *origpkt)
321 vpn_packet_t pkt1, pkt2;
322 vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
323 vpn_packet_t *inpkt = origpkt;
325 vpn_packet_t *outpkt;
328 static int priority = 0;
334 if(!n->status.reachable) {
335 ifdebug(TRAFFIC) logger(LOG_INFO, _("Trying to send UDP packet to unreachable node %s (%s)"), n->name, n->hostname);
339 /* Make sure we have a valid key */
341 if(!n->status.validkey) {
342 ifdebug(TRAFFIC) logger(LOG_INFO,
343 _("No valid key known yet for %s (%s), forwarding via TCP"),
344 n->name, n->hostname);
346 if(!n->status.waitingforkey)
349 n->status.waitingforkey = true;
351 send_tcppacket(n->nexthop->connection, origpkt);
356 if(n->options & OPTION_PMTU_DISCOVERY && inpkt->len > n->minmtu && (inpkt->data[12] | inpkt->data[13])) {
357 ifdebug(TRAFFIC) logger(LOG_INFO,
358 _("Packet for %s (%s) larger than minimum MTU, forwarding via TCP"),
359 n->name, n->hostname);
361 send_tcppacket(n->nexthop->connection, origpkt);
366 origlen = inpkt->len;
367 origpriority = inpkt->priority;
369 /* Compress the packet */
371 if(n->outcompression) {
372 outpkt = pkt[nextpkt++];
374 if((outpkt->len = compress_packet(outpkt->data, inpkt->data, inpkt->len, n->outcompression)) < 0) {
375 ifdebug(TRAFFIC) logger(LOG_ERR, _("Error while compressing packet to %s (%s)"),
376 n->name, n->hostname);
383 /* Add sequence number */
385 inpkt->seqno = htonl(++(n->sent_seqno));
386 inpkt->len += sizeof(inpkt->seqno);
388 /* Encrypt the packet */
391 outpkt = pkt[nextpkt++];
393 if(!EVP_EncryptInit_ex(&n->outctx, NULL, NULL, NULL, NULL)
394 || !EVP_EncryptUpdate(&n->outctx, (unsigned char *) &outpkt->seqno, &outlen,
395 (unsigned char *) &inpkt->seqno, inpkt->len)
396 || !EVP_EncryptFinal_ex(&n->outctx, (unsigned char *) &outpkt->seqno + outlen, &outpad)) {
397 ifdebug(TRAFFIC) logger(LOG_ERR, _("Error while encrypting packet to %s (%s): %s"),
398 n->name, n->hostname, ERR_error_string(ERR_get_error(), NULL));
402 outpkt->len = outlen + outpad;
406 /* Add the message authentication code */
408 if(n->outdigest && n->outmaclength) {
409 HMAC(n->outdigest, n->outkey, n->outkeylength, (unsigned char *) &inpkt->seqno,
410 inpkt->len, (unsigned char *) &inpkt->seqno + inpkt->len, NULL);
411 inpkt->len += n->outmaclength;
414 /* Determine which socket we have to use */
416 for(sock = 0; sock < listen_sockets; sock++)
417 if(n->address.sa.sa_family == listen_socket[sock].sa.sa.sa_family)
420 if(sock >= listen_sockets)
421 sock = 0; /* If none is available, just use the first and hope for the best. */
423 /* Send the packet */
425 #if defined(SOL_IP) && defined(IP_TOS)
426 if(priorityinheritance && origpriority != priority
427 && listen_socket[sock].sa.sa.sa_family == AF_INET) {
428 priority = origpriority;
429 ifdebug(TRAFFIC) logger(LOG_DEBUG, _("Setting outgoing packet priority to %d"), priority);
430 if(setsockopt(listen_socket[sock].udp, SOL_IP, IP_TOS, &priority, sizeof(priority))) /* SO_PRIORITY doesn't seem to work */
431 logger(LOG_ERR, _("System call `%s' failed: %s"), "setsockopt", strerror(errno));
435 if((sendto(listen_socket[sock].udp, (char *) &inpkt->seqno, inpkt->len, 0, &(n->address.sa), SALEN(n->address.sa))) < 0) {
436 if(errno == EMSGSIZE) {
437 if(n->maxmtu >= origlen)
438 n->maxmtu = origlen - 1;
439 if(n->mtu >= origlen)
440 n->mtu = origlen - 1;
442 logger(LOG_ERR, _("Error sending packet to %s (%s): %s"), n->name, n->hostname, strerror(errno));
446 origpkt->len = origlen;
450 send a packet to the given vpn ip.
452 void send_packet(const node_t *n, vpn_packet_t *packet)
460 memcpy(packet->data, mymac.x, ETH_ALEN);
461 write_packet(packet);
465 ifdebug(TRAFFIC) logger(LOG_ERR, _("Sending packet of %d bytes to %s (%s)"),
466 packet->len, n->name, n->hostname);
468 if(!n->status.reachable) {
469 ifdebug(TRAFFIC) logger(LOG_INFO, _("Node %s (%s) is not reachable"),
470 n->name, n->hostname);
474 via = (packet->priority == -1 || n->via == myself) ? n->nexthop : n->via;
477 ifdebug(TRAFFIC) logger(LOG_INFO, _("Sending packet to %s via %s (%s)"),
478 n->name, via->name, n->via->hostname);
480 if(packet->priority == -1 || ((myself->options | via->options) & OPTION_TCPONLY)) {
481 if(!send_tcppacket(via->connection, packet))
482 terminate_connection(via->connection, true);
484 send_udppacket(via, packet);
487 /* Broadcast a packet using the minimum spanning tree */
489 void broadcast_packet(const node_t *from, vpn_packet_t *packet)
496 ifdebug(TRAFFIC) logger(LOG_INFO, _("Broadcasting packet of %d bytes from %s (%s)"),
497 packet->len, from->name, from->hostname);
500 send_packet(myself, packet);
502 // In TunnelServer mode, do not forward broadcast packets.
503 // The MST might not be valid and create loops.
508 for(node = connection_tree->head; node; node = node->next) {
511 if(c->status.active && c->status.mst && c != from->nexthop->connection)
512 send_packet(c->node, packet);
516 static node_t *try_harder(const sockaddr_t *from, const vpn_packet_t *pkt) {
521 for(node = edge_weight_tree->head; node; node = node->next) {
524 if(sockaddrcmp_noport(from, &e->address))
530 if(!try_mac(e->to, pkt))
540 void handle_incoming_vpn_data(int sock)
545 socklen_t fromlen = sizeof(from);
550 pkt.len = recvfrom(sock, (char *) &pkt.seqno, MAXSIZE, 0, &from.sa, &fromlen);
553 if(errno != EAGAIN && errno != EINTR)
554 logger(LOG_ERR, _("Receiving packet failed: %s"), strerror(errno));
558 sockaddrunmap(&from); /* Some braindead IPv6 implementations do stupid things. */
560 n = lookup_node_udp(&from);
563 n = try_harder(&from, &pkt);
565 update_node_udp(n, &from);
566 else ifdebug(PROTOCOL) {
567 hostname = sockaddr2hostname(&from);
568 logger(LOG_WARNING, _("Received UDP packet from unknown source %s"), hostname);
576 receive_udppacket(n, &pkt);