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) {
68 if(!n->status.reachable) {
69 logger(LOG_DEBUG, "Trying to send MTU probe to unreachable node %s (%s)", n->name, n->hostname);
73 if(n->mtuprobes >= 10 && !n->minmtu) {
74 ifdebug(TRAFFIC) logger(LOG_INFO, "No response to MTU probes from %s (%s)", n->name, n->hostname);
78 for(i = 0; i < 3; i++) {
79 if(n->mtuprobes >= 30 || n->minmtu >= n->maxmtu) {
81 ifdebug(TRAFFIC) logger(LOG_INFO, "Fixing MTU of %s (%s) to %d after %d probes", n->name, n->hostname, n->mtu, n->mtuprobes);
85 len = n->minmtu + 1 + rand() % (n->maxmtu - n->minmtu);
89 memset(packet.data, 0, 14);
90 RAND_pseudo_bytes(packet.data + 14, len - 14);
94 ifdebug(TRAFFIC) logger(LOG_INFO, "Sending MTU probe length %d to %s (%s)", len, n->name, n->hostname);
96 send_udppacket(n, &packet);
99 n->mtuevent = new_event();
100 n->mtuevent->handler = (event_handler_t)send_mtu_probe;
101 n->mtuevent->data = n;
102 n->mtuevent->time = now + 1;
103 event_add(n->mtuevent);
106 void mtu_probe_h(node_t *n, vpn_packet_t *packet, length_t len) {
107 ifdebug(TRAFFIC) logger(LOG_INFO, "Got MTU probe length %d from %s (%s)", packet->len, n->name, n->hostname);
109 if(!packet->data[0]) {
111 send_packet(n, packet);
118 static length_t compress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level) {
120 lzo_uint lzolen = MAXSIZE;
121 lzo1x_1_compress(source, len, dest, &lzolen, lzo_wrkmem);
123 } else if(level < 10) {
124 unsigned long destlen = MAXSIZE;
125 if(compress2(dest, &destlen, source, len, level) == Z_OK)
130 lzo_uint lzolen = MAXSIZE;
131 lzo1x_999_compress(source, len, dest, &lzolen, lzo_wrkmem);
138 static length_t uncompress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level) {
140 lzo_uint lzolen = MAXSIZE;
141 if(lzo1x_decompress_safe(source, len, dest, &lzolen, NULL) == LZO_E_OK)
146 unsigned long destlen = MAXSIZE;
147 if(uncompress(dest, &destlen, source, len) == Z_OK)
158 static void receive_packet(node_t *n, vpn_packet_t *packet) {
159 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Received packet of %d bytes from %s (%s)",
160 packet->len, n->name, n->hostname);
165 static bool try_mac(const node_t *n, const vpn_packet_t *inpkt) {
166 unsigned char hmac[EVP_MAX_MD_SIZE];
168 if(!n->indigest || !n->inmaclength || !n->inkey || inpkt->len < sizeof inpkt->seqno + n->inmaclength)
171 HMAC(n->indigest, n->inkey, n->inkeylength, (unsigned char *) &inpkt->seqno, inpkt->len - n->inmaclength, (unsigned char *)hmac, NULL);
173 return !memcmp(hmac, (char *) &inpkt->seqno + inpkt->len - n->inmaclength, n->inmaclength);
176 static void receive_udppacket(node_t *n, vpn_packet_t *inpkt) {
177 vpn_packet_t pkt1, pkt2;
178 vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
180 vpn_packet_t *outpkt = pkt[0];
182 unsigned char hmac[EVP_MAX_MD_SIZE];
186 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Got packet from %s (%s) but he hasn't got our key yet",
187 n->name, n->hostname);
191 /* Check packet length */
193 if(inpkt->len < sizeof(inpkt->seqno) + n->inmaclength) {
194 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Got too short packet from %s (%s)",
195 n->name, n->hostname);
199 /* Check the message authentication code */
201 if(n->indigest && n->inmaclength) {
202 inpkt->len -= n->inmaclength;
203 HMAC(n->indigest, n->inkey, n->inkeylength,
204 (unsigned char *) &inpkt->seqno, inpkt->len, (unsigned char *)hmac, NULL);
206 if(memcmp(hmac, (char *) &inpkt->seqno + inpkt->len, n->inmaclength)) {
207 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Got unauthenticated packet from %s (%s)",
208 n->name, n->hostname);
213 /* Decrypt the packet */
216 outpkt = pkt[nextpkt++];
218 if(!EVP_DecryptInit_ex(&n->inctx, NULL, NULL, NULL, NULL)
219 || !EVP_DecryptUpdate(&n->inctx, (unsigned char *) &outpkt->seqno, &outlen,
220 (unsigned char *) &inpkt->seqno, inpkt->len)
221 || !EVP_DecryptFinal_ex(&n->inctx, (unsigned char *) &outpkt->seqno + outlen, &outpad)) {
222 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Error decrypting packet from %s (%s): %s",
223 n->name, n->hostname, ERR_error_string(ERR_get_error(), NULL));
227 outpkt->len = outlen + outpad;
231 /* Check the sequence number */
233 inpkt->len -= sizeof(inpkt->seqno);
234 inpkt->seqno = ntohl(inpkt->seqno);
236 if(inpkt->seqno != n->received_seqno + 1) {
237 if(inpkt->seqno >= n->received_seqno + sizeof(n->late) * 8) {
238 logger(LOG_WARNING, "Lost %d packets from %s (%s)",
239 inpkt->seqno - n->received_seqno - 1, n->name, n->hostname);
241 memset(n->late, 0, sizeof(n->late));
242 } else if (inpkt->seqno <= n->received_seqno) {
243 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))) {
244 logger(LOG_WARNING, "Got late or replayed packet from %s (%s), seqno %d, last received %d",
245 n->name, n->hostname, inpkt->seqno, n->received_seqno);
249 for(i = n->received_seqno + 1; i < inpkt->seqno; i++)
250 n->late[(i / 8) % sizeof(n->late)] |= 1 << i % 8;
254 n->late[(inpkt->seqno / 8) % sizeof(n->late)] &= ~(1 << inpkt->seqno % 8);
256 if(inpkt->seqno > n->received_seqno)
257 n->received_seqno = inpkt->seqno;
259 if(n->received_seqno > MAX_SEQNO)
262 /* Decompress the packet */
264 length_t origlen = inpkt->len;
266 if(n->incompression) {
267 outpkt = pkt[nextpkt++];
269 if((outpkt->len = uncompress_packet(outpkt->data, inpkt->data, inpkt->len, n->incompression)) < 0) {
270 ifdebug(TRAFFIC) logger(LOG_ERR, "Error while uncompressing packet from %s (%s)",
271 n->name, n->hostname);
277 origlen -= MTU/64 + 20;
283 n->connection->last_ping_time = now;
285 if(!inpkt->data[12] && !inpkt->data[13])
286 mtu_probe_h(n, inpkt, origlen);
288 receive_packet(n, inpkt);
291 void receive_tcppacket(connection_t *c, char *buffer, int len) {
295 if(c->options & OPTION_TCPONLY)
298 outpkt.priority = -1;
299 memcpy(outpkt.data, buffer, len);
301 receive_packet(c->node, &outpkt);
304 static void send_udppacket(node_t *n, vpn_packet_t *origpkt) {
305 vpn_packet_t pkt1, pkt2;
306 vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
307 vpn_packet_t *inpkt = origpkt;
309 vpn_packet_t *outpkt;
312 static int priority = 0;
316 if(!n->status.reachable) {
317 ifdebug(TRAFFIC) logger(LOG_INFO, "Trying to send UDP packet to unreachable node %s (%s)", n->name, n->hostname);
321 /* Make sure we have a valid key */
323 if(!n->status.validkey) {
324 ifdebug(TRAFFIC) logger(LOG_INFO,
325 "No valid key known yet for %s (%s), forwarding via TCP",
326 n->name, n->hostname);
328 if(!n->status.waitingforkey)
331 n->status.waitingforkey = true;
333 send_tcppacket(n->nexthop->connection, origpkt);
338 if(n->options & OPTION_PMTU_DISCOVERY && inpkt->len > n->minmtu && (inpkt->data[12] | inpkt->data[13])) {
339 ifdebug(TRAFFIC) logger(LOG_INFO,
340 "Packet for %s (%s) larger than minimum MTU, forwarding via TCP",
341 n->name, n->hostname);
343 send_tcppacket(n->nexthop->connection, origpkt);
348 origlen = inpkt->len;
349 origpriority = inpkt->priority;
351 /* Compress the packet */
353 if(n->outcompression) {
354 outpkt = pkt[nextpkt++];
356 if((outpkt->len = compress_packet(outpkt->data, inpkt->data, inpkt->len, n->outcompression)) < 0) {
357 ifdebug(TRAFFIC) logger(LOG_ERR, "Error while compressing packet to %s (%s)",
358 n->name, n->hostname);
365 /* Add sequence number */
367 inpkt->seqno = htonl(++(n->sent_seqno));
368 inpkt->len += sizeof(inpkt->seqno);
370 /* Encrypt the packet */
373 outpkt = pkt[nextpkt++];
375 if(!EVP_EncryptInit_ex(&n->outctx, NULL, NULL, NULL, NULL)
376 || !EVP_EncryptUpdate(&n->outctx, (unsigned char *) &outpkt->seqno, &outlen,
377 (unsigned char *) &inpkt->seqno, inpkt->len)
378 || !EVP_EncryptFinal_ex(&n->outctx, (unsigned char *) &outpkt->seqno + outlen, &outpad)) {
379 ifdebug(TRAFFIC) logger(LOG_ERR, "Error while encrypting packet to %s (%s): %s",
380 n->name, n->hostname, ERR_error_string(ERR_get_error(), NULL));
384 outpkt->len = outlen + outpad;
388 /* Add the message authentication code */
390 if(n->outdigest && n->outmaclength) {
391 HMAC(n->outdigest, n->outkey, n->outkeylength, (unsigned char *) &inpkt->seqno,
392 inpkt->len, (unsigned char *) &inpkt->seqno + inpkt->len, NULL);
393 inpkt->len += n->outmaclength;
396 /* Determine which socket we have to use */
398 for(sock = 0; sock < listen_sockets; sock++)
399 if(n->address.sa.sa_family == listen_socket[sock].sa.sa.sa_family)
402 if(sock >= listen_sockets)
403 sock = 0; /* If none is available, just use the first and hope for the best. */
405 /* Send the packet */
407 #if defined(SOL_IP) && defined(IP_TOS)
408 if(priorityinheritance && origpriority != priority
409 && listen_socket[sock].sa.sa.sa_family == AF_INET) {
410 priority = origpriority;
411 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Setting outgoing packet priority to %d", priority);
412 if(setsockopt(listen_socket[sock].udp, SOL_IP, IP_TOS, &priority, sizeof(priority))) /* SO_PRIORITY doesn't seem to work */
413 logger(LOG_ERR, "System call `%s' failed: %s", "setsockopt", strerror(errno));
417 if((sendto(listen_socket[sock].udp, (char *) &inpkt->seqno, inpkt->len, 0, &(n->address.sa), SALEN(n->address.sa))) < 0) {
418 if(errno == EMSGSIZE) {
419 if(n->maxmtu >= origlen)
420 n->maxmtu = origlen - 1;
421 if(n->mtu >= origlen)
422 n->mtu = origlen - 1;
424 logger(LOG_ERR, "Error sending packet to %s (%s): %s", n->name, n->hostname, strerror(errno));
428 origpkt->len = origlen;
432 send a packet to the given vpn ip.
434 void send_packet(const node_t *n, vpn_packet_t *packet) {
439 memcpy(packet->data, mymac.x, ETH_ALEN);
440 write_packet(packet);
444 ifdebug(TRAFFIC) logger(LOG_ERR, "Sending packet of %d bytes to %s (%s)",
445 packet->len, n->name, n->hostname);
447 if(!n->status.reachable) {
448 ifdebug(TRAFFIC) logger(LOG_INFO, "Node %s (%s) is not reachable",
449 n->name, n->hostname);
453 via = (packet->priority == -1 || n->via == myself) ? n->nexthop : n->via;
456 ifdebug(TRAFFIC) logger(LOG_INFO, "Sending packet to %s via %s (%s)",
457 n->name, via->name, n->via->hostname);
459 if(packet->priority == -1 || ((myself->options | via->options) & OPTION_TCPONLY)) {
460 if(!send_tcppacket(via->connection, packet))
461 terminate_connection(via->connection, true);
463 send_udppacket(via, packet);
466 /* Broadcast a packet using the minimum spanning tree */
468 void broadcast_packet(const node_t *from, vpn_packet_t *packet) {
472 ifdebug(TRAFFIC) logger(LOG_INFO, "Broadcasting packet of %d bytes from %s (%s)",
473 packet->len, from->name, from->hostname);
476 send_packet(myself, packet);
478 // In TunnelServer mode, do not forward broadcast packets.
479 // The MST might not be valid and create loops.
484 for(node = connection_tree->head; node; node = node->next) {
487 if(c->status.active && c->status.mst && c != from->nexthop->connection)
488 send_packet(c->node, packet);
492 static node_t *try_harder(const sockaddr_t *from, const vpn_packet_t *pkt) {
497 for(node = edge_weight_tree->head; node; node = node->next) {
500 if(sockaddrcmp_noport(from, &e->address))
506 if(!try_mac(e->to, pkt))
516 void handle_incoming_vpn_data(int sock) {
520 socklen_t fromlen = sizeof(from);
523 pkt.len = recvfrom(sock, (char *) &pkt.seqno, MAXSIZE, 0, &from.sa, &fromlen);
526 if(errno != EAGAIN && errno != EINTR)
527 logger(LOG_ERR, "Receiving packet failed: %s", strerror(errno));
531 sockaddrunmap(&from); /* Some braindead IPv6 implementations do stupid things. */
533 n = lookup_node_udp(&from);
536 n = try_harder(&from, &pkt);
538 update_node_udp(n, &from);
539 else ifdebug(PROTOCOL) {
540 hostname = sockaddr2hostname(&from);
541 logger(LOG_WARNING, "Received UDP packet from unknown source %s", hostname);
549 receive_udppacket(n, &pkt);