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