Applied Martin Kihlgren's IdentityGenerosity patch,
[oweals/tinc.git] / src / net_packet.c
1 /*
2     net_packet.c -- Handles in- and outgoing VPN packets
3     Copyright (C) 1998-2003 Ivo Timmermans <ivo@o2w.nl>,
4                   2000-2003 Guus Sliepen <guus@sliepen.eu.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: net_packet.c,v 1.1.2.49 2003/12/27 16:32:52 guus Exp $
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 bool strictsource = true;
58 EVP_CIPHER_CTX packet_ctx;
59 static char lzo_wrkmem[LZO1X_999_MEM_COMPRESS > LZO1X_1_MEM_COMPRESS ? LZO1X_999_MEM_COMPRESS : LZO1X_1_MEM_COMPRESS];
60
61 static void send_udppacket(node_t *, vpn_packet_t *);
62
63 #define MAX_SEQNO 1073741824
64
65 void send_mtu_probe(node_t *n)
66 {
67         vpn_packet_t packet;
68         int len, i;
69         
70         cp();
71
72         n->mtuprobes++;
73         n->mtuevent = NULL;
74
75         if(n->mtuprobes >= 10 && !n->minmtu) {
76                 ifdebug(TRAFFIC) logger(LOG_INFO, _("No response to MTU probes from %s (%s)"), n->name, n->hostname);
77                 return;
78         }
79
80         for(i = 0; i < 3; i++) {
81                 if(n->mtuprobes >= 30 || n->minmtu >= n->maxmtu) {
82                         n->mtu = n->minmtu;
83                         ifdebug(TRAFFIC) logger(LOG_INFO, _("Fixing MTU of %s (%s) to %d after %d probes"), n->name, n->hostname, n->mtu, n->mtuprobes);
84                         return;
85                 }
86
87                 len = n->minmtu + 1 + random() % (n->maxmtu - n->minmtu);
88                 if(len < 64)
89                         len = 64;
90                 
91                 memset(packet.data, 0, 14);
92                 RAND_pseudo_bytes(packet.data + 14, len - 14);
93                 packet.len = len;
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 = xmalloc(sizeof(*n->mtuevent));
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 bool authenticate_udppacket(node_t *n, vpn_packet_t *inpkt) {
172         char hmac[EVP_MAX_MD_SIZE];
173
174         if(inpkt->len < sizeof(inpkt->seqno) + (myself->digest ? myself->maclength : 0))
175                 return false;
176
177         /* Check the message authentication code */
178
179         if(myself->digest && myself->maclength) {
180                 HMAC(myself->digest, myself->key, myself->keylength,
181                          (char *) &inpkt->seqno, inpkt->len - myself->maclength, hmac, NULL);
182
183                 if(memcmp(hmac, (char *) &inpkt->seqno + inpkt->len - myself->maclength, myself->maclength))
184                         return false;
185         }
186
187         return true;
188 }
189
190 static void receive_udppacket(node_t *n, vpn_packet_t *inpkt)
191 {
192         vpn_packet_t pkt1, pkt2;
193         vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
194         int nextpkt = 0;
195         vpn_packet_t *outpkt = pkt[0];
196         int outlen, outpad;
197         int i;
198
199         cp();
200
201         if(!authenticate_udppacket(n, inpkt)) {
202                 ifdebug(TRAFFIC) logger(LOG_DEBUG, _("Got unauthenticated packet from %s (%s)"),
203                                            n->name, n->hostname);
204                 return;
205         }
206
207         inpkt->len -= myself->digest ? myself->maclength : 0;
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, (char *) &outpkt->seqno, &outlen,
216                                         (char *) &inpkt->seqno, inpkt->len)
217                                 || !EVP_DecryptFinal_ex(&packet_ctx, (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(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                         } else
243                                 for(i = n->received_seqno + 1; i < inpkt->seqno; i++)
244                                         n->late[(inpkt->seqno / 8) % sizeof(n->late)] |= 1 << i % 8;
245                 }
246         }
247         
248         n->received_seqno = inpkt->seqno;
249         n->late[(n->received_seqno / 8) % sizeof(n->late)] &= ~(1 << n->received_seqno % 8);
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         if(n->connection)
269                 n->connection->last_ping_time = now;
270
271         if(!inpkt->data[12] && !inpkt->data[13])
272                 mtu_probe_h(n, inpkt);
273         else
274                 receive_packet(n, inpkt);
275 }
276
277 void receive_tcppacket(connection_t *c, char *buffer, int len)
278 {
279         vpn_packet_t outpkt;
280
281         cp();
282
283         outpkt.len = len;
284         memcpy(outpkt.data, buffer, len);
285
286         receive_packet(c->node, &outpkt);
287 }
288
289 static void send_udppacket(node_t *n, vpn_packet_t *inpkt)
290 {
291         vpn_packet_t pkt1, pkt2;
292         vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
293         int nextpkt = 0;
294         vpn_packet_t *outpkt;
295         int origlen;
296         int outlen, outpad;
297         vpn_packet_t *copy;
298         static int priority = 0;
299         int origpriority;
300         int sock;
301
302         cp();
303
304         /* Make sure we have a valid key */
305
306         if(!n->status.validkey) {
307                 ifdebug(TRAFFIC) logger(LOG_INFO,
308                                    _("No valid key known yet for %s (%s), queueing packet"),
309                                    n->name, n->hostname);
310
311                 /* Since packet is on the stack of handle_tap_input(), we have to make a copy of it first. */
312
313                 *(copy = xmalloc(sizeof(*copy))) = *inpkt;
314
315                 list_insert_tail(n->queue, copy);
316
317                 if(n->queue->count > MAXQUEUELENGTH)
318                         list_delete_head(n->queue);
319
320                 if(!n->status.waitingforkey)
321                         send_req_key(n->nexthop->connection, myself, n);
322
323                 n->status.waitingforkey = true;
324
325                 return;
326         }
327
328         origlen = inpkt->len;
329         origpriority = inpkt->priority;
330
331         /* Compress the packet */
332
333         if(n->compression) {
334                 outpkt = pkt[nextpkt++];
335
336                 if((outpkt->len = compress_packet(outpkt->data, inpkt->data, inpkt->len, n->compression)) < 0) {
337                         ifdebug(TRAFFIC) logger(LOG_ERR, _("Error while compressing packet to %s (%s)"),
338                                    n->name, n->hostname);
339                         return;
340                 }
341
342                 inpkt = outpkt;
343         }
344
345         /* Add sequence number */
346
347         inpkt->seqno = htonl(++(n->sent_seqno));
348         inpkt->len += sizeof(inpkt->seqno);
349
350         /* Encrypt the packet */
351
352         if(n->cipher) {
353                 outpkt = pkt[nextpkt++];
354
355                 if(!EVP_EncryptInit_ex(&n->packet_ctx, NULL, NULL, NULL, NULL)
356                                 || !EVP_EncryptUpdate(&n->packet_ctx, (char *) &outpkt->seqno, &outlen,
357                                         (char *) &inpkt->seqno, inpkt->len)
358                                 || !EVP_EncryptFinal_ex(&n->packet_ctx, (char *) &outpkt->seqno + outlen, &outpad)) {
359                         ifdebug(TRAFFIC) logger(LOG_ERR, _("Error while encrypting packet to %s (%s): %s"),
360                                                 n->name, n->hostname, ERR_error_string(ERR_get_error(), NULL));
361                         goto end;
362                 }
363
364                 outpkt->len = outlen + outpad;
365                 inpkt = outpkt;
366         }
367
368         /* Add the message authentication code */
369
370         if(n->digest && n->maclength) {
371                 HMAC(n->digest, n->key, n->keylength, (char *) &inpkt->seqno,
372                          inpkt->len, (char *) &inpkt->seqno + inpkt->len, &outlen);
373                 inpkt->len += n->maclength;
374         }
375
376         /* Determine which socket we have to use */
377
378         for(sock = 0; sock < listen_sockets; sock++)
379                 if(n->address.sa.sa_family == listen_socket[sock].sa.sa.sa_family)
380                         break;
381
382         if(sock >= listen_sockets)
383                 sock = 0;                               /* If none is available, just use the first and hope for the best. */
384
385         /* Send the packet */
386
387 #if defined(SOL_IP) && defined(IP_TOS)
388         if(priorityinheritance && origpriority != priority
389            && listen_socket[sock].sa.sa.sa_family == AF_INET) {
390                 priority = origpriority;
391                 ifdebug(TRAFFIC) logger(LOG_DEBUG, _("Setting outgoing packet priority to %d"), priority);
392                 if(setsockopt(listen_socket[sock].udp, SOL_IP, IP_TOS, &priority, sizeof(priority)))    /* SO_PRIORITY doesn't seem to work */
393                         logger(LOG_ERR, _("System call `%s' failed: %s"), "setsockopt", strerror(errno));
394         }
395 #endif
396
397         if((sendto(listen_socket[sock].udp, (char *) &inpkt->seqno, inpkt->len, 0, &(n->address.sa), SALEN(n->address.sa))) < 0) {
398                 if(errno == EMSGSIZE) {
399                         if(n->maxmtu >= origlen)
400                                 n->maxmtu = origlen - 1;
401                         if(n->mtu >= origlen)
402                                 n->mtu = origlen - 1;
403                 } else
404                         logger(LOG_ERR, _("Error sending packet to %s (%s): %s"), n->name, n->hostname, strerror(errno));
405         }
406
407 end:
408         inpkt->len = origlen;
409 }
410
411 /*
412   send a packet to the given vpn ip.
413 */
414 void send_packet(const node_t *n, vpn_packet_t *packet)
415 {
416         node_t *via;
417
418         cp();
419
420         if(n == myself) {
421                 if(overwrite_mac)
422                          memcpy(packet->data, mymac.x, ETH_ALEN);
423                 write_packet(packet);
424                 return;
425         }
426
427         ifdebug(TRAFFIC) logger(LOG_ERR, _("Sending packet of %d bytes to %s (%s)"),
428                            packet->len, n->name, n->hostname);
429
430         if(!n->status.reachable) {
431                 ifdebug(TRAFFIC) logger(LOG_INFO, _("Node %s (%s) is not reachable"),
432                                    n->name, n->hostname);
433                 return;
434         }
435
436         via = (n->via == myself) ? n->nexthop : n->via;
437
438         if(via != n)
439                 ifdebug(TRAFFIC) logger(LOG_ERR, _("Sending packet to %s via %s (%s)"),
440                            n->name, via->name, n->via->hostname);
441
442         if((myself->options | via->options) & OPTION_TCPONLY) {
443                 if(!send_tcppacket(via->connection, packet))
444                         terminate_connection(via->connection, true);
445         } else
446                 send_udppacket(via, packet);
447 }
448
449 /* Broadcast a packet using the minimum spanning tree */
450
451 void broadcast_packet(const node_t *from, vpn_packet_t *packet)
452 {
453         avl_node_t *node;
454         connection_t *c;
455
456         cp();
457
458         ifdebug(TRAFFIC) logger(LOG_INFO, _("Broadcasting packet of %d bytes from %s (%s)"),
459                            packet->len, from->name, from->hostname);
460
461         for(node = connection_tree->head; node; node = node->next) {
462                 c = node->data;
463
464                 if(c->status.active && c->status.mst && c != from->nexthop->connection)
465                         send_packet(c->node, packet);
466         }
467 }
468
469 void flush_queue(node_t *n)
470 {
471         list_node_t *node, *next;
472
473         cp();
474
475         ifdebug(TRAFFIC) logger(LOG_INFO, _("Flushing queue for %s (%s)"), n->name, n->hostname);
476
477         for(node = n->queue->head; node; node = next) {
478                 next = node->next;
479                 send_udppacket(n, node->data);
480                 list_delete_node(n->queue, node);
481         }
482 }
483
484 void handle_incoming_vpn_data(int sock)
485 {
486         vpn_packet_t pkt;
487         char *hostname;
488         sockaddr_t from;
489         socklen_t fromlen = sizeof(from);
490         node_t *n;
491         static time_t lasttime = 0;
492
493         cp();
494
495         pkt.len = recvfrom(sock, (char *) &pkt.seqno, MAXSIZE, 0, &from.sa, &fromlen);
496
497         if(pkt.len < 0) {
498                 logger(LOG_ERR, _("Receiving packet failed: %s"), strerror(errno));
499                 return;
500         }
501
502         sockaddrunmap(&from);           /* Some braindead IPv6 implementations do stupid things. */
503
504         n = lookup_node_udp(&from);
505
506         if(!n && !strictsource && myself->digest && myself->maclength && lasttime != now) {
507                 avl_node_t *node;
508
509                 lasttime = now;
510
511                 for(node = node_tree->head; node; node = node->next) {
512                         n = node->data;
513
514                         if(authenticate_udppacket(n, &pkt)) {
515                                 update_node_address(n, &from);
516                                 logger(LOG_DEBUG, _("Updated address of node %s to %s"), n->name, n->hostname);
517                                 break;
518                         }
519                 }
520         }
521
522         if(!n) {
523                 hostname = sockaddr2hostname(&from);
524                 logger(LOG_WARNING, _("Received UDP packet from unknown source %s"), hostname);
525                 free(hostname);
526                 return;
527         }
528
529         receive_udppacket(n, &pkt);
530 }