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