Marking potential late packets was in the wrong place.
[tinc] / src / net_packet.c
1 /*
2     net_packet.c -- Handles in- and outgoing VPN packets
3     Copyright (C) 1998-2004 Ivo Timmermans <ivo@tinc-vpn.org>,
4                   2000-2004 Guus Sliepen <guus@tinc-vpn.org>
5
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.
10
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.
15
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.
19
20     $Id$
21 */
22
23 #include "system.h"
24
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>
30
31 #include <zlib.h>
32 #include <lzo1x.h>
33
34 #include "avl_tree.h"
35 #include "conf.h"
36 #include "connection.h"
37 #include "device.h"
38 #include "ethernet.h"
39 #include "event.h"
40 #include "graph.h"
41 #include "list.h"
42 #include "logger.h"
43 #include "net.h"
44 #include "netutl.h"
45 #include "protocol.h"
46 #include "process.h"
47 #include "route.h"
48 #include "utils.h"
49 #include "xalloc.h"
50
51 #ifdef WSAEMSGSIZE
52 #define EMSGSIZE WSAEMSGSIZE
53 #endif
54
55 int keylifetime = 0;
56 int keyexpires = 0;
57 EVP_CIPHER_CTX packet_ctx;
58 static char lzo_wrkmem[LZO1X_999_MEM_COMPRESS > LZO1X_1_MEM_COMPRESS ? LZO1X_999_MEM_COMPRESS : LZO1X_1_MEM_COMPRESS];
59
60 static void send_udppacket(node_t *, vpn_packet_t *);
61
62 #define MAX_SEQNO 1073741824
63
64 void send_mtu_probe(node_t *n)
65 {
66         vpn_packet_t packet;
67         int len, i;
68         
69         cp();
70
71         n->mtuprobes++;
72         n->mtuevent = NULL;
73
74         if(n->mtuprobes >= 10 && !n->minmtu) {
75                 ifdebug(TRAFFIC) logger(LOG_INFO, _("No response to MTU probes from %s (%s)"), n->name, n->hostname);
76                 return;
77         }
78
79         for(i = 0; i < 3; i++) {
80                 if(n->mtuprobes >= 30 || n->minmtu >= n->maxmtu) {
81                         n->mtu = n->minmtu;
82                         ifdebug(TRAFFIC) logger(LOG_INFO, _("Fixing MTU of %s (%s) to %d after %d probes"), n->name, n->hostname, n->mtu, n->mtuprobes);
83                         return;
84                 }
85
86                 len = n->minmtu + 1 + random() % (n->maxmtu - n->minmtu);
87                 if(len < 64)
88                         len = 64;
89                 
90                 memset(packet.data, 0, 14);
91                 RAND_pseudo_bytes(packet.data + 14, len - 14);
92                 packet.len = len;
93
94                 ifdebug(TRAFFIC) logger(LOG_INFO, _("Sending MTU probe length %d to %s (%s)"), len, n->name, n->hostname);
95
96                 send_udppacket(n, &packet);
97         }
98
99         n->mtuevent = xmalloc(sizeof(*n->mtuevent));
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);
104 }
105
106 void mtu_probe_h(node_t *n, vpn_packet_t *packet) {
107         ifdebug(TRAFFIC) logger(LOG_INFO, _("Got MTU probe length %d from %s (%s)"), packet->len, n->name, n->hostname);
108
109         if(!packet->data[0]) {
110                 packet->data[0] = 1;
111                 send_packet(n, packet);
112         } else {
113                 if(n->minmtu < packet->len)
114                         n->minmtu = packet->len;
115         }
116 }
117
118 static length_t compress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level)
119 {
120         if(level == 10) {
121                 lzo_uint lzolen = MAXSIZE;
122                 lzo1x_1_compress(source, len, dest, &lzolen, lzo_wrkmem);
123                 return lzolen;
124         } else if(level < 10) {
125                 unsigned long destlen = MAXSIZE;
126                 if(compress2(dest, &destlen, source, len, level) == Z_OK)
127                         return destlen;
128                 else
129                         return -1;
130         } else {
131                 lzo_uint lzolen = MAXSIZE;
132                 lzo1x_999_compress(source, len, dest, &lzolen, lzo_wrkmem);
133                 return lzolen;
134         }
135         
136         return -1;
137 }
138
139 static length_t uncompress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level)
140 {
141         if(level > 9) {
142                 lzo_uint lzolen = MAXSIZE;
143                 if(lzo1x_decompress_safe(source, len, dest, &lzolen, NULL) == LZO_E_OK)
144                         return lzolen;
145                 else
146                         return -1;
147         } else {
148                 unsigned long destlen = MAXSIZE;
149                 if(uncompress(dest, &destlen, source, len) == Z_OK)
150                         return destlen;
151                 else
152                         return -1;
153         }
154         
155         return -1;
156 }
157
158 /* VPN packet I/O */
159
160 static void receive_packet(node_t *n, vpn_packet_t *packet)
161 {
162         cp();
163
164         ifdebug(TRAFFIC) logger(LOG_DEBUG, _("Received packet of %d bytes from %s (%s)"),
165                            packet->len, n->name, n->hostname);
166
167         route(n, packet);
168 }
169
170 static void receive_udppacket(node_t *n, vpn_packet_t *inpkt)
171 {
172         vpn_packet_t pkt1, pkt2;
173         vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
174         int nextpkt = 0;
175         vpn_packet_t *outpkt = pkt[0];
176         int outlen, outpad;
177         char hmac[EVP_MAX_MD_SIZE];
178         int i;
179
180         cp();
181
182         /* Check packet length */
183
184         if(inpkt->len < sizeof(inpkt->seqno) + myself->maclength) {
185                 ifdebug(TRAFFIC) logger(LOG_DEBUG, _("Got too short packet from %s (%s)"),
186                                         n->name, n->hostname);
187                 return;
188         }
189
190         /* Check the message authentication code */
191
192         if(myself->digest && myself->maclength) {
193                 inpkt->len -= myself->maclength;
194                 HMAC(myself->digest, myself->key, myself->keylength,
195                          (char *) &inpkt->seqno, inpkt->len, hmac, NULL);
196
197                 if(memcmp(hmac, (char *) &inpkt->seqno + inpkt->len, myself->maclength)) {
198                         ifdebug(TRAFFIC) logger(LOG_DEBUG, _("Got unauthenticated packet from %s (%s)"),
199                                            n->name, n->hostname);
200                         return;
201                 }
202         }
203
204         /* Decrypt the packet */
205
206         if(myself->cipher) {
207                 outpkt = pkt[nextpkt++];
208
209                 if(!EVP_DecryptInit_ex(&packet_ctx, NULL, NULL, NULL, NULL)
210                                 || !EVP_DecryptUpdate(&packet_ctx, (char *) &outpkt->seqno, &outlen,
211                                         (char *) &inpkt->seqno, inpkt->len)
212                                 || !EVP_DecryptFinal_ex(&packet_ctx, (char *) &outpkt->seqno + outlen, &outpad)) {
213                         ifdebug(TRAFFIC) logger(LOG_DEBUG, _("Error decrypting packet from %s (%s): %s"),
214                                                 n->name, n->hostname, ERR_error_string(ERR_get_error(), NULL));
215                         return;
216                 }
217                 
218                 outpkt->len = outlen + outpad;
219                 inpkt = outpkt;
220         }
221
222         /* Check the sequence number */
223
224         inpkt->len -= sizeof(inpkt->seqno);
225         inpkt->seqno = ntohl(inpkt->seqno);
226
227         if(inpkt->seqno != n->received_seqno + 1) {
228                 if(inpkt->seqno >= n->received_seqno + sizeof(n->late) * 8) {
229                         logger(LOG_WARNING, _("Lost %d packets from %s (%s)"),
230                                            inpkt->seqno - n->received_seqno - 1, n->name, n->hostname);
231                         
232                         memset(n->late, 0, sizeof(n->late));
233                 } else if (inpkt->seqno <= n->received_seqno) {
234                         if(inpkt->seqno <= n->received_seqno - sizeof(n->late) * 8 || !(n->late[(inpkt->seqno / 8) % sizeof(n->late)] & (1 << inpkt->seqno % 8))) {
235                                 logger(LOG_WARNING, _("Got late or replayed packet from %s (%s), seqno %d, last received %d"),
236                                            n->name, n->hostname, inpkt->seqno, n->received_seqno);
237                                 return;
238                         }
239                 } else {
240                         for(i = n->received_seqno + 1; i < inpkt->seqno; i++)
241                                 n->late[(inpkt->seqno / 8) % sizeof(n->late)] |= 1 << i % 8;
242                 }
243         }
244         
245         n->received_seqno = inpkt->seqno;
246         n->late[(n->received_seqno / 8) % sizeof(n->late)] &= ~(1 << n->received_seqno % 8);
247                         
248         if(n->received_seqno > MAX_SEQNO)
249                 keyexpires = 0;
250
251         /* Decompress the packet */
252
253         if(myself->compression) {
254                 outpkt = pkt[nextpkt++];
255
256                 if((outpkt->len = uncompress_packet(outpkt->data, inpkt->data, inpkt->len, myself->compression)) < 0) {
257                         ifdebug(TRAFFIC) logger(LOG_ERR, _("Error while uncompressing packet from %s (%s)"),
258                                                  n->name, n->hostname);
259                         return;
260                 }
261
262                 inpkt = outpkt;
263         }
264
265         if(n->connection)
266                 n->connection->last_ping_time = now;
267
268         if(!inpkt->data[12] && !inpkt->data[13])
269                 mtu_probe_h(n, inpkt);
270         else
271                 receive_packet(n, inpkt);
272 }
273
274 void receive_tcppacket(connection_t *c, char *buffer, int len)
275 {
276         vpn_packet_t outpkt;
277
278         cp();
279
280         outpkt.len = len;
281         memcpy(outpkt.data, buffer, len);
282
283         receive_packet(c->node, &outpkt);
284 }
285
286 static void send_udppacket(node_t *n, vpn_packet_t *inpkt)
287 {
288         vpn_packet_t pkt1, pkt2;
289         vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
290         int nextpkt = 0;
291         vpn_packet_t *outpkt;
292         int origlen;
293         int outlen, outpad;
294         vpn_packet_t *copy;
295         static int priority = 0;
296         int origpriority;
297         int sock;
298
299         cp();
300
301         /* Make sure we have a valid key */
302
303         if(!n->status.validkey) {
304                 ifdebug(TRAFFIC) logger(LOG_INFO,
305                                    _("No valid key known yet for %s (%s), queueing packet"),
306                                    n->name, n->hostname);
307
308                 /* Since packet is on the stack of handle_tap_input(), we have to make a copy of it first. */
309
310                 *(copy = xmalloc(sizeof(*copy))) = *inpkt;
311
312                 list_insert_tail(n->queue, copy);
313
314                 if(n->queue->count > MAXQUEUELENGTH)
315                         list_delete_head(n->queue);
316
317                 if(!n->status.waitingforkey)
318                         send_req_key(n->nexthop->connection, myself, n);
319
320                 n->status.waitingforkey = true;
321
322                 return;
323         }
324
325         origlen = inpkt->len;
326         origpriority = inpkt->priority;
327
328         /* Compress the packet */
329
330         if(n->compression) {
331                 outpkt = pkt[nextpkt++];
332
333                 if((outpkt->len = compress_packet(outpkt->data, inpkt->data, inpkt->len, n->compression)) < 0) {
334                         ifdebug(TRAFFIC) logger(LOG_ERR, _("Error while compressing packet to %s (%s)"),
335                                    n->name, n->hostname);
336                         return;
337                 }
338
339                 inpkt = outpkt;
340         }
341
342         /* Add sequence number */
343
344         inpkt->seqno = htonl(++(n->sent_seqno));
345         inpkt->len += sizeof(inpkt->seqno);
346
347         /* Encrypt the packet */
348
349         if(n->cipher) {
350                 outpkt = pkt[nextpkt++];
351
352                 if(!EVP_EncryptInit_ex(&n->packet_ctx, NULL, NULL, NULL, NULL)
353                                 || !EVP_EncryptUpdate(&n->packet_ctx, (char *) &outpkt->seqno, &outlen,
354                                         (char *) &inpkt->seqno, inpkt->len)
355                                 || !EVP_EncryptFinal_ex(&n->packet_ctx, (char *) &outpkt->seqno + outlen, &outpad)) {
356                         ifdebug(TRAFFIC) logger(LOG_ERR, _("Error while encrypting packet to %s (%s): %s"),
357                                                 n->name, n->hostname, ERR_error_string(ERR_get_error(), NULL));
358                         goto end;
359                 }
360
361                 outpkt->len = outlen + outpad;
362                 inpkt = outpkt;
363         }
364
365         /* Add the message authentication code */
366
367         if(n->digest && n->maclength) {
368                 HMAC(n->digest, n->key, n->keylength, (char *) &inpkt->seqno,
369                          inpkt->len, (char *) &inpkt->seqno + inpkt->len, &outlen);
370                 inpkt->len += n->maclength;
371         }
372
373         /* Determine which socket we have to use */
374
375         for(sock = 0; sock < listen_sockets; sock++)
376                 if(n->address.sa.sa_family == listen_socket[sock].sa.sa.sa_family)
377                         break;
378
379         if(sock >= listen_sockets)
380                 sock = 0;                               /* If none is available, just use the first and hope for the best. */
381
382         /* Send the packet */
383
384 #if defined(SOL_IP) && defined(IP_TOS)
385         if(priorityinheritance && origpriority != priority
386            && listen_socket[sock].sa.sa.sa_family == AF_INET) {
387                 priority = origpriority;
388                 ifdebug(TRAFFIC) logger(LOG_DEBUG, _("Setting outgoing packet priority to %d"), priority);
389                 if(setsockopt(listen_socket[sock].udp, SOL_IP, IP_TOS, &priority, sizeof(priority)))    /* SO_PRIORITY doesn't seem to work */
390                         logger(LOG_ERR, _("System call `%s' failed: %s"), "setsockopt", strerror(errno));
391         }
392 #endif
393
394         if((sendto(listen_socket[sock].udp, (char *) &inpkt->seqno, inpkt->len, 0, &(n->address.sa), SALEN(n->address.sa))) < 0) {
395                 if(errno == EMSGSIZE) {
396                         if(n->maxmtu >= origlen)
397                                 n->maxmtu = origlen - 1;
398                         if(n->mtu >= origlen)
399                                 n->mtu = origlen - 1;
400                 } else
401                         logger(LOG_ERR, _("Error sending packet to %s (%s): %s"), n->name, n->hostname, strerror(errno));
402         }
403
404 end:
405         inpkt->len = origlen;
406 }
407
408 /*
409   send a packet to the given vpn ip.
410 */
411 void send_packet(const node_t *n, vpn_packet_t *packet)
412 {
413         node_t *via;
414
415         cp();
416
417         if(n == myself) {
418                 if(overwrite_mac)
419                          memcpy(packet->data, mymac.x, ETH_ALEN);
420                 write_packet(packet);
421                 return;
422         }
423
424         ifdebug(TRAFFIC) logger(LOG_ERR, _("Sending packet of %d bytes to %s (%s)"),
425                            packet->len, n->name, n->hostname);
426
427         if(!n->status.reachable) {
428                 ifdebug(TRAFFIC) logger(LOG_INFO, _("Node %s (%s) is not reachable"),
429                                    n->name, n->hostname);
430                 return;
431         }
432
433         via = (n->via == myself) ? n->nexthop : n->via;
434
435         if(via != n)
436                 ifdebug(TRAFFIC) logger(LOG_ERR, _("Sending packet to %s via %s (%s)"),
437                            n->name, via->name, n->via->hostname);
438
439         if((myself->options | via->options) & OPTION_TCPONLY) {
440                 if(!send_tcppacket(via->connection, packet))
441                         terminate_connection(via->connection, true);
442         } else
443                 send_udppacket(via, packet);
444 }
445
446 /* Broadcast a packet using the minimum spanning tree */
447
448 void broadcast_packet(const node_t *from, vpn_packet_t *packet)
449 {
450         avl_node_t *node;
451         connection_t *c;
452
453         cp();
454
455         ifdebug(TRAFFIC) logger(LOG_INFO, _("Broadcasting packet of %d bytes from %s (%s)"),
456                            packet->len, from->name, from->hostname);
457
458         for(node = connection_tree->head; node; node = node->next) {
459                 c = node->data;
460
461                 if(c->status.active && c->status.mst && c != from->nexthop->connection)
462                         send_packet(c->node, packet);
463         }
464 }
465
466 void flush_queue(node_t *n)
467 {
468         list_node_t *node, *next;
469
470         cp();
471
472         ifdebug(TRAFFIC) logger(LOG_INFO, _("Flushing queue for %s (%s)"), n->name, n->hostname);
473
474         for(node = n->queue->head; node; node = next) {
475                 next = node->next;
476                 send_udppacket(n, node->data);
477                 list_delete_node(n->queue, node);
478         }
479 }
480
481 void handle_incoming_vpn_data(int sock)
482 {
483         vpn_packet_t pkt;
484         char *hostname;
485         sockaddr_t from;
486         socklen_t fromlen = sizeof(from);
487         node_t *n;
488
489         cp();
490
491         pkt.len = recvfrom(sock, (char *) &pkt.seqno, MAXSIZE, 0, &from.sa, &fromlen);
492
493         if(pkt.len < 0) {
494                 logger(LOG_ERR, _("Receiving packet failed: %s"), strerror(errno));
495                 return;
496         }
497
498         sockaddrunmap(&from);           /* Some braindead IPv6 implementations do stupid things. */
499
500         n = lookup_node_udp(&from);
501
502         if(!n) {
503                 hostname = sockaddr2hostname(&from);
504                 logger(LOG_WARNING, _("Received UDP packet from unknown source %s"),
505                            hostname);
506                 free(hostname);
507                 return;
508         }
509
510         receive_udppacket(n, &pkt);
511 }