Add --disable-lzo configure option
[oweals/tinc.git] / src / net_packet.c
1 /*
2     net_packet.c -- Handles in- and outgoing VPN packets
3     Copyright (C) 1998-2005 Ivo Timmermans,
4                   2000-2010 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 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.
19 */
20
21 #include "system.h"
22
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>
28
29 #include <zlib.h>
30
31 #ifdef HAVE_LZO
32 #include LZO1X_H
33 #endif
34
35 #include "avl_tree.h"
36 #include "conf.h"
37 #include "connection.h"
38 #include "device.h"
39 #include "ethernet.h"
40 #include "event.h"
41 #include "graph.h"
42 #include "list.h"
43 #include "logger.h"
44 #include "net.h"
45 #include "netutl.h"
46 #include "protocol.h"
47 #include "process.h"
48 #include "route.h"
49 #include "utils.h"
50 #include "xalloc.h"
51
52 int keylifetime = 0;
53 int keyexpires = 0;
54 #ifdef HAVE_LZO
55 static char lzo_wrkmem[LZO1X_999_MEM_COMPRESS > LZO1X_1_MEM_COMPRESS ? LZO1X_999_MEM_COMPRESS : LZO1X_1_MEM_COMPRESS];
56 #endif
57
58 static void send_udppacket(node_t *, vpn_packet_t *);
59
60 #define MAX_SEQNO 1073741824
61
62 // mtuprobes == 1..30: initial discovery, send bursts with 1 second interval
63 // mtuprobes ==    31: sleep pinginterval seconds
64 // mtuprobes ==    32: send 1 burst, sleep pingtimeout second
65 // mtuprobes ==    33: no response from other side, restart PMTU discovery process
66
67 void send_mtu_probe(node_t *n) {
68         vpn_packet_t packet;
69         int len, i;
70         int timeout = 1;
71         
72         n->mtuprobes++;
73         n->mtuevent = NULL;
74
75         if(!n->status.reachable || !n->status.validkey) {
76                 ifdebug(TRAFFIC) logger(LOG_INFO, "Trying to send MTU probe to unreachable or rekeying node %s (%s)", n->name, n->hostname);
77                 n->mtuprobes = 0;
78                 return;
79         }
80
81         if(n->mtuprobes > 32) {
82                 ifdebug(TRAFFIC) logger(LOG_INFO, "%s (%s) did not respond to UDP ping, restarting PMTU discovery", n->name, n->hostname);
83                 n->mtuprobes = 1;
84                 n->minmtu = 0;
85                 n->maxmtu = MTU;
86         }
87
88         if(n->mtuprobes >= 10 && !n->minmtu) {
89                 ifdebug(TRAFFIC) logger(LOG_INFO, "No response to MTU probes from %s (%s)", n->name, n->hostname);
90                 n->mtuprobes = 0;
91                 return;
92         }
93
94         if(n->mtuprobes == 30 || (n->mtuprobes < 30 && n->minmtu >= n->maxmtu)) {
95                 if(n->minmtu > n->maxmtu)
96                         n->minmtu = n->maxmtu;
97                 else
98                         n->maxmtu = n->minmtu;
99                 n->mtu = n->minmtu;
100                 ifdebug(TRAFFIC) logger(LOG_INFO, "Fixing MTU of %s (%s) to %d after %d probes", n->name, n->hostname, n->mtu, n->mtuprobes);
101                 n->mtuprobes = 31;
102         }
103
104         if(n->mtuprobes == 31) {
105                 timeout = pinginterval;
106                 goto end;
107         } else if(n->mtuprobes == 32) {
108                 timeout = pingtimeout;
109         }
110
111         for(i = 0; i < 3; i++) {
112                 if(n->maxmtu <= n->minmtu)
113                         len = n->maxmtu;
114                 else
115                         len = n->minmtu + 1 + rand() % (n->maxmtu - n->minmtu);
116
117                 if(len < 64)
118                         len = 64;
119                 
120                 memset(packet.data, 0, 14);
121                 RAND_pseudo_bytes(packet.data + 14, len - 14);
122                 packet.len = len;
123                 packet.priority = 0;
124
125                 ifdebug(TRAFFIC) logger(LOG_INFO, "Sending MTU probe length %d to %s (%s)", len, n->name, n->hostname);
126
127                 send_udppacket(n, &packet);
128         }
129
130 end:
131         n->mtuevent = new_event();
132         n->mtuevent->handler = (event_handler_t)send_mtu_probe;
133         n->mtuevent->data = n;
134         n->mtuevent->time = now + timeout;
135         event_add(n->mtuevent);
136 }
137
138 void mtu_probe_h(node_t *n, vpn_packet_t *packet, length_t len) {
139         ifdebug(TRAFFIC) logger(LOG_INFO, "Got MTU probe length %d from %s (%s)", packet->len, n->name, n->hostname);
140
141         if(!packet->data[0]) {
142                 packet->data[0] = 1;
143                 send_udppacket(n, packet);
144         } else {
145                 if(len > n->maxmtu)
146                         len = n->maxmtu;
147                 if(n->minmtu < len)
148                         n->minmtu = len;
149                 if(n->mtuprobes > 30)
150                         n->mtuprobes = 30;
151         }
152 }
153
154 static length_t compress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level) {
155         if(level == 10) {
156 #ifdef HAVE_LZO
157                 lzo_uint lzolen = MAXSIZE;
158                 lzo1x_1_compress(source, len, dest, &lzolen, lzo_wrkmem);
159                 return lzolen;
160 #else
161                 return -1;
162 #endif
163         } else if(level < 10) {
164                 unsigned long destlen = MAXSIZE;
165                 if(compress2(dest, &destlen, source, len, level) == Z_OK)
166                         return destlen;
167                 else
168                         return -1;
169         } else {
170 #ifdef HAVE_LZO
171                 lzo_uint lzolen = MAXSIZE;
172                 lzo1x_999_compress(source, len, dest, &lzolen, lzo_wrkmem);
173                 return lzolen;
174 #else
175                 return -1;
176 #endif
177         }
178         
179         return -1;
180 }
181
182 static length_t uncompress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level) {
183         if(level > 9) {
184 #ifdef HAVE_LZO
185                 lzo_uint lzolen = MAXSIZE;
186                 if(lzo1x_decompress_safe(source, len, dest, &lzolen, NULL) == LZO_E_OK)
187                         return lzolen;
188                 else
189 #endif
190                         return -1;
191         } else {
192                 unsigned long destlen = MAXSIZE;
193                 if(uncompress(dest, &destlen, source, len) == Z_OK)
194                         return destlen;
195                 else
196                         return -1;
197         }
198         
199         return -1;
200 }
201
202 /* VPN packet I/O */
203
204 static void receive_packet(node_t *n, vpn_packet_t *packet) {
205         ifdebug(TRAFFIC) logger(LOG_DEBUG, "Received packet of %d bytes from %s (%s)",
206                            packet->len, n->name, n->hostname);
207
208         route(n, packet);
209 }
210
211 static bool try_mac(const node_t *n, const vpn_packet_t *inpkt) {
212         unsigned char hmac[EVP_MAX_MD_SIZE];
213
214         if(!n->indigest || !n->inmaclength || !n->inkey || inpkt->len < sizeof inpkt->seqno + n->inmaclength)
215                 return false;
216
217         HMAC(n->indigest, n->inkey, n->inkeylength, (unsigned char *) &inpkt->seqno, inpkt->len - n->inmaclength, (unsigned char *)hmac, NULL);
218
219         return !memcmp(hmac, (char *) &inpkt->seqno + inpkt->len - n->inmaclength, n->inmaclength);
220 }
221
222 static void receive_udppacket(node_t *n, vpn_packet_t *inpkt) {
223         vpn_packet_t pkt1, pkt2;
224         vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
225         int nextpkt = 0;
226         vpn_packet_t *outpkt = pkt[0];
227         int outlen, outpad;
228         unsigned char hmac[EVP_MAX_MD_SIZE];
229         int i;
230
231         if(!n->inkey) {
232                 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Got packet from %s (%s) but he hasn't got our key yet",
233                                         n->name, n->hostname);
234                 return;
235         }
236
237         /* Check packet length */
238
239         if(inpkt->len < sizeof(inpkt->seqno) + n->inmaclength) {
240                 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Got too short packet from %s (%s)",
241                                         n->name, n->hostname);
242                 return;
243         }
244
245         /* Check the message authentication code */
246
247         if(n->indigest && n->inmaclength) {
248                 inpkt->len -= n->inmaclength;
249                 HMAC(n->indigest, n->inkey, n->inkeylength,
250                          (unsigned char *) &inpkt->seqno, inpkt->len, (unsigned char *)hmac, NULL);
251
252                 if(memcmp(hmac, (char *) &inpkt->seqno + inpkt->len, n->inmaclength)) {
253                         ifdebug(TRAFFIC) logger(LOG_DEBUG, "Got unauthenticated packet from %s (%s)",
254                                            n->name, n->hostname);
255                         return;
256                 }
257         }
258
259         /* Decrypt the packet */
260
261         if(n->incipher) {
262                 outpkt = pkt[nextpkt++];
263
264                 if(!EVP_DecryptInit_ex(&n->inctx, NULL, NULL, NULL, NULL)
265                                 || !EVP_DecryptUpdate(&n->inctx, (unsigned char *) &outpkt->seqno, &outlen,
266                                         (unsigned char *) &inpkt->seqno, inpkt->len)
267                                 || !EVP_DecryptFinal_ex(&n->inctx, (unsigned char *) &outpkt->seqno + outlen, &outpad)) {
268                         ifdebug(TRAFFIC) logger(LOG_DEBUG, "Error decrypting packet from %s (%s): %s",
269                                                 n->name, n->hostname, ERR_error_string(ERR_get_error(), NULL));
270                         return;
271                 }
272                 
273                 outpkt->len = outlen + outpad;
274                 inpkt = outpkt;
275         }
276
277         /* Check the sequence number */
278
279         inpkt->len -= sizeof(inpkt->seqno);
280         inpkt->seqno = ntohl(inpkt->seqno);
281
282         if(inpkt->seqno != n->received_seqno + 1) {
283                 if(inpkt->seqno >= n->received_seqno + sizeof(n->late) * 8) {
284                         logger(LOG_WARNING, "Lost %d packets from %s (%s)",
285                                            inpkt->seqno - n->received_seqno - 1, n->name, n->hostname);
286                         
287                         memset(n->late, 0, sizeof(n->late));
288                 } else if (inpkt->seqno <= n->received_seqno) {
289                         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))) {
290                                 logger(LOG_WARNING, "Got late or replayed packet from %s (%s), seqno %d, last received %d",
291                                            n->name, n->hostname, inpkt->seqno, n->received_seqno);
292                                 return;
293                         }
294                 } else {
295                         for(i = n->received_seqno + 1; i < inpkt->seqno; i++)
296                                 n->late[(i / 8) % sizeof(n->late)] |= 1 << i % 8;
297                 }
298         }
299         
300         n->late[(inpkt->seqno / 8) % sizeof(n->late)] &= ~(1 << inpkt->seqno % 8);
301
302         if(inpkt->seqno > n->received_seqno)
303                 n->received_seqno = inpkt->seqno;
304                         
305         if(n->received_seqno > MAX_SEQNO)
306                 keyexpires = 0;
307
308         /* Decompress the packet */
309
310         length_t origlen = inpkt->len;
311
312         if(n->incompression) {
313                 outpkt = pkt[nextpkt++];
314
315                 if((outpkt->len = uncompress_packet(outpkt->data, inpkt->data, inpkt->len, n->incompression)) < 0) {
316                         ifdebug(TRAFFIC) logger(LOG_ERR, "Error while uncompressing packet from %s (%s)",
317                                                  n->name, n->hostname);
318                         return;
319                 }
320
321                 inpkt = outpkt;
322
323                 origlen -= MTU/64 + 20;
324         }
325
326         inpkt->priority = 0;
327
328         if(!inpkt->data[12] && !inpkt->data[13])
329                 mtu_probe_h(n, inpkt, origlen);
330         else
331                 receive_packet(n, inpkt);
332 }
333
334 void receive_tcppacket(connection_t *c, char *buffer, int len) {
335         vpn_packet_t outpkt;
336
337         outpkt.len = len;
338         if(c->options & OPTION_TCPONLY)
339                 outpkt.priority = 0;
340         else
341                 outpkt.priority = -1;
342         memcpy(outpkt.data, buffer, len);
343
344         receive_packet(c->node, &outpkt);
345 }
346
347 static void send_udppacket(node_t *n, vpn_packet_t *origpkt) {
348         vpn_packet_t pkt1, pkt2;
349         vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
350         vpn_packet_t *inpkt = origpkt;
351         int nextpkt = 0;
352         vpn_packet_t *outpkt;
353         int origlen;
354         int outlen, outpad;
355         static int priority = 0;
356         int origpriority;
357         int sock;
358
359         if(!n->status.reachable) {
360                 ifdebug(TRAFFIC) logger(LOG_INFO, "Trying to send UDP packet to unreachable node %s (%s)", n->name, n->hostname);
361                 return;
362         }
363
364         /* Make sure we have a valid key */
365
366         if(!n->status.validkey) {
367                 ifdebug(TRAFFIC) logger(LOG_INFO,
368                                    "No valid key known yet for %s (%s), forwarding via TCP",
369                                    n->name, n->hostname);
370
371                 if(n->last_req_key + 10 < now) {
372                         send_req_key(n);
373                         n->last_req_key = now;
374                 }
375
376                 send_tcppacket(n->nexthop->connection, origpkt);
377
378                 return;
379         }
380
381         if(n->options & OPTION_PMTU_DISCOVERY && inpkt->len > n->minmtu && (inpkt->data[12] | inpkt->data[13])) {
382                 ifdebug(TRAFFIC) logger(LOG_INFO,
383                                 "Packet for %s (%s) larger than minimum MTU, forwarding via %s",
384                                 n->name, n->hostname, n != n->nexthop ? n->nexthop->name : "TCP");
385
386                 if(n != n->nexthop)
387                         send_packet(n->nexthop, origpkt);
388                 else
389                         send_tcppacket(n->nexthop->connection, origpkt);
390
391                 return;
392         }
393
394         origlen = inpkt->len;
395         origpriority = inpkt->priority;
396
397         /* Compress the packet */
398
399         if(n->outcompression) {
400                 outpkt = pkt[nextpkt++];
401
402                 if((outpkt->len = compress_packet(outpkt->data, inpkt->data, inpkt->len, n->outcompression)) < 0) {
403                         ifdebug(TRAFFIC) logger(LOG_ERR, "Error while compressing packet to %s (%s)",
404                                    n->name, n->hostname);
405                         return;
406                 }
407
408                 inpkt = outpkt;
409         }
410
411         /* Add sequence number */
412
413         inpkt->seqno = htonl(++(n->sent_seqno));
414         inpkt->len += sizeof(inpkt->seqno);
415
416         /* Encrypt the packet */
417
418         if(n->outcipher) {
419                 outpkt = pkt[nextpkt++];
420
421                 if(!EVP_EncryptInit_ex(&n->outctx, NULL, NULL, NULL, NULL)
422                                 || !EVP_EncryptUpdate(&n->outctx, (unsigned char *) &outpkt->seqno, &outlen,
423                                         (unsigned char *) &inpkt->seqno, inpkt->len)
424                                 || !EVP_EncryptFinal_ex(&n->outctx, (unsigned char *) &outpkt->seqno + outlen, &outpad)) {
425                         ifdebug(TRAFFIC) logger(LOG_ERR, "Error while encrypting packet to %s (%s): %s",
426                                                 n->name, n->hostname, ERR_error_string(ERR_get_error(), NULL));
427                         goto end;
428                 }
429
430                 outpkt->len = outlen + outpad;
431                 inpkt = outpkt;
432         }
433
434         /* Add the message authentication code */
435
436         if(n->outdigest && n->outmaclength) {
437                 HMAC(n->outdigest, n->outkey, n->outkeylength, (unsigned char *) &inpkt->seqno,
438                          inpkt->len, (unsigned char *) &inpkt->seqno + inpkt->len, NULL);
439                 inpkt->len += n->outmaclength;
440         }
441
442         /* Determine which socket we have to use */
443
444         for(sock = 0; sock < listen_sockets; sock++)
445                 if(n->address.sa.sa_family == listen_socket[sock].sa.sa.sa_family)
446                         break;
447
448         if(sock >= listen_sockets)
449                 sock = 0;                               /* If none is available, just use the first and hope for the best. */
450
451         /* Send the packet */
452
453 #if defined(SOL_IP) && defined(IP_TOS)
454         if(priorityinheritance && origpriority != priority
455            && listen_socket[sock].sa.sa.sa_family == AF_INET) {
456                 priority = origpriority;
457                 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Setting outgoing packet priority to %d", priority);
458                 if(setsockopt(listen_socket[sock].udp, SOL_IP, IP_TOS, &priority, sizeof(priority)))    /* SO_PRIORITY doesn't seem to work */
459                         logger(LOG_ERR, "System call `%s' failed: %s", "setsockopt", strerror(errno));
460         }
461 #endif
462
463         if(sendto(listen_socket[sock].udp, (char *) &inpkt->seqno, inpkt->len, 0, &(n->address.sa), SALEN(n->address.sa)) < 0 && !sockwouldblock(sockerrno)) {
464                 if(sockmsgsize(sockerrno)) {
465                         if(n->maxmtu >= origlen)
466                                 n->maxmtu = origlen - 1;
467                         if(n->mtu >= origlen)
468                                 n->mtu = origlen - 1;
469                 } else
470                         logger(LOG_ERR, "Error sending packet to %s (%s): %s", n->name, n->hostname, sockstrerror(sockerrno));
471         }
472
473 end:
474         origpkt->len = origlen;
475 }
476
477 /*
478   send a packet to the given vpn ip.
479 */
480 void send_packet(const node_t *n, vpn_packet_t *packet) {
481         node_t *via;
482
483         if(n == myself) {
484                 if(overwrite_mac)
485                          memcpy(packet->data, mymac.x, ETH_ALEN);
486                 write_packet(packet);
487                 return;
488         }
489
490         ifdebug(TRAFFIC) logger(LOG_ERR, "Sending packet of %d bytes to %s (%s)",
491                            packet->len, n->name, n->hostname);
492
493         if(!n->status.reachable) {
494                 ifdebug(TRAFFIC) logger(LOG_INFO, "Node %s (%s) is not reachable",
495                                    n->name, n->hostname);
496                 return;
497         }
498
499         via = (packet->priority == -1 || n->via == myself) ? n->nexthop : n->via;
500
501         if(via != n)
502                 ifdebug(TRAFFIC) logger(LOG_INFO, "Sending packet to %s via %s (%s)",
503                            n->name, via->name, n->via->hostname);
504
505         if(packet->priority == -1 || ((myself->options | via->options) & OPTION_TCPONLY)) {
506                 if(!send_tcppacket(via->connection, packet))
507                         terminate_connection(via->connection, true);
508         } else
509                 send_udppacket(via, packet);
510 }
511
512 /* Broadcast a packet using the minimum spanning tree */
513
514 void broadcast_packet(const node_t *from, vpn_packet_t *packet) {
515         avl_node_t *node;
516         connection_t *c;
517
518         ifdebug(TRAFFIC) logger(LOG_INFO, "Broadcasting packet of %d bytes from %s (%s)",
519                            packet->len, from->name, from->hostname);
520
521         if(from != myself) {
522                 send_packet(myself, packet);
523
524                 // In TunnelServer mode, do not forward broadcast packets.
525                 // The MST might not be valid and create loops.
526                 if(tunnelserver)
527                         return;
528         }
529
530         for(node = connection_tree->head; node; node = node->next) {
531                 c = node->data;
532
533                 if(c->status.active && c->status.mst && c != from->nexthop->connection)
534                         send_packet(c->node, packet);
535         }
536 }
537
538 static node_t *try_harder(const sockaddr_t *from, const vpn_packet_t *pkt) {
539         avl_node_t *node;
540         edge_t *e;
541         node_t *n = NULL;
542         static time_t last_hard_try = 0;
543
544         for(node = edge_weight_tree->head; node; node = node->next) {
545                 e = node->data;
546
547                 if(sockaddrcmp_noport(from, &e->address)) {
548                         if(last_hard_try == now)
549                                 continue;
550                         last_hard_try = now;
551                 }
552
553                 if(!n)
554                         n = e->to;
555
556                 if(!try_mac(e->to, pkt))
557                         continue;
558
559                 n = e->to;
560                 break;
561         }
562
563         return n;
564 }
565
566 void handle_incoming_vpn_data(int sock) {
567         vpn_packet_t pkt;
568         char *hostname;
569         sockaddr_t from;
570         socklen_t fromlen = sizeof(from);
571         node_t *n;
572
573         pkt.len = recvfrom(sock, (char *) &pkt.seqno, MAXSIZE, 0, &from.sa, &fromlen);
574
575         if(pkt.len < 0) {
576                 if(!sockwouldblock(sockerrno))
577                         logger(LOG_ERR, "Receiving packet failed: %s", sockstrerror(sockerrno));
578                 return;
579         }
580
581         sockaddrunmap(&from);           /* Some braindead IPv6 implementations do stupid things. */
582
583         n = lookup_node_udp(&from);
584
585         if(!n) {
586                 n = try_harder(&from, &pkt);
587                 if(n)
588                         update_node_udp(n, &from);
589                 else ifdebug(PROTOCOL) {
590                         hostname = sockaddr2hostname(&from);
591                         logger(LOG_WARNING, "Received UDP packet from unknown source %s", hostname);
592                         free(hostname);
593                         return;
594                 }
595                 else
596                         return;
597         }
598
599         receive_udppacket(n, &pkt);
600 }