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