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