Merge branch 'master' into 1.1
[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-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 #ifdef HAVE_ZLIB
30 #include <zlib.h>
31 #endif
32
33 #ifdef HAVE_LZO
34 #include LZO1X_H
35 #endif
36
37 #include "splay_tree.h"
38 #include "cipher.h"
39 #include "conf.h"
40 #include "connection.h"
41 #include "crypto.h"
42 #include "digest.h"
43 #include "device.h"
44 #include "ethernet.h"
45 #include "graph.h"
46 #include "list.h"
47 #include "logger.h"
48 #include "net.h"
49 #include "netutl.h"
50 #include "protocol.h"
51 #include "process.h"
52 #include "route.h"
53 #include "utils.h"
54 #include "xalloc.h"
55
56 int keylifetime = 0;
57 int keyexpires = 0;
58 #ifdef HAVE_LZO
59 static char lzo_wrkmem[LZO1X_999_MEM_COMPRESS > LZO1X_1_MEM_COMPRESS ? LZO1X_999_MEM_COMPRESS : LZO1X_1_MEM_COMPRESS];
60 #endif
61
62 static void send_udppacket(node_t *, vpn_packet_t *);
63
64 #define MAX_SEQNO 1073741824
65
66 // mtuprobes == 1..30: initial discovery, send bursts with 1 second interval
67 // mtuprobes ==    31: sleep pinginterval seconds
68 // mtuprobes ==    32: send 1 burst, sleep pingtimeout second
69 // mtuprobes ==    33: no response from other side, restart PMTU discovery process
70
71 static void send_mtu_probe_handler(int fd, short events, void *data) {
72         node_t *n = data;
73         vpn_packet_t packet;
74         int len, i;
75         int timeout = 1;
76         
77         n->mtuprobes++;
78
79         if(!n->status.reachable || !n->status.validkey) {
80                 ifdebug(TRAFFIC) logger(LOG_INFO, "Trying to send MTU probe to unreachable or rekeying node %s (%s)", n->name, n->hostname);
81                 n->mtuprobes = 0;
82                 return;
83         }
84
85         if(n->mtuprobes > 32) {
86                 ifdebug(TRAFFIC) logger(LOG_INFO, "%s (%s) did not respond to UDP ping, restarting PMTU discovery", n->name, n->hostname);
87                 n->mtuprobes = 1;
88                 n->minmtu = 0;
89                 n->maxmtu = MTU;
90         }
91
92         if(n->mtuprobes >= 10 && !n->minmtu) {
93                 ifdebug(TRAFFIC) logger(LOG_INFO, "No response to MTU probes from %s (%s)", n->name, n->hostname);
94                 n->mtuprobes = 0;
95                 return;
96         }
97
98         if(n->mtuprobes == 30 || (n->mtuprobes < 30 && n->minmtu >= n->maxmtu)) {
99                 if(n->minmtu > n->maxmtu)
100                         n->minmtu = n->maxmtu;
101                 else
102                         n->maxmtu = n->minmtu;
103                 n->mtu = n->minmtu;
104                 ifdebug(TRAFFIC) logger(LOG_INFO, "Fixing MTU of %s (%s) to %d after %d probes", n->name, n->hostname, n->mtu, n->mtuprobes);
105                 n->mtuprobes = 31;
106         }
107
108         if(n->mtuprobes == 31) {
109                 timeout = pinginterval;
110                 goto end;
111         } else if(n->mtuprobes == 32) {
112                 timeout = pingtimeout;
113         }
114
115         for(i = 0; i < 3; i++) {
116                 if(n->maxmtu <= n->minmtu)
117                         len = n->maxmtu;
118                 else
119                         len = n->minmtu + 1 + rand() % (n->maxmtu - n->minmtu);
120
121                 if(len < 64)
122                         len = 64;
123                 
124                 memset(packet.data, 0, 14);
125                 randomize(packet.data + 14, len - 14);
126                 packet.len = len;
127                 packet.priority = 0;
128
129                 ifdebug(TRAFFIC) logger(LOG_INFO, "Sending MTU probe length %d to %s (%s)", len, n->name, n->hostname);
130
131                 send_udppacket(n, &packet);
132         }
133
134 end:
135         event_add(&n->mtuevent, &(struct timeval){timeout, 0});
136 }
137
138 void send_mtu_probe(node_t *n) {
139         if(!timeout_initialized(&n->mtuevent))
140                 timeout_set(&n->mtuevent, send_mtu_probe_handler, n);
141         send_mtu_probe_handler(0, 0, n);
142 }
143
144 void mtu_probe_h(node_t *n, vpn_packet_t *packet, length_t len) {
145         ifdebug(TRAFFIC) logger(LOG_INFO, "Got MTU probe length %d from %s (%s)", packet->len, n->name, n->hostname);
146
147         if(!packet->data[0]) {
148                 packet->data[0] = 1;
149                 send_udppacket(n, packet);
150         } else {
151                 if(len > n->maxmtu)
152                         len = n->maxmtu;
153                 if(n->minmtu < len)
154                         n->minmtu = len;
155                 if(n->mtuprobes > 30)
156                         n->mtuprobes = 30;
157         }
158 }
159
160 static length_t compress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level) {
161         if(level == 0) {
162                 memcpy(dest, source, len);
163                 return len;
164         } else if(level == 10) {
165 #ifdef HAVE_LZO
166                 lzo_uint lzolen = MAXSIZE;
167                 lzo1x_1_compress(source, len, dest, &lzolen, lzo_wrkmem);
168                 return lzolen;
169 #else
170                 return -1;
171 #endif
172         } else if(level < 10) {
173 #ifdef HAVE_ZLIB
174                 unsigned long destlen = MAXSIZE;
175                 if(compress2(dest, &destlen, source, len, level) == Z_OK)
176                         return destlen;
177                 else
178 #endif
179                         return -1;
180         } else {
181 #ifdef HAVE_LZO
182                 lzo_uint lzolen = MAXSIZE;
183                 lzo1x_999_compress(source, len, dest, &lzolen, lzo_wrkmem);
184                 return lzolen;
185 #else
186                 return -1;
187 #endif
188         }
189         
190         return -1;
191 }
192
193 static length_t uncompress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level) {
194         if(level == 0) {
195                 memcpy(dest, source, len);
196                 return len;
197         } else if(level > 9) {
198 #ifdef HAVE_LZO
199                 lzo_uint lzolen = MAXSIZE;
200                 if(lzo1x_decompress_safe(source, len, dest, &lzolen, NULL) == LZO_E_OK)
201                         return lzolen;
202                 else
203 #endif
204                         return -1;
205         }
206 #ifdef HAVE_ZLIB
207         else {
208                 unsigned long destlen = MAXSIZE;
209                 if(uncompress(dest, &destlen, source, len) == Z_OK)
210                         return destlen;
211                 else
212                         return -1;
213         }
214 #endif
215
216         return -1;
217 }
218
219 /* VPN packet I/O */
220
221 static void receive_packet(node_t *n, vpn_packet_t *packet) {
222         ifdebug(TRAFFIC) logger(LOG_DEBUG, "Received packet of %d bytes from %s (%s)",
223                            packet->len, n->name, n->hostname);
224
225         route(n, packet);
226 }
227
228 static bool try_mac(node_t *n, const vpn_packet_t *inpkt) {
229         if(!digest_active(&n->indigest) || inpkt->len < sizeof inpkt->seqno + digest_length(&n->indigest))
230                 return false;
231
232         return digest_verify(&n->indigest, &inpkt->seqno, inpkt->len - n->indigest.maclength, (const char *)&inpkt->seqno + inpkt->len - n->indigest.maclength);
233 }
234
235 static void receive_udppacket(node_t *n, vpn_packet_t *inpkt) {
236         vpn_packet_t pkt1, pkt2;
237         vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
238         int nextpkt = 0;
239         vpn_packet_t *outpkt = pkt[0];
240         size_t outlen;
241         int i;
242
243         if(!cipher_active(&n->incipher)) {
244                 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Got packet from %s (%s) but he hasn't got our key yet",
245                                         n->name, n->hostname);
246                 return;
247         }
248
249         /* Check packet length */
250
251         if(inpkt->len < sizeof inpkt->seqno + digest_length(&n->indigest)) {
252                 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Got too short packet from %s (%s)",
253                                         n->name, n->hostname);
254                 return;
255         }
256
257         /* Check the message authentication code */
258
259         if(digest_active(&n->indigest)) {
260                 inpkt->len -= n->indigest.maclength;
261                 if(!digest_verify(&n->indigest, &inpkt->seqno, inpkt->len, (const char *)&inpkt->seqno + inpkt->len)) {
262                         ifdebug(TRAFFIC) logger(LOG_DEBUG, "Got unauthenticated packet from %s (%s)", n->name, n->hostname);
263                         return;
264                 }
265         }
266         /* Decrypt the packet */
267
268         if(cipher_active(&n->incipher)) {
269                 outpkt = pkt[nextpkt++];
270                 outlen = MAXSIZE;
271
272                 if(!cipher_decrypt(&n->incipher, &inpkt->seqno, inpkt->len, &outpkt->seqno, &outlen, true)) {
273                         ifdebug(TRAFFIC) logger(LOG_DEBUG, "Error decrypting packet from %s (%s)", n->name, n->hostname);
274                         return;
275                 }
276                 
277                 outpkt->len = outlen;
278                 inpkt = outpkt;
279         }
280
281         /* Check the sequence number */
282
283         inpkt->len -= sizeof inpkt->seqno;
284         inpkt->seqno = ntohl(inpkt->seqno);
285
286         if(inpkt->seqno != n->received_seqno + 1) {
287                 if(inpkt->seqno >= n->received_seqno + sizeof n->late * 8) {
288                         logger(LOG_WARNING, "Lost %d packets from %s (%s)",
289                                            inpkt->seqno - n->received_seqno - 1, n->name, n->hostname);
290                         
291                         memset(n->late, 0, sizeof n->late);
292                 } else if (inpkt->seqno <= n->received_seqno) {
293                         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))) {
294                                 logger(LOG_WARNING, "Got late or replayed packet from %s (%s), seqno %d, last received %d",
295                                            n->name, n->hostname, inpkt->seqno, n->received_seqno);
296                                 return;
297                         }
298                 } else {
299                         for(i = n->received_seqno + 1; i < inpkt->seqno; i++)
300                                 n->late[(i / 8) % sizeof n->late] |= 1 << i % 8;
301                 }
302         }
303         
304         n->late[(inpkt->seqno / 8) % sizeof n->late] &= ~(1 << inpkt->seqno % 8);
305
306         if(inpkt->seqno > n->received_seqno)
307                 n->received_seqno = inpkt->seqno;
308                         
309         if(n->received_seqno > MAX_SEQNO)
310                 regenerate_key();
311
312         /* Decompress the packet */
313
314         length_t origlen = inpkt->len;
315
316         if(n->incompression) {
317                 outpkt = pkt[nextpkt++];
318
319                 if((outpkt->len = uncompress_packet(outpkt->data, inpkt->data, inpkt->len, n->incompression)) < 0) {
320                         ifdebug(TRAFFIC) logger(LOG_ERR, "Error while uncompressing packet from %s (%s)",
321                                                  n->name, n->hostname);
322                         return;
323                 }
324
325                 inpkt = outpkt;
326
327                 origlen -= MTU/64 + 20;
328         }
329
330         inpkt->priority = 0;
331
332         if(!inpkt->data[12] && !inpkt->data[13])
333                 mtu_probe_h(n, inpkt, origlen);
334         else
335                 receive_packet(n, inpkt);
336 }
337
338 void receive_tcppacket(connection_t *c, char *buffer, int len) {
339         vpn_packet_t outpkt;
340
341         outpkt.len = len;
342         if(c->options & OPTION_TCPONLY)
343                 outpkt.priority = 0;
344         else
345                 outpkt.priority = -1;
346         memcpy(outpkt.data, buffer, len);
347
348         receive_packet(c->node, &outpkt);
349 }
350
351 static void send_udppacket(node_t *n, vpn_packet_t *origpkt) {
352         vpn_packet_t pkt1, pkt2;
353         vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
354         vpn_packet_t *inpkt = origpkt;
355         int nextpkt = 0;
356         vpn_packet_t *outpkt;
357         int origlen;
358         size_t outlen;
359         static int priority = 0;
360         int origpriority;
361         int sock;
362
363         if(!n->status.reachable) {
364                 ifdebug(TRAFFIC) logger(LOG_INFO, "Trying to send UDP packet to unreachable node %s (%s)", n->name, n->hostname);
365                 return;
366         }
367
368         /* Make sure we have a valid key */
369
370         if(!n->status.validkey) {
371                 ifdebug(TRAFFIC) logger(LOG_INFO,
372                                    "No valid key known yet for %s (%s), forwarding via TCP",
373                                    n->name, n->hostname);
374
375                 if(n->last_req_key + 10 < now) {
376                         send_req_key(n);
377                         n->last_req_key = now;
378                 }
379
380                 send_tcppacket(n->nexthop->connection, origpkt);
381
382                 return;
383         }
384
385         if(n->options & OPTION_PMTU_DISCOVERY && inpkt->len > n->minmtu && (inpkt->data[12] | inpkt->data[13])) {
386                 ifdebug(TRAFFIC) logger(LOG_INFO,
387                                 "Packet for %s (%s) larger than minimum MTU, forwarding via %s",
388                                 n->name, n->hostname, n != n->nexthop ? n->nexthop->name : "TCP");
389
390                 if(n != n->nexthop)
391                         send_packet(n->nexthop, origpkt);
392                 else
393                         send_tcppacket(n->nexthop->connection, origpkt);
394
395                 return;
396         }
397
398         origlen = inpkt->len;
399         origpriority = inpkt->priority;
400
401         /* Compress the packet */
402
403         if(n->outcompression) {
404                 outpkt = pkt[nextpkt++];
405
406                 if((outpkt->len = compress_packet(outpkt->data, inpkt->data, inpkt->len, n->outcompression)) < 0) {
407                         ifdebug(TRAFFIC) logger(LOG_ERR, "Error while compressing packet to %s (%s)",
408                                    n->name, n->hostname);
409                         return;
410                 }
411
412                 inpkt = outpkt;
413         }
414
415         /* Add sequence number */
416
417         inpkt->seqno = htonl(++(n->sent_seqno));
418         inpkt->len += sizeof inpkt->seqno;
419
420         /* Encrypt the packet */
421
422         if(cipher_active(&n->outcipher)) {
423                 outpkt = pkt[nextpkt++];
424                 outlen = MAXSIZE;
425
426                 if(!cipher_encrypt(&n->outcipher, &inpkt->seqno, inpkt->len, &outpkt->seqno, &outlen, true)) {
427                         ifdebug(TRAFFIC) logger(LOG_ERR, "Error while encrypting packet to %s (%s)", n->name, n->hostname);
428                         goto end;
429                 }
430
431                 outpkt->len = outlen;
432                 inpkt = outpkt;
433         }
434
435         /* Add the message authentication code */
436
437         if(digest_active(&n->outdigest)) {
438                 digest_create(&n->outdigest, &inpkt->seqno, inpkt->len, (char *)&inpkt->seqno + inpkt->len);
439                 inpkt->len += digest_length(&n->outdigest);
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         splay_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         splay_node_t *node;
540         node_t *n, *found = NULL;
541         static time_t last_hard_try = 0;
542         time_t now = time(NULL);
543
544         if(last_hard_try == now)
545                 return NULL;
546         else
547                 last_hard_try = now;
548
549         for(node = node_tree->head; node; node = node->next) {
550                 n = node->data;
551
552                 if(n == myself || !n->status.reachable || !digest_active(&n->indigest))
553                         continue;
554
555                 if(try_mac(n, pkt)) {
556                         found = n;
557                         break;
558                 }
559         }
560
561         return found;
562 }
563
564 void handle_incoming_vpn_data(int sock, short events, void *data) {
565         vpn_packet_t pkt;
566         char *hostname;
567         sockaddr_t from;
568         socklen_t fromlen = sizeof from;
569         node_t *n;
570         int len;
571
572         len = recvfrom(sock, (char *) &pkt.seqno, MAXSIZE, 0, &from.sa, &fromlen);
573
574         if(len <= 0 || len > MAXSIZE) {
575                 if(!sockwouldblock(sockerrno))
576                         logger(LOG_ERR, "Receiving packet failed: %s", sockstrerror(sockerrno));
577                 return;
578         }
579
580         pkt.len = len;
581
582         sockaddrunmap(&from);           /* Some braindead IPv6 implementations do stupid things. */
583
584         n = lookup_node_udp(&from);
585
586         if(!n) {
587                 n = try_harder(&from, &pkt);
588                 if(n)
589                         update_node_udp(n, &from);
590                 else ifdebug(PROTOCOL) {
591                         hostname = sockaddr2hostname(&from);
592                         logger(LOG_WARNING, "Received UDP packet from unknown source %s", hostname);
593                         free(hostname);
594                         return;
595                 }
596                 else
597                         return;
598         }
599
600         receive_udppacket(n, &pkt);
601 }
602
603 void handle_device_data(int sock, short events, void *data) {
604         vpn_packet_t packet;
605
606         if(read_packet(&packet))
607                 route(myself, &packet);
608 }