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