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