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