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