Merge branch 'master' into 1.1
[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-2009 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 <zlib.h>
26 #include LZO1X_H
27
28 #include "splay_tree.h"
29 #include "cipher.h"
30 #include "conf.h"
31 #include "connection.h"
32 #include "crypto.h"
33 #include "digest.h"
34 #include "device.h"
35 #include "ethernet.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 static void send_mtu_probe_handler(int fd, short events, void *data) {
60         node_t *n = data;
61         vpn_packet_t packet;
62         int len, i;
63         
64         cp();
65
66         n->mtuprobes++;
67
68         if(n->mtuprobes >= 10 && !n->minmtu) {
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->minmtu >= n->maxmtu) {
75                         n->mtu = n->minmtu;
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->minmtu + 1 + random() % (n->maxmtu - n->minmtu);
81                 if(len < 64)
82                         len = 64;
83                 
84                 memset(packet.data, 0, 14);
85                 randomize(packet.data + 14, len - 14);
86                 packet.len = len;
87                 packet.priority = 0;
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         event_add(&n->mtuevent, &(struct timeval){1, 0});
95 }
96
97 void send_mtu_probe(node_t *n) {
98         if(!timeout_initialized(&n->mtuevent))
99                 timeout_set(&n->mtuevent, send_mtu_probe_handler, n);
100         send_mtu_probe_handler(0, 0, n);
101 }
102
103 void mtu_probe_h(node_t *n, vpn_packet_t *packet, length_t len) {
104         ifdebug(TRAFFIC) logger(LOG_INFO, _("Got MTU probe length %d from %s (%s)"), packet->len, n->name, n->hostname);
105
106         if(!packet->data[0]) {
107                 packet->data[0] = 1;
108                 send_packet(n, packet);
109         } else {
110                 if(n->minmtu < len)
111                         n->minmtu = len;
112         }
113 }
114
115 static length_t compress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level) {
116         if(level == 10) {
117                 lzo_uint lzolen = MAXSIZE;
118                 lzo1x_1_compress(source, len, dest, &lzolen, lzo_wrkmem);
119                 return lzolen;
120         } else if(level < 10) {
121                 unsigned long destlen = MAXSIZE;
122                 if(compress2(dest, &destlen, source, len, level) == Z_OK)
123                         return destlen;
124                 else
125                         return -1;
126         } else {
127                 lzo_uint lzolen = MAXSIZE;
128                 lzo1x_999_compress(source, len, dest, &lzolen, lzo_wrkmem);
129                 return lzolen;
130         }
131         
132         return -1;
133 }
134
135 static length_t uncompress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level) {
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         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 bool try_mac(node_t *n, const vpn_packet_t *inpkt)
165 {
166         if(!digest_active(&n->indigest) || !n->inmaclength || inpkt->len < sizeof inpkt->seqno + n->inmaclength)
167                 return false;
168
169         return digest_verify(&n->indigest, &inpkt->seqno, inpkt->len, &inpkt->seqno + inpkt->len);
170 }
171
172 static void receive_udppacket(node_t *n, vpn_packet_t *inpkt)
173 {
174         vpn_packet_t pkt1, pkt2;
175         vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
176         int nextpkt = 0;
177         vpn_packet_t *outpkt = pkt[0];
178         size_t outlen;
179         int i;
180
181         cp();
182
183         if(!cipher_active(&n->incipher)) {
184                 ifdebug(TRAFFIC) logger(LOG_DEBUG, _("Got packet from %s (%s) but he hasn't got our key yet"),
185                                         n->name, n->hostname);
186                 return;
187         }
188
189         /* Check packet length */
190
191         if(inpkt->len < sizeof inpkt->seqno + digest_length(&n->indigest)) {
192                 ifdebug(TRAFFIC) logger(LOG_DEBUG, _("Got too short packet from %s (%s)"),
193                                         n->name, n->hostname);
194                 return;
195         }
196
197         /* Check the message authentication code */
198
199         if(digest_active(&n->indigest) && !digest_verify(&n->indigest, &inpkt->seqno, inpkt->len, &inpkt->seqno + inpkt->len)) {
200                 ifdebug(TRAFFIC) logger(LOG_DEBUG, _("Got unauthenticated packet from %s (%s)"), n->name, n->hostname);
201                 return;
202         }
203
204         /* Decrypt the packet */
205
206         if(cipher_active(&n->incipher)) {
207                 outpkt = pkt[nextpkt++];
208                 outlen = MAXSIZE;
209
210                 if(!cipher_decrypt(&n->incipher, &inpkt->seqno, inpkt->len, &outpkt->seqno, &outlen, true)) {
211                         ifdebug(TRAFFIC) logger(LOG_DEBUG, _("Error decrypting packet from %s (%s)"), n->name, n->hostname);
212                         return;
213                 }
214                 
215                 outpkt->len = outlen;
216                 inpkt = outpkt;
217         }
218
219         /* Check the sequence number */
220
221         inpkt->len -= sizeof inpkt->seqno;
222         inpkt->seqno = ntohl(inpkt->seqno);
223
224         if(inpkt->seqno != n->received_seqno + 1) {
225                 if(inpkt->seqno >= n->received_seqno + sizeof n->late * 8) {
226                         logger(LOG_WARNING, _("Lost %d packets from %s (%s)"),
227                                            inpkt->seqno - n->received_seqno - 1, n->name, n->hostname);
228                         
229                         memset(n->late, 0, sizeof n->late);
230                 } else if (inpkt->seqno <= n->received_seqno) {
231                         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))) {
232                                 logger(LOG_WARNING, _("Got late or replayed packet from %s (%s), seqno %d, last received %d"),
233                                            n->name, n->hostname, inpkt->seqno, n->received_seqno);
234                                 return;
235                         }
236                 } else {
237                         for(i = n->received_seqno + 1; i < inpkt->seqno; i++)
238                                 n->late[(i / 8) % sizeof n->late] |= 1 << i % 8;
239                 }
240         }
241         
242         n->late[(inpkt->seqno / 8) % sizeof n->late] &= ~(1 << inpkt->seqno % 8);
243
244         if(inpkt->seqno > n->received_seqno)
245                 n->received_seqno = inpkt->seqno;
246                         
247         if(n->received_seqno > MAX_SEQNO)
248                 regenerate_key();
249
250         /* Decompress the packet */
251
252         length_t origlen = inpkt->len;
253
254         if(n->incompression) {
255                 outpkt = pkt[nextpkt++];
256
257                 if((outpkt->len = uncompress_packet(outpkt->data, inpkt->data, inpkt->len, n->incompression)) < 0) {
258                         ifdebug(TRAFFIC) logger(LOG_ERR, _("Error while uncompressing packet from %s (%s)"),
259                                                  n->name, n->hostname);
260                         return;
261                 }
262
263                 inpkt = outpkt;
264
265                 origlen -= MTU/64 + 20;
266         }
267
268         inpkt->priority = 0;
269
270         if(!inpkt->data[12] && !inpkt->data[13])
271                 mtu_probe_h(n, inpkt, origlen);
272         else
273                 receive_packet(n, inpkt);
274 }
275
276 void receive_tcppacket(connection_t *c, char *buffer, int len) {
277         vpn_packet_t outpkt;
278
279         cp();
280
281         outpkt.len = len;
282         if(c->options & OPTION_TCPONLY)
283                 outpkt.priority = 0;
284         else
285                 outpkt.priority = -1;
286         memcpy(outpkt.data, buffer, len);
287
288         receive_packet(c->node, &outpkt);
289 }
290
291 static void send_udppacket(node_t *n, vpn_packet_t *origpkt) {
292         vpn_packet_t pkt1, pkt2;
293         vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
294         vpn_packet_t *inpkt = origpkt;
295         int nextpkt = 0;
296         vpn_packet_t *outpkt;
297         int origlen;
298         size_t outlen;
299         static int priority = 0;
300         int origpriority;
301         int sock;
302
303         cp();
304
305         /* Make sure we have a valid key */
306
307         if(!n->status.validkey) {
308                 ifdebug(TRAFFIC) logger(LOG_INFO,
309                                    _("No valid key known yet for %s (%s), forwarding via TCP"),
310                                    n->name, n->hostname);
311
312                 if(!n->status.waitingforkey)
313                         send_req_key(n);
314
315                 n->status.waitingforkey = true;
316
317                 send_tcppacket(n->nexthop->connection, origpkt);
318
319                 return;
320         }
321
322         if(n->options & OPTION_PMTU_DISCOVERY && !n->minmtu && (inpkt->data[12] | inpkt->data[13])) {
323                 ifdebug(TRAFFIC) logger(LOG_INFO,
324                                 _("No minimum MTU established yet for %s (%s), forwarding via TCP"),
325                                 n->name, n->hostname);
326
327                 send_tcppacket(n->nexthop->connection, origpkt);
328
329                 return;
330         }
331
332         origlen = inpkt->len;
333         origpriority = inpkt->priority;
334
335         /* Compress the packet */
336
337         if(n->outcompression) {
338                 outpkt = pkt[nextpkt++];
339
340                 if((outpkt->len = compress_packet(outpkt->data, inpkt->data, inpkt->len, n->outcompression)) < 0) {
341                         ifdebug(TRAFFIC) logger(LOG_ERR, _("Error while compressing packet to %s (%s)"),
342                                    n->name, n->hostname);
343                         return;
344                 }
345
346                 inpkt = outpkt;
347         }
348
349         /* Add sequence number */
350
351         inpkt->seqno = htonl(++(n->sent_seqno));
352         inpkt->len += sizeof inpkt->seqno;
353
354         /* Encrypt the packet */
355
356         if(cipher_active(&n->outcipher)) {
357                 outpkt = pkt[nextpkt++];
358                 outlen = MAXSIZE;
359
360                 if(!cipher_encrypt(&n->outcipher, &inpkt->seqno, inpkt->len, &outpkt->seqno, &outlen, true)) {
361                         ifdebug(TRAFFIC) logger(LOG_ERR, _("Error while encrypting packet to %s (%s)"), n->name, n->hostname);
362                         goto end;
363                 }
364
365                 outpkt->len = outlen;
366                 inpkt = outpkt;
367         }
368
369         /* Add the message authentication code */
370
371         if(digest_active(&n->outdigest)) {
372                 digest_create(&n->outdigest, &inpkt->seqno, inpkt->len, &inpkt->seqno + inpkt->len);
373                 inpkt->len += digest_length(&n->outdigest);
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         origpkt->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         node_t *via;
416
417         cp();
418
419         if(n == myself) {
420                 if(overwrite_mac)
421                          memcpy(packet->data, mymac.x, ETH_ALEN);
422                 write_packet(packet);
423                 return;
424         }
425
426         ifdebug(TRAFFIC) logger(LOG_ERR, _("Sending packet of %d bytes to %s (%s)"),
427                            packet->len, n->name, n->hostname);
428
429         if(!n->status.reachable) {
430                 ifdebug(TRAFFIC) logger(LOG_INFO, _("Node %s (%s) is not reachable"),
431                                    n->name, n->hostname);
432                 return;
433         }
434
435         via = (packet->priority == -1 || n->via == myself) ? n->nexthop : n->via;
436
437         if(via != n)
438                 ifdebug(TRAFFIC) logger(LOG_INFO, _("Sending packet to %s via %s (%s)"),
439                            n->name, via->name, n->via->hostname);
440
441         if(packet->priority == -1 || ((myself->options | via->options) & OPTION_TCPONLY)) {
442                 if(!send_tcppacket(via->connection, packet))
443                         terminate_connection(via->connection, true);
444         } else
445                 send_udppacket(via, packet);
446 }
447
448 /* Broadcast a packet using the minimum spanning tree */
449
450 void broadcast_packet(const node_t *from, vpn_packet_t *packet) {
451         splay_node_t *node;
452         connection_t *c;
453
454         cp();
455
456         ifdebug(TRAFFIC) logger(LOG_INFO, _("Broadcasting packet of %d bytes from %s (%s)"),
457                            packet->len, from->name, from->hostname);
458
459         if(from != myself) {
460                 send_packet(myself, packet);
461
462                 // In TunnelServer mode, do not forward broadcast packets.
463                 // The MST might not be valid and create loops.
464                 if(tunnelserver)
465                         return;
466         }
467
468         for(node = connection_tree->head; node; node = node->next) {
469                 c = node->data;
470
471                 if(c->status.active && c->status.mst && c != from->nexthop->connection)
472                         send_packet(c->node, packet);
473         }
474 }
475
476 static node_t *try_harder(const sockaddr_t *from, const vpn_packet_t *pkt) {
477         splay_node_t *node;
478         edge_t *e;
479         node_t *n = NULL;
480
481         for(node = edge_weight_tree->head; node; node = node->next) {
482                 e = node->data;
483
484                 if(sockaddrcmp_noport(from, &e->address))
485                         continue;
486
487                 if(!n)
488                         n = e->to;
489
490                 if(!try_mac(e->to, pkt))
491                         continue;
492
493                 n = e->to;
494                 break;
495         }
496
497         return n;
498 }
499
500 void handle_incoming_vpn_data(int sock, short events, void *data)
501 {
502         vpn_packet_t pkt;
503         char *hostname;
504         sockaddr_t from;
505         socklen_t fromlen = sizeof from;
506         node_t *n;
507
508         cp();
509
510         pkt.len = recvfrom(sock, (char *) &pkt.seqno, MAXSIZE, 0, &from.sa, &fromlen);
511
512         if(pkt.len < 0) {
513                 logger(LOG_ERR, _("Receiving packet failed: %s"), strerror(errno));
514                 return;
515         }
516
517         sockaddrunmap(&from);           /* Some braindead IPv6 implementations do stupid things. */
518
519         n = lookup_node_udp(&from);
520
521         if(!n) {
522                 n = try_harder(&from, &pkt);
523                 if(n)
524                         update_node_udp(n, &from);
525                 else ifdebug(PROTOCOL) {
526                         hostname = sockaddr2hostname(&from);
527                         logger(LOG_WARNING, _("Received UDP packet from unknown source %s"), hostname);
528                         free(hostname);
529                         return;
530                 }
531                 else
532                         return;
533         }
534
535         receive_udppacket(n, &pkt);
536 }
537
538 void handle_device_data(int sock, short events, void *data) {
539         vpn_packet_t packet;
540
541         if(read_packet(&packet))
542                 route(myself, &packet);
543 }