Use packet size before decompression to calculate path MTU.
[tinc] / src / net_packet.c
1 /*
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>
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 static char lzo_wrkmem[LZO1X_999_MEM_COMPRESS > LZO1X_1_MEM_COMPRESS ? LZO1X_999_MEM_COMPRESS : LZO1X_1_MEM_COMPRESS];
58
59 static void send_udppacket(node_t *, vpn_packet_t *);
60
61 #define MAX_SEQNO 1073741824
62
63 void send_mtu_probe(node_t *n)
64 {
65         vpn_packet_t packet;
66         int len, i;
67         
68         cp();
69
70         n->mtuprobes++;
71         n->mtuevent = NULL;
72
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);
75                 return;
76         }
77
78         for(i = 0; i < 3; i++) {
79                 if(n->mtuprobes >= 30 || n->minmtu >= n->maxmtu) {
80                         n->mtu = n->minmtu;
81                         ifdebug(TRAFFIC) logger(LOG_INFO, _("Fixing MTU of %s (%s) to %d after %d probes"), n->name, n->hostname, n->mtu, n->mtuprobes);
82                         return;
83                 }
84
85                 len = n->minmtu + 1 + random() % (n->maxmtu - n->minmtu);
86                 if(len < 64)
87                         len = 64;
88                 
89                 memset(packet.data, 0, 14);
90                 RAND_pseudo_bytes(packet.data + 14, len - 14);
91                 packet.len = len;
92                 packet.priority = 0;
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 = 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);
104 }
105
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);
108
109         if(!packet->data[0]) {
110                 packet->data[0] = 1;
111                 send_packet(n, packet);
112         } else {
113                 if(n->minmtu < len)
114                         n->minmtu = 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 bool try_mac(const node_t *n, const vpn_packet_t *inpkt)
171 {
172         unsigned char hmac[EVP_MAX_MD_SIZE];
173
174         if(!n->indigest || !n->inmaclength || !n->inkey || inpkt->len < sizeof inpkt->seqno + n->inmaclength)
175                 return false;
176
177         HMAC(n->indigest, n->inkey, n->inkeylength, (unsigned char *) &inpkt->seqno, inpkt->len - n->inmaclength, (unsigned char *)hmac, NULL);
178
179         return !memcmp(hmac, (char *) &inpkt->seqno + inpkt->len - n->inmaclength, n->inmaclength);
180 }
181
182 static void receive_udppacket(node_t *n, vpn_packet_t *inpkt)
183 {
184         vpn_packet_t pkt1, pkt2;
185         vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
186         int nextpkt = 0;
187         vpn_packet_t *outpkt = pkt[0];
188         int outlen, outpad;
189         unsigned char hmac[EVP_MAX_MD_SIZE];
190         int i;
191
192         cp();
193
194         if(!n->inkey) {
195                 ifdebug(TRAFFIC) logger(LOG_DEBUG, _("Got packet from %s (%s) but he hasn't got our key yet"),
196                                         n->name, n->hostname);
197                 return;
198         }
199
200         /* Check packet length */
201
202         if(inpkt->len < sizeof(inpkt->seqno) + n->inmaclength) {
203                 ifdebug(TRAFFIC) logger(LOG_DEBUG, _("Got too short packet from %s (%s)"),
204                                         n->name, n->hostname);
205                 return;
206         }
207
208         /* Check the message authentication code */
209
210         if(n->indigest && n->inmaclength) {
211                 inpkt->len -= n->inmaclength;
212                 HMAC(n->indigest, n->inkey, n->inkeylength,
213                          (unsigned char *) &inpkt->seqno, inpkt->len, (unsigned char *)hmac, NULL);
214
215                 if(memcmp(hmac, (char *) &inpkt->seqno + inpkt->len, n->inmaclength)) {
216                         ifdebug(TRAFFIC) logger(LOG_DEBUG, _("Got unauthenticated packet from %s (%s)"),
217                                            n->name, n->hostname);
218                         return;
219                 }
220         }
221
222         /* Decrypt the packet */
223
224         if(n->incipher) {
225                 outpkt = pkt[nextpkt++];
226
227                 if(!EVP_DecryptInit_ex(&n->inctx, NULL, NULL, NULL, NULL)
228                                 || !EVP_DecryptUpdate(&n->inctx, (unsigned char *) &outpkt->seqno, &outlen,
229                                         (unsigned char *) &inpkt->seqno, inpkt->len)
230                                 || !EVP_DecryptFinal_ex(&n->inctx, (unsigned char *) &outpkt->seqno + outlen, &outpad)) {
231                         ifdebug(TRAFFIC) logger(LOG_DEBUG, _("Error decrypting packet from %s (%s): %s"),
232                                                 n->name, n->hostname, ERR_error_string(ERR_get_error(), NULL));
233                         return;
234                 }
235                 
236                 outpkt->len = outlen + outpad;
237                 inpkt = outpkt;
238         }
239
240         /* Check the sequence number */
241
242         inpkt->len -= sizeof(inpkt->seqno);
243         inpkt->seqno = ntohl(inpkt->seqno);
244
245         if(inpkt->seqno != n->received_seqno + 1) {
246                 if(inpkt->seqno >= n->received_seqno + sizeof(n->late) * 8) {
247                         logger(LOG_WARNING, _("Lost %d packets from %s (%s)"),
248                                            inpkt->seqno - n->received_seqno - 1, n->name, n->hostname);
249                         
250                         memset(n->late, 0, sizeof(n->late));
251                 } else if (inpkt->seqno <= n->received_seqno) {
252                         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))) {
253                                 logger(LOG_WARNING, _("Got late or replayed packet from %s (%s), seqno %d, last received %d"),
254                                            n->name, n->hostname, inpkt->seqno, n->received_seqno);
255                                 return;
256                         }
257                 } else {
258                         for(i = n->received_seqno + 1; i < inpkt->seqno; i++)
259                                 n->late[(i / 8) % sizeof(n->late)] |= 1 << i % 8;
260                 }
261         }
262         
263         n->late[(inpkt->seqno / 8) % sizeof(n->late)] &= ~(1 << inpkt->seqno % 8);
264
265         if(inpkt->seqno > n->received_seqno)
266                 n->received_seqno = inpkt->seqno;
267                         
268         if(n->received_seqno > MAX_SEQNO)
269                 keyexpires = 0;
270
271         /* Decompress the packet */
272
273         length_t origlen = inpkt->len;
274
275         if(n->incompression) {
276                 outpkt = pkt[nextpkt++];
277
278                 if((outpkt->len = uncompress_packet(outpkt->data, inpkt->data, inpkt->len, n->incompression)) < 0) {
279                         ifdebug(TRAFFIC) logger(LOG_ERR, _("Error while uncompressing packet from %s (%s)"),
280                                                  n->name, n->hostname);
281                         return;
282                 }
283
284                 inpkt = outpkt;
285
286                 origlen -= MTU/64 + 20;
287         }
288
289         inpkt->priority = 0;
290
291         if(n->connection)
292                 n->connection->last_ping_time = now;
293
294         if(!inpkt->data[12] && !inpkt->data[13])
295                 mtu_probe_h(n, inpkt, origlen);
296         else
297                 receive_packet(n, inpkt);
298 }
299
300 void receive_tcppacket(connection_t *c, char *buffer, int len)
301 {
302         vpn_packet_t outpkt;
303
304         cp();
305
306         outpkt.len = len;
307         if(c->options & OPTION_TCPONLY)
308                 outpkt.priority = 0;
309         else
310                 outpkt.priority = -1;
311         memcpy(outpkt.data, buffer, len);
312
313         receive_packet(c->node, &outpkt);
314 }
315
316 static void send_udppacket(node_t *n, vpn_packet_t *origpkt)
317 {
318         vpn_packet_t pkt1, pkt2;
319         vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
320         vpn_packet_t *inpkt = origpkt;
321         int nextpkt = 0;
322         vpn_packet_t *outpkt;
323         int origlen;
324         int outlen, outpad;
325         static int priority = 0;
326         int origpriority;
327         int sock;
328
329         cp();
330
331         /* Make sure we have a valid key */
332
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);
337
338                 if(!n->status.waitingforkey)
339                         send_req_key(n);
340
341                 n->status.waitingforkey = true;
342
343                 send_tcppacket(n->nexthop->connection, origpkt);
344
345                 return;
346         }
347
348         if(n->options & OPTION_PMTU_DISCOVERY && !n->minmtu && (inpkt->data[12] | inpkt->data[13])) {
349                 ifdebug(TRAFFIC) logger(LOG_INFO,
350                                 _("No minimum MTU established yet for %s (%s), forwarding via TCP"),
351                                 n->name, n->hostname);
352
353                 send_tcppacket(n->nexthop->connection, origpkt);
354
355                 return;
356         }
357
358         origlen = inpkt->len;
359         origpriority = inpkt->priority;
360
361         /* Compress the packet */
362
363         if(n->outcompression) {
364                 outpkt = pkt[nextpkt++];
365
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);
369                         return;
370                 }
371
372                 inpkt = outpkt;
373         }
374
375         /* Add sequence number */
376
377         inpkt->seqno = htonl(++(n->sent_seqno));
378         inpkt->len += sizeof(inpkt->seqno);
379
380         /* Encrypt the packet */
381
382         if(n->outcipher) {
383                 outpkt = pkt[nextpkt++];
384
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));
391                         goto end;
392                 }
393
394                 outpkt->len = outlen + outpad;
395                 inpkt = outpkt;
396         }
397
398         /* Add the message authentication code */
399
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;
404         }
405
406         /* Determine which socket we have to use */
407
408         for(sock = 0; sock < listen_sockets; sock++)
409                 if(n->address.sa.sa_family == listen_socket[sock].sa.sa.sa_family)
410                         break;
411
412         if(sock >= listen_sockets)
413                 sock = 0;                               /* If none is available, just use the first and hope for the best. */
414
415         /* Send the packet */
416
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));
424         }
425 #endif
426
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;
433                 } else
434                         logger(LOG_ERR, _("Error sending packet to %s (%s): %s"), n->name, n->hostname, strerror(errno));
435         }
436
437 end:
438         origpkt->len = origlen;
439 }
440
441 /*
442   send a packet to the given vpn ip.
443 */
444 void send_packet(const node_t *n, vpn_packet_t *packet)
445 {
446         node_t *via;
447
448         cp();
449
450         if(n == myself) {
451                 if(overwrite_mac)
452                          memcpy(packet->data, mymac.x, ETH_ALEN);
453                 write_packet(packet);
454                 return;
455         }
456
457         ifdebug(TRAFFIC) logger(LOG_ERR, _("Sending packet of %d bytes to %s (%s)"),
458                            packet->len, n->name, n->hostname);
459
460         if(!n->status.reachable) {
461                 ifdebug(TRAFFIC) logger(LOG_INFO, _("Node %s (%s) is not reachable"),
462                                    n->name, n->hostname);
463                 return;
464         }
465
466         via = (packet->priority == -1 || n->via == myself) ? n->nexthop : n->via;
467
468         if(via != n)
469                 ifdebug(TRAFFIC) logger(LOG_INFO, _("Sending packet to %s via %s (%s)"),
470                            n->name, via->name, n->via->hostname);
471
472         if(packet->priority == -1 || ((myself->options | via->options) & OPTION_TCPONLY)) {
473                 if(!send_tcppacket(via->connection, packet))
474                         terminate_connection(via->connection, true);
475         } else
476                 send_udppacket(via, packet);
477 }
478
479 /* Broadcast a packet using the minimum spanning tree */
480
481 void broadcast_packet(const node_t *from, vpn_packet_t *packet)
482 {
483         avl_node_t *node;
484         connection_t *c;
485
486         cp();
487
488         ifdebug(TRAFFIC) logger(LOG_INFO, _("Broadcasting packet of %d bytes from %s (%s)"),
489                            packet->len, from->name, from->hostname);
490
491         if(from != myself)
492                 send_packet(myself, packet);
493
494         for(node = connection_tree->head; node; node = node->next) {
495                 c = node->data;
496
497                 if(c->status.active && c->status.mst && c != from->nexthop->connection)
498                         send_packet(c->node, packet);
499         }
500 }
501
502 static node_t *try_harder(const sockaddr_t *from, const vpn_packet_t *pkt) {
503         avl_node_t *node;
504         edge_t *e;
505         node_t *n = NULL;
506
507         for(node = edge_weight_tree->head; node; node = node->next) {
508                 e = node->data;
509
510                 if(sockaddrcmp_noport(from, &e->address))
511                         continue;
512
513                 if(!n)
514                         n = e->to;
515
516                 if(!try_mac(e->to, pkt))
517                         continue;
518
519                 n = e->to;
520                 break;
521         }
522
523         return n;
524 }
525
526 void handle_incoming_vpn_data(int sock)
527 {
528         vpn_packet_t pkt;
529         char *hostname;
530         sockaddr_t from;
531         socklen_t fromlen = sizeof(from);
532         node_t *n;
533
534         cp();
535
536         pkt.len = recvfrom(sock, (char *) &pkt.seqno, MAXSIZE, 0, &from.sa, &fromlen);
537
538         if(pkt.len < 0) {
539                 logger(LOG_ERR, _("Receiving packet failed: %s"), strerror(errno));
540                 return;
541         }
542
543         sockaddrunmap(&from);           /* Some braindead IPv6 implementations do stupid things. */
544
545         n = lookup_node_udp(&from);
546
547         if(!n) {
548                 n = try_harder(&from, &pkt);
549                 if(n)
550                         update_node_udp(n, &from);
551                 else ifdebug(PROTOCOL) {
552                         hostname = sockaddr2hostname(&from);
553                         logger(LOG_WARNING, _("Received UDP packet from unknown source %s"), hostname);
554                         free(hostname);
555                         return;
556                 }
557                 else
558                         return;
559         }
560
561         receive_udppacket(n, &pkt);
562 }