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