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