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