2 net_packet.c -- Handles in- and outgoing VPN packets
3 Copyright (C) 1998-2005 Ivo Timmermans,
4 2000-2006 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"
51 #define EMSGSIZE WSAEMSGSIZE
55 EVP_CIPHER_CTX packet_ctx;
56 static char lzo_wrkmem[LZO1X_999_MEM_COMPRESS > LZO1X_1_MEM_COMPRESS ? LZO1X_999_MEM_COMPRESS : LZO1X_1_MEM_COMPRESS];
58 static void send_udppacket(node_t *, vpn_packet_t *);
60 #define MAX_SEQNO 1073741824
62 static void send_mtu_probe_handler(int fd, short events, void *data) {
71 if(n->mtuprobes >= 10 && !n->minmtu) {
72 ifdebug(TRAFFIC) logger(LOG_INFO, _("No response to MTU probes from %s (%s)"), n->name, n->hostname);
76 for(i = 0; i < 3; i++) {
77 if(n->mtuprobes >= 30 || n->minmtu >= n->maxmtu) {
79 ifdebug(TRAFFIC) logger(LOG_INFO, _("Fixing MTU of %s (%s) to %d after %d probes"), n->name, n->hostname, n->mtu, n->mtuprobes);
83 len = n->minmtu + 1 + random() % (n->maxmtu - n->minmtu);
87 memset(packet.data, 0, 14);
88 RAND_pseudo_bytes(packet.data + 14, len - 14);
91 ifdebug(TRAFFIC) logger(LOG_INFO, _("Sending MTU probe length %d to %s (%s)"), len, n->name, n->hostname);
93 send_udppacket(n, &packet);
96 event_add(&n->mtuevent, &(struct timeval){1, 0});
99 void send_mtu_probe(node_t *n) {
100 if(!timeout_initialized(&n->mtuevent))
101 timeout_set(&n->mtuevent, send_mtu_probe_handler, n);
102 send_mtu_probe_handler(0, 0, n);
105 void mtu_probe_h(node_t *n, vpn_packet_t *packet) {
106 ifdebug(TRAFFIC) logger(LOG_INFO, _("Got MTU probe length %d from %s (%s)"), packet->len, n->name, n->hostname);
108 if(!packet->data[0]) {
110 send_packet(n, packet);
112 if(n->minmtu < packet->len)
113 n->minmtu = packet->len;
117 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)
141 lzo_uint lzolen = MAXSIZE;
142 if(lzo1x_decompress_safe(source, len, dest, &lzolen, NULL) == LZO_E_OK)
147 unsigned long destlen = MAXSIZE;
148 if(uncompress(dest, &destlen, source, len) == Z_OK)
159 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 void receive_udppacket(node_t *n, vpn_packet_t *inpkt)
171 vpn_packet_t pkt1, pkt2;
172 vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
174 vpn_packet_t *outpkt = pkt[0];
176 unsigned char hmac[EVP_MAX_MD_SIZE];
181 /* Check packet length */
183 if(inpkt->len < sizeof(inpkt->seqno) + myself->maclength) {
184 ifdebug(TRAFFIC) logger(LOG_DEBUG, _("Got too short packet from %s (%s)"),
185 n->name, n->hostname);
189 /* Check the message authentication code */
191 if(myself->digest && myself->maclength) {
192 inpkt->len -= myself->maclength;
193 HMAC(myself->digest, myself->key, myself->keylength,
194 (unsigned char *) &inpkt->seqno, inpkt->len, (unsigned char *)hmac, NULL);
196 if(memcmp(hmac, (char *) &inpkt->seqno + inpkt->len, myself->maclength)) {
197 ifdebug(TRAFFIC) logger(LOG_DEBUG, _("Got unauthenticated packet from %s (%s)"),
198 n->name, n->hostname);
203 /* Decrypt the packet */
206 outpkt = pkt[nextpkt++];
208 if(!EVP_DecryptInit_ex(&packet_ctx, NULL, NULL, NULL, NULL)
209 || !EVP_DecryptUpdate(&packet_ctx, (unsigned char *) &outpkt->seqno, &outlen,
210 (unsigned char *) &inpkt->seqno, inpkt->len)
211 || !EVP_DecryptFinal_ex(&packet_ctx, (unsigned char *) &outpkt->seqno + outlen, &outpad)) {
212 ifdebug(TRAFFIC) logger(LOG_DEBUG, _("Error decrypting packet from %s (%s): %s"),
213 n->name, n->hostname, ERR_error_string(ERR_get_error(), NULL));
217 outpkt->len = outlen + outpad;
221 /* Check the sequence number */
223 inpkt->len -= sizeof(inpkt->seqno);
224 inpkt->seqno = ntohl(inpkt->seqno);
226 if(inpkt->seqno != n->received_seqno + 1) {
227 if(inpkt->seqno >= n->received_seqno + sizeof(n->late) * 8) {
228 logger(LOG_WARNING, _("Lost %d packets from %s (%s)"),
229 inpkt->seqno - n->received_seqno - 1, n->name, n->hostname);
231 memset(n->late, 0, sizeof(n->late));
232 } else if (inpkt->seqno <= n->received_seqno) {
233 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))) {
234 logger(LOG_WARNING, _("Got late or replayed packet from %s (%s), seqno %d, last received %d"),
235 n->name, n->hostname, inpkt->seqno, n->received_seqno);
239 for(i = n->received_seqno + 1; i < inpkt->seqno; i++)
240 n->late[(i / 8) % sizeof(n->late)] |= 1 << i % 8;
244 n->late[(inpkt->seqno / 8) % sizeof(n->late)] &= ~(1 << inpkt->seqno % 8);
246 if(inpkt->seqno > n->received_seqno)
247 n->received_seqno = inpkt->seqno;
249 if(n->received_seqno > MAX_SEQNO)
252 /* Decompress the packet */
254 if(myself->compression) {
255 outpkt = pkt[nextpkt++];
257 if((outpkt->len = uncompress_packet(outpkt->data, inpkt->data, inpkt->len, myself->compression)) < 0) {
258 ifdebug(TRAFFIC) logger(LOG_ERR, _("Error while uncompressing packet from %s (%s)"),
259 n->name, n->hostname);
267 n->connection->last_ping_time = now;
269 if(!inpkt->data[12] && !inpkt->data[13])
270 mtu_probe_h(n, inpkt);
272 receive_packet(n, inpkt);
275 void receive_tcppacket(connection_t *c, char *buffer, int len)
282 memcpy(outpkt.data, buffer, len);
284 receive_packet(c->node, &outpkt);
287 static void send_udppacket(node_t *n, vpn_packet_t *origpkt)
289 vpn_packet_t pkt1, pkt2;
290 vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
291 vpn_packet_t *inpkt = origpkt;
293 vpn_packet_t *outpkt;
297 static int priority = 0;
303 /* Make sure we have a valid key */
305 if(!n->status.validkey) {
306 ifdebug(TRAFFIC) logger(LOG_INFO,
307 _("No valid key known yet for %s (%s), queueing packet"),
308 n->name, n->hostname);
310 /* Since packet is on the stack of handle_tap_input(), we have to make a copy of it first. */
312 *(copy = xmalloc(sizeof(*copy))) = *inpkt;
314 list_insert_tail(n->queue, copy);
316 if(n->queue->count > MAXQUEUELENGTH)
317 list_delete_head(n->queue);
319 if(!n->status.waitingforkey)
320 send_req_key(n->nexthop->connection, myself, n);
322 n->status.waitingforkey = true;
327 origlen = inpkt->len;
328 origpriority = inpkt->priority;
330 /* Compress the packet */
333 outpkt = pkt[nextpkt++];
335 if((outpkt->len = compress_packet(outpkt->data, inpkt->data, inpkt->len, n->compression)) < 0) {
336 ifdebug(TRAFFIC) logger(LOG_ERR, _("Error while compressing packet to %s (%s)"),
337 n->name, n->hostname);
344 /* Add sequence number */
346 inpkt->seqno = htonl(++(n->sent_seqno));
347 inpkt->len += sizeof(inpkt->seqno);
349 /* Encrypt the packet */
352 outpkt = pkt[nextpkt++];
354 if(!EVP_EncryptInit_ex(&n->packet_ctx, NULL, NULL, NULL, NULL)
355 || !EVP_EncryptUpdate(&n->packet_ctx, (unsigned char *) &outpkt->seqno, &outlen,
356 (unsigned char *) &inpkt->seqno, inpkt->len)
357 || !EVP_EncryptFinal_ex(&n->packet_ctx, (unsigned char *) &outpkt->seqno + outlen, &outpad)) {
358 ifdebug(TRAFFIC) logger(LOG_ERR, _("Error while encrypting packet to %s (%s): %s"),
359 n->name, n->hostname, ERR_error_string(ERR_get_error(), NULL));
363 outpkt->len = outlen + outpad;
367 /* Add the message authentication code */
369 if(n->digest && n->maclength) {
370 HMAC(n->digest, n->key, n->keylength, (unsigned char *) &inpkt->seqno,
371 inpkt->len, (unsigned char *) &inpkt->seqno + inpkt->len, NULL);
372 inpkt->len += n->maclength;
375 /* Determine which socket we have to use */
377 for(sock = 0; sock < listen_sockets; sock++)
378 if(n->address.sa.sa_family == listen_socket[sock].sa.sa.sa_family)
381 if(sock >= listen_sockets)
382 sock = 0; /* If none is available, just use the first and hope for the best. */
384 /* Send the packet */
386 #if defined(SOL_IP) && defined(IP_TOS)
387 if(priorityinheritance && origpriority != priority
388 && listen_socket[sock].sa.sa.sa_family == AF_INET) {
389 priority = origpriority;
390 ifdebug(TRAFFIC) logger(LOG_DEBUG, _("Setting outgoing packet priority to %d"), priority);
391 if(setsockopt(listen_socket[sock].udp, SOL_IP, IP_TOS, &priority, sizeof(priority))) /* SO_PRIORITY doesn't seem to work */
392 logger(LOG_ERR, _("System call `%s' failed: %s"), "setsockopt", strerror(errno));
396 if((sendto(listen_socket[sock].udp, (char *) &inpkt->seqno, inpkt->len, 0, &(n->address.sa), SALEN(n->address.sa))) < 0) {
397 if(errno == EMSGSIZE) {
398 if(n->maxmtu >= origlen)
399 n->maxmtu = origlen - 1;
400 if(n->mtu >= origlen)
401 n->mtu = origlen - 1;
403 logger(LOG_ERR, _("Error sending packet to %s (%s): %s"), n->name, n->hostname, strerror(errno));
407 origpkt->len = origlen;
411 send a packet to the given vpn ip.
413 void send_packet(const node_t *n, vpn_packet_t *packet)
421 memcpy(packet->data, mymac.x, ETH_ALEN);
422 write_packet(packet);
426 ifdebug(TRAFFIC) logger(LOG_ERR, _("Sending packet of %d bytes to %s (%s)"),
427 packet->len, n->name, n->hostname);
429 if(!n->status.reachable) {
430 ifdebug(TRAFFIC) logger(LOG_INFO, _("Node %s (%s) is not reachable"),
431 n->name, n->hostname);
435 via = (n->via == myself) ? n->nexthop : n->via;
438 ifdebug(TRAFFIC) logger(LOG_ERR, _("Sending packet to %s via %s (%s)"),
439 n->name, via->name, n->via->hostname);
441 if((myself->options | via->options) & OPTION_TCPONLY) {
442 if(!send_tcppacket(via->connection, packet))
443 terminate_connection(via->connection, true);
445 send_udppacket(via, packet);
448 /* Broadcast a packet using the minimum spanning tree */
450 void broadcast_packet(const node_t *from, vpn_packet_t *packet)
457 ifdebug(TRAFFIC) logger(LOG_INFO, _("Broadcasting packet of %d bytes from %s (%s)"),
458 packet->len, from->name, from->hostname);
461 send_packet(myself, packet);
463 for(node = connection_tree->head; node; node = node->next) {
466 if(c->status.active && c->status.mst && c != from->nexthop->connection)
467 send_packet(c->node, packet);
471 void flush_queue(node_t *n)
473 list_node_t *node, *next;
477 ifdebug(TRAFFIC) logger(LOG_INFO, _("Flushing queue for %s (%s)"), n->name, n->hostname);
479 for(node = n->queue->head; node; node = next) {
481 send_udppacket(n, node->data);
482 list_delete_node(n->queue, node);
486 void handle_incoming_vpn_data(int sock, short events, void *data)
491 socklen_t fromlen = sizeof(from);
496 pkt.len = recvfrom(sock, (char *) &pkt.seqno, MAXSIZE, 0, &from.sa, &fromlen);
499 logger(LOG_ERR, _("Receiving packet failed: %s"), strerror(errno));
503 sockaddrunmap(&from); /* Some braindead IPv6 implementations do stupid things. */
505 n = lookup_node_udp(&from);
508 hostname = sockaddr2hostname(&from);
509 logger(LOG_WARNING, _("Received UDP packet from unknown source %s"),
515 receive_udppacket(n, &pkt);
518 void handle_device_data(int sock, short events, void *data)
522 if(read_packet(&packet))
523 route(myself, &packet);