b3cd8d4ed071d80455f10649eb5a2454466603ee
[tinc] / 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 <gcrypt.h>
26
27 #include <zlib.h>
28 #include <lzo1x.h>
29
30 #include "avl_tree.h"
31 #include "conf.h"
32 #include "connection.h"
33 #include "device.h"
34 #include "ethernet.h"
35 #include "event.h"
36 #include "graph.h"
37 #include "list.h"
38 #include "logger.h"
39 #include "net.h"
40 #include "netutl.h"
41 #include "protocol.h"
42 #include "process.h"
43 #include "route.h"
44 #include "utils.h"
45 #include "xalloc.h"
46
47 #ifdef WSAEMSGSIZE
48 #define EMSGSIZE WSAEMSGSIZE
49 #endif
50
51 int keylifetime = 0;
52 int keyexpires = 0;
53 static char lzo_wrkmem[LZO1X_999_MEM_COMPRESS > LZO1X_1_MEM_COMPRESS ? LZO1X_999_MEM_COMPRESS : LZO1X_1_MEM_COMPRESS];
54
55 static void send_udppacket(node_t *, vpn_packet_t *);
56
57 #define MAX_SEQNO 1073741824
58
59 void send_mtu_probe(node_t *n)
60 {
61         vpn_packet_t packet;
62         int len, i;
63         
64         cp();
65
66         n->mtuprobes++;
67         n->mtuevent = NULL;
68
69         if(n->mtuprobes >= 10 && !n->minmtu) {
70                 ifdebug(TRAFFIC) logger(LOG_INFO, _("No response to MTU probes from %s (%s)"), n->name, n->hostname);
71                 return;
72         }
73
74         for(i = 0; i < 3; i++) {
75                 if(n->mtuprobes >= 30 || n->minmtu >= n->maxmtu) {
76                         n->mtu = n->minmtu;
77                         ifdebug(TRAFFIC) logger(LOG_INFO, _("Fixing MTU of %s (%s) to %d after %d probes"), n->name, n->hostname, n->mtu, n->mtuprobes);
78                         return;
79                 }
80
81                 len = n->minmtu + 1 + random() % (n->maxmtu - n->minmtu);
82                 if(len < 64)
83                         len = 64;
84                 
85                 memset(packet.data, 0, 14);
86                 gcry_randomize(packet.data + 14, len - 14, GCRY_WEAK_RANDOM);
87                 packet.len = len;
88
89                 ifdebug(TRAFFIC) logger(LOG_INFO, _("Sending MTU probe length %d to %s (%s)"), len, n->name, n->hostname);
90
91                 send_udppacket(n, &packet);
92         }
93
94         n->mtuevent = xmalloc(sizeof(*n->mtuevent));
95         n->mtuevent->handler = (event_handler_t)send_mtu_probe;
96         n->mtuevent->data = n;
97         n->mtuevent->time = now + 1;
98         event_add(n->mtuevent);
99 }
100
101 void mtu_probe_h(node_t *n, vpn_packet_t *packet) {
102         ifdebug(TRAFFIC) logger(LOG_INFO, _("Got MTU probe length %d from %s (%s)"), packet->len, n->name, n->hostname);
103
104         if(!packet->data[0]) {
105                 packet->data[0] = 1;
106                 send_packet(n, packet);
107         } else {
108                 if(n->minmtu < packet->len)
109                         n->minmtu = packet->len;
110         }
111 }
112
113 static length_t compress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level)
114 {
115         if(level == 10) {
116                 lzo_uint lzolen = MAXSIZE;
117                 lzo1x_1_compress(source, len, dest, &lzolen, lzo_wrkmem);
118                 return lzolen;
119         } else if(level < 10) {
120                 unsigned long destlen = MAXSIZE;
121                 if(compress2(dest, &destlen, source, len, level) == Z_OK)
122                         return destlen;
123                 else
124                         return -1;
125         } else {
126                 lzo_uint lzolen = MAXSIZE;
127                 lzo1x_999_compress(source, len, dest, &lzolen, lzo_wrkmem);
128                 return lzolen;
129         }
130         
131         return -1;
132 }
133
134 static length_t uncompress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level)
135 {
136         if(level > 9) {
137                 lzo_uint lzolen = MAXSIZE;
138                 if(lzo1x_decompress_safe(source, len, dest, &lzolen, NULL) == LZO_E_OK)
139                         return lzolen;
140                 else
141                         return -1;
142         } else {
143                 unsigned long destlen = MAXSIZE;
144                 if(uncompress(dest, &destlen, source, len) == Z_OK)
145                         return destlen;
146                 else
147                         return -1;
148         }
149         
150         return -1;
151 }
152
153 /* VPN packet I/O */
154
155 static void receive_packet(node_t *n, vpn_packet_t *packet)
156 {
157         cp();
158
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 void receive_udppacket(node_t *n, vpn_packet_t *inpkt)
166 {
167         vpn_packet_t pkt1, pkt2;
168         vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
169         int nextpkt = 0;
170         vpn_packet_t *outpkt = pkt[0];
171         char *hmac = NULL;
172         int result;
173         int i;
174         static char iv[32] = {0};
175
176         cp();
177
178         /* Check packet length */
179
180         if(inpkt->len < sizeof(inpkt->seqno) + myself->maclength) {
181                 ifdebug(TRAFFIC) logger(LOG_DEBUG, _("Got too short packet from %s (%s)"),
182                                         n->name, n->hostname);
183                 return;
184         }
185
186         /* Check the message authentication code */
187
188         if(myself->digest && myself->maclength) {
189                 inpkt->len -= myself->maclength;
190                 gcry_md_reset(myself->digest_ctx);
191                 gcry_md_write(myself->digest_ctx, (char *)&inpkt->seqno, inpkt->len);
192                 hmac = gcry_md_read(myself->digest_ctx, 0);
193         
194                 if(!hmac || memcmp(hmac, (char *)&inpkt->seqno + inpkt->len, myself->maclength)) {
195                         ifdebug(TRAFFIC) logger(LOG_DEBUG, _("Got unauthenticated packet from %s (%s)"),
196                                            n->name, n->hostname);
197                         return;
198                 }
199         }
200
201         /* Decrypt the packet */
202
203         if(myself->cipher) {
204                 gcry_cipher_reset(myself->cipher_ctx);
205                 //memcpy(iv, &inpkt->seqno, sizeof inpkt->seqno);
206                 //gcry_cipher_setiv(myself->cipher_ctx, iv, myself->cipherblklen);
207                 result = gcry_cipher_decrypt(myself->cipher_ctx, (char *)&inpkt->seqno, inpkt->len, NULL, 0);
208
209                 if(result) {
210                         ifdebug(TRAFFIC) logger(LOG_DEBUG, _("Error decrypting packet from %s (%s): %s"),
211                                                 n->name, n->hostname, gpg_strerror(result));
212                         logger(LOG_DEBUG, "%p %p %d", myself->cipher_ctx, (char *)&inpkt->seqno, inpkt->len);
213                         return;
214                 }
215         }
216
217         /* Remove padding */
218
219         if(myself->cipherblklen > 1) {
220                 int padlen;
221                 
222                 padlen = ((uint8_t *)&inpkt->seqno)[inpkt->len - 1];
223                 
224                 if(padlen && padlen <= myself->cipherblklen)
225                         inpkt->len -= padlen;
226         }
227
228         /* Check the sequence number */
229
230         inpkt->len -= sizeof(inpkt->seqno);
231         inpkt->seqno = ntohl(inpkt->seqno);
232
233         if(inpkt->seqno != n->received_seqno + 1) {
234                 if(inpkt->seqno >= n->received_seqno + sizeof(n->late) * 8) {
235                         logger(LOG_WARNING, _("Lost %u packets from %s (%s)"),
236                                            inpkt->seqno - n->received_seqno - 1, n->name, n->hostname);
237                         
238                         memset(n->late, 0, sizeof(n->late));
239                 } else if (inpkt->seqno <= n->received_seqno) {
240                         if(inpkt->seqno <= n->received_seqno - sizeof(n->late) * 8 || !(n->late[(inpkt->seqno / 8) % sizeof(n->late)] & (1 << inpkt->seqno % 8))) {
241                                 logger(LOG_WARNING, _("Got late or replayed packet from %s (%s), seqno %u, last received %u"),
242                                            n->name, n->hostname, inpkt->seqno, n->received_seqno);
243                         } else
244                                 for(i = n->received_seqno + 1; i < inpkt->seqno; i++)
245                                         n->late[(inpkt->seqno / 8) % sizeof(n->late)] |= 1 << i % 8;
246                 }
247         }
248         
249         if(inpkt->seqno > n->received_seqno) {
250                 n->received_seqno = inpkt->seqno;
251                 n->late[(n->received_seqno / 8) % sizeof(n->late)] &= ~(1 << n->received_seqno % 8);
252         }
253                         
254         if(n->received_seqno > MAX_SEQNO)
255                 keyexpires = 0;
256
257         /* Decompress the packet */
258
259         if(myself->compression) {
260                 outpkt = pkt[nextpkt++];
261
262                 if((outpkt->len = uncompress_packet(outpkt->data, inpkt->data, inpkt->len, myself->compression)) < 0) {
263                         ifdebug(TRAFFIC) logger(LOG_ERR, _("Error while uncompressing packet from %s (%s)"),
264                                                  n->name, n->hostname);
265                         return;
266                 }
267
268                 inpkt = outpkt;
269         }
270
271         if(n->connection)
272                 n->connection->last_ping_time = now;
273
274         if(!inpkt->data[12] && !inpkt->data[13])
275                 mtu_probe_h(n, inpkt);
276         else
277                 receive_packet(n, inpkt);
278 }
279
280 void receive_tcppacket(connection_t *c, char *buffer, int len)
281 {
282         vpn_packet_t outpkt;
283
284         cp();
285
286         outpkt.len = len;
287         memcpy(outpkt.data, buffer, len);
288
289         receive_packet(c->node, &outpkt);
290 }
291
292 static void send_udppacket(node_t *n, vpn_packet_t *inpkt)
293 {
294         vpn_packet_t pkt1, pkt2;
295         vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
296         int nextpkt = 0;
297         vpn_packet_t *outpkt;
298         int origlen;
299         int result;
300         vpn_packet_t *copy;
301         static int priority = 0;
302         int origpriority;
303         int sock;
304         char *hmac = NULL;
305         static char iv[32] = {0};
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                 /* Add padding */
359
360                 if(n->cipherblklen > 1) {
361                         int padlen, i;
362                         uint8_t *p;
363
364                         padlen = n->cipherblklen - inpkt->len % n->cipherblklen;
365                         p = (char *)&inpkt->seqno + inpkt->len;
366
367                         if(padlen == n->cipherblklen) {
368                                 if(p[-1] != 0 && p[-1] <= n->cipherblklen) {
369                                         inpkt->len += n->cipherblklen;
370                                         for(i = 0; i < n->cipherblklen; i++)
371                                                 *p++ = i + 1;
372                                 }
373                         } else {
374                                 inpkt->len += padlen;
375                                 for(i = 0; i < padlen; i++)
376                                         *p++ = i + 1;
377                         }
378                 }
379                                         
380                 gcry_cipher_reset(n->cipher_ctx);
381                 //memcpy(iv, &inpkt->seqno, sizeof inpkt->seqno);
382                 //gcry_cipher_setiv(n->cipher_ctx, iv, n->cipherblklen);
383                 result = gcry_cipher_encrypt(n->cipher_ctx, (char *)&inpkt->seqno, inpkt->len, NULL, 0);
384
385                 if(result) {
386                         ifdebug(TRAFFIC) logger(LOG_ERR, _("Error while encrypting packet to %s (%s): %s"),
387                                                 n->name, n->hostname, gpg_strerror(result));
388                         goto end;
389                 }
390         }
391
392         /* Add the message authentication code */
393
394         if(n->digest && n->maclength) {
395                 gcry_md_reset(n->digest_ctx);
396                 gcry_md_write(n->digest_ctx, (char *)&inpkt->seqno, inpkt->len);
397                 hmac = gcry_md_read(n->digest_ctx, 0);
398
399                 if(!hmac) {
400                         ifdebug(TRAFFIC) logger(LOG_ERR, _("Error while authenticating packet to %s (%s)"),
401                                                 n->name, n->hostname);
402                         goto end;
403                 }
404                 
405                 memcpy((char *)&inpkt->seqno + inpkt->len, hmac, n->maclength);
406                 inpkt->len += n->maclength;
407         }
408
409         /* Determine which socket we have to use */
410
411         for(sock = 0; sock < listen_sockets; sock++)
412                 if(n->address.sa.sa_family == listen_socket[sock].sa.sa.sa_family)
413                         break;
414
415         if(sock >= listen_sockets)
416                 sock = 0;                               /* If none is available, just use the first and hope for the best. */
417
418         /* Send the packet */
419
420 #if defined(SOL_IP) && defined(IP_TOS)
421         if(priorityinheritance && origpriority != priority
422            && listen_socket[sock].sa.sa.sa_family == AF_INET) {
423                 priority = origpriority;
424                 ifdebug(TRAFFIC) logger(LOG_DEBUG, _("Setting outgoing packet priority to %d"), priority);
425                 if(setsockopt(listen_socket[sock].udp, SOL_IP, IP_TOS, &priority, sizeof(priority)))    /* SO_PRIORITY doesn't seem to work */
426                         logger(LOG_ERR, _("System call `%s' failed: %s"), "setsockopt", strerror(errno));
427         }
428 #endif
429
430         if((sendto(listen_socket[sock].udp, (char *) &inpkt->seqno, inpkt->len, 0, &(n->address.sa), SALEN(n->address.sa))) < 0) {
431                 if(errno == EMSGSIZE) {
432                         if(n->maxmtu >= origlen)
433                                 n->maxmtu = origlen - 1;
434                         if(n->mtu >= origlen)
435                                 n->mtu = origlen - 1;
436                 } else
437                         logger(LOG_ERR, _("Error sending packet to %s (%s): %s"), n->name, n->hostname, strerror(errno));
438         }
439
440 end:
441         inpkt->len = origlen;
442 }
443
444 /*
445   send a packet to the given vpn ip.
446 */
447 void send_packet(const node_t *n, vpn_packet_t *packet)
448 {
449         node_t *via;
450
451         cp();
452
453         if(n == myself) {
454                 if(overwrite_mac)
455                          memcpy(packet->data, mymac.x, ETH_ALEN);
456                 write_packet(packet);
457                 return;
458         }
459
460         ifdebug(TRAFFIC) logger(LOG_ERR, _("Sending packet of %d bytes to %s (%s)"),
461                            packet->len, n->name, n->hostname);
462
463         if(!n->status.reachable) {
464                 ifdebug(TRAFFIC) logger(LOG_INFO, _("Node %s (%s) is not reachable"),
465                                    n->name, n->hostname);
466                 return;
467         }
468
469         via = (n->via == myself) ? n->nexthop : n->via;
470
471         if(via != n)
472                 ifdebug(TRAFFIC) logger(LOG_ERR, _("Sending packet to %s via %s (%s)"),
473                            n->name, via->name, n->via->hostname);
474
475         if((myself->options | via->options) & OPTION_TCPONLY) {
476                 if(!send_tcppacket(via->connection, packet))
477                         terminate_connection(via->connection, true);
478         } else
479                 send_udppacket(via, packet);
480 }
481
482 /* Broadcast a packet using the minimum spanning tree */
483
484 void broadcast_packet(const node_t *from, vpn_packet_t *packet)
485 {
486         avl_node_t *node;
487         connection_t *c;
488
489         cp();
490
491         ifdebug(TRAFFIC) logger(LOG_INFO, _("Broadcasting packet of %d bytes from %s (%s)"),
492                            packet->len, from->name, from->hostname);
493
494         for(node = connection_tree->head; node; node = node->next) {
495                 c = node->data;
496
497                 if(c->status.active && c->status.mst && c != from->nexthop->connection)
498                         send_packet(c->node, packet);
499         }
500 }
501
502 void flush_queue(node_t *n)
503 {
504         list_node_t *node, *next;
505
506         cp();
507
508         ifdebug(TRAFFIC) logger(LOG_INFO, _("Flushing queue for %s (%s)"), n->name, n->hostname);
509
510         for(node = n->queue->head; node; node = next) {
511                 next = node->next;
512                 send_udppacket(n, node->data);
513                 list_delete_node(n->queue, node);
514         }
515 }
516
517 void handle_incoming_vpn_data(int sock)
518 {
519         vpn_packet_t pkt;
520         char *hostname;
521         sockaddr_t from;
522         socklen_t fromlen = sizeof(from);
523         node_t *n;
524
525         cp();
526
527         pkt.len = recvfrom(sock, (char *) &pkt.seqno, MAXSIZE, 0, &from.sa, &fromlen);
528
529         if(pkt.len < 0) {
530                 logger(LOG_ERR, _("Receiving packet failed: %s"), strerror(errno));
531                 return;
532         }
533
534         sockaddrunmap(&from);           /* Some braindead IPv6 implementations do stupid things. */
535
536         n = lookup_node_udp(&from);
537
538         if(!n) {
539                 hostname = sockaddr2hostname(&from);
540                 logger(LOG_WARNING, _("Received UDP packet from unknown source %s"),
541                            hostname);
542                 free(hostname);
543                 return;
544         }
545
546         receive_udppacket(n, &pkt);
547 }