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 void send_mtu_probe(node_t *n) {
70 if(!n->status.reachable) {
71 logger(LOG_DEBUG, _("Trying to send MTU probe to unreachable node %s (%s)"), n->name, n->hostname);
75 if(n->mtuprobes >= 10 && !n->minmtu) {
76 ifdebug(TRAFFIC) logger(LOG_INFO, _("No response to MTU probes from %s (%s)"), n->name, n->hostname);
80 for(i = 0; i < 3; i++) {
81 if(n->mtuprobes >= 30 || n->minmtu >= n->maxmtu) {
83 ifdebug(TRAFFIC) logger(LOG_INFO, _("Fixing MTU of %s (%s) to %d after %d probes"), n->name, n->hostname, n->mtu, n->mtuprobes);
87 len = n->minmtu + 1 + rand() % (n->maxmtu - n->minmtu);
91 memset(packet.data, 0, 14);
92 RAND_pseudo_bytes(packet.data + 14, len - 14);
96 ifdebug(TRAFFIC) logger(LOG_INFO, _("Sending MTU probe length %d to %s (%s)"), len, n->name, n->hostname);
98 send_udppacket(n, &packet);
101 n->mtuevent = new_event();
102 n->mtuevent->handler = (event_handler_t)send_mtu_probe;
103 n->mtuevent->data = n;
104 n->mtuevent->time = now + 1;
105 event_add(n->mtuevent);
108 void mtu_probe_h(node_t *n, vpn_packet_t *packet, length_t len) {
109 ifdebug(TRAFFIC) logger(LOG_INFO, _("Got MTU probe length %d from %s (%s)"), packet->len, n->name, n->hostname);
111 if(!packet->data[0]) {
113 send_packet(n, packet);
120 static length_t compress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level) {
122 lzo_uint lzolen = MAXSIZE;
123 lzo1x_1_compress(source, len, dest, &lzolen, lzo_wrkmem);
125 } else if(level < 10) {
126 unsigned long destlen = MAXSIZE;
127 if(compress2(dest, &destlen, source, len, level) == Z_OK)
132 lzo_uint lzolen = MAXSIZE;
133 lzo1x_999_compress(source, len, dest, &lzolen, lzo_wrkmem);
140 static length_t uncompress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level) {
142 lzo_uint lzolen = MAXSIZE;
143 if(lzo1x_decompress_safe(source, len, dest, &lzolen, NULL) == LZO_E_OK)
148 unsigned long destlen = MAXSIZE;
149 if(uncompress(dest, &destlen, source, len) == Z_OK)
160 static void receive_packet(node_t *n, vpn_packet_t *packet) {
163 ifdebug(TRAFFIC) logger(LOG_DEBUG, _("Received packet of %d bytes from %s (%s)"),
164 packet->len, n->name, n->hostname);
169 static bool try_mac(const node_t *n, const vpn_packet_t *inpkt) {
170 unsigned char hmac[EVP_MAX_MD_SIZE];
172 if(!n->indigest || !n->inmaclength || !n->inkey || inpkt->len < sizeof inpkt->seqno + n->inmaclength)
175 HMAC(n->indigest, n->inkey, n->inkeylength, (unsigned char *) &inpkt->seqno, inpkt->len - n->inmaclength, (unsigned char *)hmac, NULL);
177 return !memcmp(hmac, (char *) &inpkt->seqno + inpkt->len - n->inmaclength, n->inmaclength);
180 static void receive_udppacket(node_t *n, vpn_packet_t *inpkt) {
181 vpn_packet_t pkt1, pkt2;
182 vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
184 vpn_packet_t *outpkt = pkt[0];
186 unsigned char hmac[EVP_MAX_MD_SIZE];
192 ifdebug(TRAFFIC) logger(LOG_DEBUG, _("Got packet from %s (%s) but he hasn't got our key yet"),
193 n->name, n->hostname);
197 /* Check packet length */
199 if(inpkt->len < sizeof(inpkt->seqno) + n->inmaclength) {
200 ifdebug(TRAFFIC) logger(LOG_DEBUG, _("Got too short packet from %s (%s)"),
201 n->name, n->hostname);
205 /* Check the message authentication code */
207 if(n->indigest && n->inmaclength) {
208 inpkt->len -= n->inmaclength;
209 HMAC(n->indigest, n->inkey, n->inkeylength,
210 (unsigned char *) &inpkt->seqno, inpkt->len, (unsigned char *)hmac, NULL);
212 if(memcmp(hmac, (char *) &inpkt->seqno + inpkt->len, n->inmaclength)) {
213 ifdebug(TRAFFIC) logger(LOG_DEBUG, _("Got unauthenticated packet from %s (%s)"),
214 n->name, n->hostname);
219 /* Decrypt the packet */
222 outpkt = pkt[nextpkt++];
224 if(!EVP_DecryptInit_ex(&n->inctx, NULL, NULL, NULL, NULL)
225 || !EVP_DecryptUpdate(&n->inctx, (unsigned char *) &outpkt->seqno, &outlen,
226 (unsigned char *) &inpkt->seqno, inpkt->len)
227 || !EVP_DecryptFinal_ex(&n->inctx, (unsigned char *) &outpkt->seqno + outlen, &outpad)) {
228 ifdebug(TRAFFIC) logger(LOG_DEBUG, _("Error decrypting packet from %s (%s): %s"),
229 n->name, n->hostname, ERR_error_string(ERR_get_error(), NULL));
233 outpkt->len = outlen + outpad;
237 /* Check the sequence number */
239 inpkt->len -= sizeof(inpkt->seqno);
240 inpkt->seqno = ntohl(inpkt->seqno);
242 if(inpkt->seqno != n->received_seqno + 1) {
243 if(inpkt->seqno >= n->received_seqno + sizeof(n->late) * 8) {
244 logger(LOG_WARNING, _("Lost %d packets from %s (%s)"),
245 inpkt->seqno - n->received_seqno - 1, n->name, n->hostname);
247 memset(n->late, 0, sizeof(n->late));
248 } else if (inpkt->seqno <= n->received_seqno) {
249 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))) {
250 logger(LOG_WARNING, _("Got late or replayed packet from %s (%s), seqno %d, last received %d"),
251 n->name, n->hostname, inpkt->seqno, n->received_seqno);
255 for(i = n->received_seqno + 1; i < inpkt->seqno; i++)
256 n->late[(i / 8) % sizeof(n->late)] |= 1 << i % 8;
260 n->late[(inpkt->seqno / 8) % sizeof(n->late)] &= ~(1 << inpkt->seqno % 8);
262 if(inpkt->seqno > n->received_seqno)
263 n->received_seqno = inpkt->seqno;
265 if(n->received_seqno > MAX_SEQNO)
268 /* Decompress the packet */
270 length_t origlen = inpkt->len;
272 if(n->incompression) {
273 outpkt = pkt[nextpkt++];
275 if((outpkt->len = uncompress_packet(outpkt->data, inpkt->data, inpkt->len, n->incompression)) < 0) {
276 ifdebug(TRAFFIC) logger(LOG_ERR, _("Error while uncompressing packet from %s (%s)"),
277 n->name, n->hostname);
283 origlen -= MTU/64 + 20;
289 n->connection->last_ping_time = now;
291 if(!inpkt->data[12] && !inpkt->data[13])
292 mtu_probe_h(n, inpkt, origlen);
294 receive_packet(n, inpkt);
297 void receive_tcppacket(connection_t *c, char *buffer, int len) {
303 if(c->options & OPTION_TCPONLY)
306 outpkt.priority = -1;
307 memcpy(outpkt.data, buffer, len);
309 receive_packet(c->node, &outpkt);
312 static void send_udppacket(node_t *n, vpn_packet_t *origpkt) {
313 vpn_packet_t pkt1, pkt2;
314 vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
315 vpn_packet_t *inpkt = origpkt;
317 vpn_packet_t *outpkt;
320 static int priority = 0;
326 if(!n->status.reachable) {
327 ifdebug(TRAFFIC) logger(LOG_INFO, _("Trying to send UDP packet to unreachable node %s (%s)"), n->name, n->hostname);
331 /* Make sure we have a valid key */
333 if(!n->status.validkey) {
334 ifdebug(TRAFFIC) logger(LOG_INFO,
335 _("No valid key known yet for %s (%s), forwarding via TCP"),
336 n->name, n->hostname);
338 if(!n->status.waitingforkey)
341 n->status.waitingforkey = true;
343 send_tcppacket(n->nexthop->connection, origpkt);
348 if(n->options & OPTION_PMTU_DISCOVERY && inpkt->len > n->minmtu && (inpkt->data[12] | inpkt->data[13])) {
349 ifdebug(TRAFFIC) logger(LOG_INFO,
350 _("Packet for %s (%s) larger than minimum MTU, forwarding via TCP"),
351 n->name, n->hostname);
353 send_tcppacket(n->nexthop->connection, origpkt);
358 origlen = inpkt->len;
359 origpriority = inpkt->priority;
361 /* Compress the packet */
363 if(n->outcompression) {
364 outpkt = pkt[nextpkt++];
366 if((outpkt->len = compress_packet(outpkt->data, inpkt->data, inpkt->len, n->outcompression)) < 0) {
367 ifdebug(TRAFFIC) logger(LOG_ERR, _("Error while compressing packet to %s (%s)"),
368 n->name, n->hostname);
375 /* Add sequence number */
377 inpkt->seqno = htonl(++(n->sent_seqno));
378 inpkt->len += sizeof(inpkt->seqno);
380 /* Encrypt the packet */
383 outpkt = pkt[nextpkt++];
385 if(!EVP_EncryptInit_ex(&n->outctx, NULL, NULL, NULL, NULL)
386 || !EVP_EncryptUpdate(&n->outctx, (unsigned char *) &outpkt->seqno, &outlen,
387 (unsigned char *) &inpkt->seqno, inpkt->len)
388 || !EVP_EncryptFinal_ex(&n->outctx, (unsigned char *) &outpkt->seqno + outlen, &outpad)) {
389 ifdebug(TRAFFIC) logger(LOG_ERR, _("Error while encrypting packet to %s (%s): %s"),
390 n->name, n->hostname, ERR_error_string(ERR_get_error(), NULL));
394 outpkt->len = outlen + outpad;
398 /* Add the message authentication code */
400 if(n->outdigest && n->outmaclength) {
401 HMAC(n->outdigest, n->outkey, n->outkeylength, (unsigned char *) &inpkt->seqno,
402 inpkt->len, (unsigned char *) &inpkt->seqno + inpkt->len, NULL);
403 inpkt->len += n->outmaclength;
406 /* Determine which socket we have to use */
408 for(sock = 0; sock < listen_sockets; sock++)
409 if(n->address.sa.sa_family == listen_socket[sock].sa.sa.sa_family)
412 if(sock >= listen_sockets)
413 sock = 0; /* If none is available, just use the first and hope for the best. */
415 /* Send the packet */
417 #if defined(SOL_IP) && defined(IP_TOS)
418 if(priorityinheritance && origpriority != priority
419 && listen_socket[sock].sa.sa.sa_family == AF_INET) {
420 priority = origpriority;
421 ifdebug(TRAFFIC) logger(LOG_DEBUG, _("Setting outgoing packet priority to %d"), priority);
422 if(setsockopt(listen_socket[sock].udp, SOL_IP, IP_TOS, &priority, sizeof(priority))) /* SO_PRIORITY doesn't seem to work */
423 logger(LOG_ERR, _("System call `%s' failed: %s"), "setsockopt", strerror(errno));
427 if((sendto(listen_socket[sock].udp, (char *) &inpkt->seqno, inpkt->len, 0, &(n->address.sa), SALEN(n->address.sa))) < 0) {
428 if(errno == EMSGSIZE) {
429 if(n->maxmtu >= origlen)
430 n->maxmtu = origlen - 1;
431 if(n->mtu >= origlen)
432 n->mtu = origlen - 1;
434 logger(LOG_ERR, _("Error sending packet to %s (%s): %s"), n->name, n->hostname, strerror(errno));
438 origpkt->len = origlen;
442 send a packet to the given vpn ip.
444 void send_packet(const node_t *n, vpn_packet_t *packet) {
451 memcpy(packet->data, mymac.x, ETH_ALEN);
452 write_packet(packet);
456 ifdebug(TRAFFIC) logger(LOG_ERR, _("Sending packet of %d bytes to %s (%s)"),
457 packet->len, n->name, n->hostname);
459 if(!n->status.reachable) {
460 ifdebug(TRAFFIC) logger(LOG_INFO, _("Node %s (%s) is not reachable"),
461 n->name, n->hostname);
465 via = (packet->priority == -1 || n->via == myself) ? n->nexthop : n->via;
468 ifdebug(TRAFFIC) logger(LOG_INFO, _("Sending packet to %s via %s (%s)"),
469 n->name, via->name, n->via->hostname);
471 if(packet->priority == -1 || ((myself->options | via->options) & OPTION_TCPONLY)) {
472 if(!send_tcppacket(via->connection, packet))
473 terminate_connection(via->connection, true);
475 send_udppacket(via, packet);
478 /* Broadcast a packet using the minimum spanning tree */
480 void broadcast_packet(const node_t *from, vpn_packet_t *packet) {
486 ifdebug(TRAFFIC) logger(LOG_INFO, _("Broadcasting packet of %d bytes from %s (%s)"),
487 packet->len, from->name, from->hostname);
490 send_packet(myself, packet);
492 // In TunnelServer mode, do not forward broadcast packets.
493 // The MST might not be valid and create loops.
498 for(node = connection_tree->head; node; node = node->next) {
501 if(c->status.active && c->status.mst && c != from->nexthop->connection)
502 send_packet(c->node, packet);
506 static node_t *try_harder(const sockaddr_t *from, const vpn_packet_t *pkt) {
511 for(node = edge_weight_tree->head; node; node = node->next) {
514 if(sockaddrcmp_noport(from, &e->address))
520 if(!try_mac(e->to, pkt))
530 void handle_incoming_vpn_data(int sock) {
534 socklen_t fromlen = sizeof(from);
539 pkt.len = recvfrom(sock, (char *) &pkt.seqno, MAXSIZE, 0, &from.sa, &fromlen);
542 if(errno != EAGAIN && errno != EINTR)
543 logger(LOG_ERR, _("Receiving packet failed: %s"), strerror(errno));
547 sockaddrunmap(&from); /* Some braindead IPv6 implementations do stupid things. */
549 n = lookup_node_udp(&from);
552 n = try_harder(&from, &pkt);
554 update_node_udp(n, &from);
555 else ifdebug(PROTOCOL) {
556 hostname = sockaddr2hostname(&from);
557 logger(LOG_WARNING, _("Received UDP packet from unknown source %s"), hostname);
565 receive_udppacket(n, &pkt);