Nodes use events, so event system should be initialised first and destroyed last.
[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-2006 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 #ifdef HAVE_LZO_LZO1X_H
33 #include <lzo/lzo1x.h>
34 #endif
35 #ifdef HAVE_LZO1X_H
36 #include <lzo1x.h>
37 #endif
38
39 #include "avl_tree.h"
40 #include "conf.h"
41 #include "connection.h"
42 #include "device.h"
43 #include "ethernet.h"
44 #include "event.h"
45 #include "graph.h"
46 #include "list.h"
47 #include "logger.h"
48 #include "net.h"
49 #include "netutl.h"
50 #include "protocol.h"
51 #include "process.h"
52 #include "route.h"
53 #include "utils.h"
54 #include "xalloc.h"
55
56 #ifdef WSAEMSGSIZE
57 #define EMSGSIZE WSAEMSGSIZE
58 #endif
59
60 int keylifetime = 0;
61 int keyexpires = 0;
62 EVP_CIPHER_CTX packet_ctx;
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 void send_mtu_probe(node_t *n)
70 {
71         vpn_packet_t packet;
72         int len, i;
73         
74         cp();
75
76         n->mtuprobes++;
77         n->mtuevent = NULL;
78
79         if(n->mtuprobes >= 10 && !n->minmtu) {
80                 ifdebug(TRAFFIC) logger(LOG_INFO, _("No response to MTU probes from %s (%s)"), n->name, n->hostname);
81                 return;
82         }
83
84         for(i = 0; i < 3; i++) {
85                 if(n->mtuprobes >= 30 || n->minmtu >= n->maxmtu) {
86                         n->mtu = n->minmtu;
87                         ifdebug(TRAFFIC) logger(LOG_INFO, _("Fixing MTU of %s (%s) to %d after %d probes"), n->name, n->hostname, n->mtu, n->mtuprobes);
88                         return;
89                 }
90
91                 len = n->minmtu + 1 + random() % (n->maxmtu - n->minmtu);
92                 if(len < 64)
93                         len = 64;
94                 
95                 memset(packet.data, 0, 14);
96                 RAND_pseudo_bytes(packet.data + 14, len - 14);
97                 packet.len = len;
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) {
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 < packet->len)
119                         n->minmtu = packet->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 void receive_udppacket(node_t *n, vpn_packet_t *inpkt)
176 {
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         cp();
186
187         /* Check packet length */
188
189         if(inpkt->len < sizeof(inpkt->seqno) + myself->maclength) {
190                 ifdebug(TRAFFIC) logger(LOG_DEBUG, _("Got too short packet from %s (%s)"),
191                                         n->name, n->hostname);
192                 return;
193         }
194
195         /* Check the message authentication code */
196
197         if(myself->digest && myself->maclength) {
198                 inpkt->len -= myself->maclength;
199                 HMAC(myself->digest, myself->key, myself->keylength,
200                          (unsigned char *) &inpkt->seqno, inpkt->len, (unsigned char *)hmac, NULL);
201
202                 if(memcmp(hmac, (char *) &inpkt->seqno + inpkt->len, myself->maclength)) {
203                         ifdebug(TRAFFIC) logger(LOG_DEBUG, _("Got unauthenticated packet from %s (%s)"),
204                                            n->name, n->hostname);
205                         return;
206                 }
207         }
208
209         /* Decrypt the packet */
210
211         if(myself->cipher) {
212                 outpkt = pkt[nextpkt++];
213
214                 if(!EVP_DecryptInit_ex(&packet_ctx, NULL, NULL, NULL, NULL)
215                                 || !EVP_DecryptUpdate(&packet_ctx, (unsigned char *) &outpkt->seqno, &outlen,
216                                         (unsigned char *) &inpkt->seqno, inpkt->len)
217                                 || !EVP_DecryptFinal_ex(&packet_ctx, (unsigned char *) &outpkt->seqno + outlen, &outpad)) {
218                         ifdebug(TRAFFIC) logger(LOG_DEBUG, _("Error decrypting packet from %s (%s): %s"),
219                                                 n->name, n->hostname, ERR_error_string(ERR_get_error(), NULL));
220                         return;
221                 }
222                 
223                 outpkt->len = outlen + outpad;
224                 inpkt = outpkt;
225         }
226
227         /* Check the sequence number */
228
229         inpkt->len -= sizeof(inpkt->seqno);
230         inpkt->seqno = ntohl(inpkt->seqno);
231
232         if(inpkt->seqno != n->received_seqno + 1) {
233                 if(inpkt->seqno >= n->received_seqno + sizeof(n->late) * 8) {
234                         logger(LOG_WARNING, _("Lost %d packets from %s (%s)"),
235                                            inpkt->seqno - n->received_seqno - 1, n->name, n->hostname);
236                         
237                         memset(n->late, 0, sizeof(n->late));
238                 } else if (inpkt->seqno <= n->received_seqno) {
239                         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))) {
240                                 logger(LOG_WARNING, _("Got late or replayed packet from %s (%s), seqno %d, last received %d"),
241                                            n->name, n->hostname, inpkt->seqno, n->received_seqno);
242                                 return;
243                         }
244                 } else {
245                         for(i = n->received_seqno + 1; i < inpkt->seqno; i++)
246                                 n->late[(i / 8) % sizeof(n->late)] |= 1 << i % 8;
247                 }
248         }
249         
250         n->late[(inpkt->seqno / 8) % sizeof(n->late)] &= ~(1 << inpkt->seqno % 8);
251
252         if(inpkt->seqno > n->received_seqno)
253                 n->received_seqno = inpkt->seqno;
254                         
255         if(n->received_seqno > MAX_SEQNO)
256                 keyexpires = 0;
257
258         /* Decompress the packet */
259
260         if(myself->compression) {
261                 outpkt = pkt[nextpkt++];
262
263                 if((outpkt->len = uncompress_packet(outpkt->data, inpkt->data, inpkt->len, myself->compression)) < 0) {
264                         ifdebug(TRAFFIC) logger(LOG_ERR, _("Error while uncompressing packet from %s (%s)"),
265                                                  n->name, n->hostname);
266                         return;
267                 }
268
269                 inpkt = outpkt;
270         }
271
272         if(n->connection)
273                 n->connection->last_ping_time = now;
274
275         if(!inpkt->data[12] && !inpkt->data[13])
276                 mtu_probe_h(n, inpkt);
277         else
278                 receive_packet(n, inpkt);
279 }
280
281 void receive_tcppacket(connection_t *c, char *buffer, int len)
282 {
283         vpn_packet_t outpkt;
284
285         cp();
286
287         outpkt.len = len;
288         memcpy(outpkt.data, buffer, len);
289
290         receive_packet(c->node, &outpkt);
291 }
292
293 static void send_udppacket(node_t *n, vpn_packet_t *origpkt)
294 {
295         vpn_packet_t pkt1, pkt2;
296         vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
297         vpn_packet_t *inpkt = origpkt;
298         int nextpkt = 0;
299         vpn_packet_t *outpkt;
300         int origlen;
301         int outlen, outpad;
302         vpn_packet_t *copy;
303         static int priority = 0;
304         int origpriority;
305         int sock;
306
307         cp();
308
309         /* Make sure we have a valid key */
310
311         if(!n->status.validkey) {
312                 ifdebug(TRAFFIC) logger(LOG_INFO,
313                                    _("No valid key known yet for %s (%s), queueing packet"),
314                                    n->name, n->hostname);
315
316                 /* Since packet is on the stack of handle_tap_input(), we have to make a copy of it first. */
317
318                 *(copy = xmalloc(sizeof(*copy))) = *inpkt;
319
320                 list_insert_tail(n->queue, copy);
321
322                 if(n->queue->count > MAXQUEUELENGTH)
323                         list_delete_head(n->queue);
324
325                 if(!n->status.waitingforkey)
326                         send_req_key(n->nexthop->connection, myself, n);
327
328                 n->status.waitingforkey = true;
329
330                 return;
331         }
332
333         origlen = inpkt->len;
334         origpriority = inpkt->priority;
335
336         /* Compress the packet */
337
338         if(n->compression) {
339                 outpkt = pkt[nextpkt++];
340
341                 if((outpkt->len = compress_packet(outpkt->data, inpkt->data, inpkt->len, n->compression)) < 0) {
342                         ifdebug(TRAFFIC) logger(LOG_ERR, _("Error while compressing packet to %s (%s)"),
343                                    n->name, n->hostname);
344                         return;
345                 }
346
347                 inpkt = outpkt;
348         }
349
350         /* Add sequence number */
351
352         inpkt->seqno = htonl(++(n->sent_seqno));
353         inpkt->len += sizeof(inpkt->seqno);
354
355         /* Encrypt the packet */
356
357         if(n->cipher) {
358                 outpkt = pkt[nextpkt++];
359
360                 if(!EVP_EncryptInit_ex(&n->packet_ctx, NULL, NULL, NULL, NULL)
361                                 || !EVP_EncryptUpdate(&n->packet_ctx, (unsigned char *) &outpkt->seqno, &outlen,
362                                         (unsigned char *) &inpkt->seqno, inpkt->len)
363                                 || !EVP_EncryptFinal_ex(&n->packet_ctx, (unsigned char *) &outpkt->seqno + outlen, &outpad)) {
364                         ifdebug(TRAFFIC) logger(LOG_ERR, _("Error while encrypting packet to %s (%s): %s"),
365                                                 n->name, n->hostname, ERR_error_string(ERR_get_error(), NULL));
366                         goto end;
367                 }
368
369                 outpkt->len = outlen + outpad;
370                 inpkt = outpkt;
371         }
372
373         /* Add the message authentication code */
374
375         if(n->digest && n->maclength) {
376                 HMAC(n->digest, n->key, n->keylength, (unsigned char *) &inpkt->seqno,
377                          inpkt->len, (unsigned char *) &inpkt->seqno + inpkt->len, NULL);
378                 inpkt->len += n->maclength;
379         }
380
381         /* Determine which socket we have to use */
382
383         for(sock = 0; sock < listen_sockets; sock++)
384                 if(n->address.sa.sa_family == listen_socket[sock].sa.sa.sa_family)
385                         break;
386
387         if(sock >= listen_sockets)
388                 sock = 0;                               /* If none is available, just use the first and hope for the best. */
389
390         /* Send the packet */
391
392 #if defined(SOL_IP) && defined(IP_TOS)
393         if(priorityinheritance && origpriority != priority
394            && listen_socket[sock].sa.sa.sa_family == AF_INET) {
395                 priority = origpriority;
396                 ifdebug(TRAFFIC) logger(LOG_DEBUG, _("Setting outgoing packet priority to %d"), priority);
397                 if(setsockopt(listen_socket[sock].udp, SOL_IP, IP_TOS, &priority, sizeof(priority)))    /* SO_PRIORITY doesn't seem to work */
398                         logger(LOG_ERR, _("System call `%s' failed: %s"), "setsockopt", strerror(errno));
399         }
400 #endif
401
402         if((sendto(listen_socket[sock].udp, (char *) &inpkt->seqno, inpkt->len, 0, &(n->address.sa), SALEN(n->address.sa))) < 0) {
403                 if(errno == EMSGSIZE) {
404                         if(n->maxmtu >= origlen)
405                                 n->maxmtu = origlen - 1;
406                         if(n->mtu >= origlen)
407                                 n->mtu = origlen - 1;
408                 } else
409                         logger(LOG_ERR, _("Error sending packet to %s (%s): %s"), n->name, n->hostname, strerror(errno));
410         }
411
412 end:
413         origpkt->len = origlen;
414 }
415
416 /*
417   send a packet to the given vpn ip.
418 */
419 void send_packet(const node_t *n, vpn_packet_t *packet)
420 {
421         node_t *via;
422
423         cp();
424
425         if(n == myself) {
426                 if(overwrite_mac)
427                          memcpy(packet->data, mymac.x, ETH_ALEN);
428                 write_packet(packet);
429                 return;
430         }
431
432         ifdebug(TRAFFIC) logger(LOG_ERR, _("Sending packet of %d bytes to %s (%s)"),
433                            packet->len, n->name, n->hostname);
434
435         if(!n->status.reachable) {
436                 ifdebug(TRAFFIC) logger(LOG_INFO, _("Node %s (%s) is not reachable"),
437                                    n->name, n->hostname);
438                 return;
439         }
440
441         via = (n->via == myself) ? n->nexthop : n->via;
442
443         if(via != n)
444                 ifdebug(TRAFFIC) logger(LOG_ERR, _("Sending packet to %s via %s (%s)"),
445                            n->name, via->name, n->via->hostname);
446
447         if((myself->options | via->options) & OPTION_TCPONLY) {
448                 if(!send_tcppacket(via->connection, packet))
449                         terminate_connection(via->connection, true);
450         } else
451                 send_udppacket(via, packet);
452 }
453
454 /* Broadcast a packet using the minimum spanning tree */
455
456 void broadcast_packet(const node_t *from, vpn_packet_t *packet)
457 {
458         avl_node_t *node;
459         connection_t *c;
460
461         cp();
462
463         ifdebug(TRAFFIC) logger(LOG_INFO, _("Broadcasting packet of %d bytes from %s (%s)"),
464                            packet->len, from->name, from->hostname);
465
466         if(from != myself)
467                 send_packet(myself, packet);
468
469         for(node = connection_tree->head; node; node = node->next) {
470                 c = node->data;
471
472                 if(c->status.active && c->status.mst && c != from->nexthop->connection)
473                         send_packet(c->node, packet);
474         }
475 }
476
477 void flush_queue(node_t *n)
478 {
479         list_node_t *node, *next;
480
481         cp();
482
483         ifdebug(TRAFFIC) logger(LOG_INFO, _("Flushing queue for %s (%s)"), n->name, n->hostname);
484
485         for(node = n->queue->head; node; node = next) {
486                 next = node->next;
487                 send_udppacket(n, node->data);
488                 list_delete_node(n->queue, node);
489         }
490 }
491
492 void handle_incoming_vpn_data(int sock)
493 {
494         vpn_packet_t pkt;
495         char *hostname;
496         sockaddr_t from;
497         socklen_t fromlen = sizeof(from);
498         node_t *n;
499
500         cp();
501
502         pkt.len = recvfrom(sock, (char *) &pkt.seqno, MAXSIZE, 0, &from.sa, &fromlen);
503
504         if(pkt.len < 0) {
505                 logger(LOG_ERR, _("Receiving packet failed: %s"), strerror(errno));
506                 return;
507         }
508
509         sockaddrunmap(&from);           /* Some braindead IPv6 implementations do stupid things. */
510
511         n = lookup_node_udp(&from);
512
513         if(!n) {
514                 hostname = sockaddr2hostname(&from);
515                 logger(LOG_WARNING, _("Received UDP packet from unknown source %s"),
516                            hostname);
517                 free(hostname);
518                 return;
519         }
520
521         receive_udppacket(n, &pkt);
522 }