Move source from lib/ to src/.
[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 along
17     with this program; if not, write to the Free Software Foundation, Inc.,
18     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 */
20
21 #include "system.h"
22
23 #include <zlib.h>
24 #include LZO1X_H
25
26 #include "splay_tree.h"
27 #include "cipher.h"
28 #include "conf.h"
29 #include "connection.h"
30 #include "crypto.h"
31 #include "digest.h"
32 #include "device.h"
33 #include "ethernet.h"
34 #include "graph.h"
35 #include "list.h"
36 #include "logger.h"
37 #include "net.h"
38 #include "netutl.h"
39 #include "protocol.h"
40 #include "process.h"
41 #include "route.h"
42 #include "utils.h"
43 #include "xalloc.h"
44
45 int keylifetime = 0;
46 int keyexpires = 0;
47 static char lzo_wrkmem[LZO1X_999_MEM_COMPRESS > LZO1X_1_MEM_COMPRESS ? LZO1X_999_MEM_COMPRESS : LZO1X_1_MEM_COMPRESS];
48
49 static void send_udppacket(node_t *, vpn_packet_t *);
50
51 #define MAX_SEQNO 1073741824
52
53 // mtuprobes == 1..30: initial discovery, send bursts with 1 second interval
54 // mtuprobes ==    31: sleep pinginterval seconds
55 // mtuprobes ==    32: send 1 burst, sleep pingtimeout second
56 // mtuprobes ==    33: no response from other side, restart PMTU discovery process
57
58 static void send_mtu_probe_handler(int fd, short events, void *data) {
59         node_t *n = data;
60         vpn_packet_t packet;
61         int len, i;
62         int timeout = 1;
63         
64         n->mtuprobes++;
65
66         if(!n->status.reachable || !n->status.validkey) {
67                 ifdebug(TRAFFIC) logger(LOG_INFO, "Trying to send MTU probe to unreachable or rekeying node %s (%s)", n->name, n->hostname);
68                 n->mtuprobes = 0;
69                 return;
70         }
71
72         if(n->mtuprobes > 32) {
73                 ifdebug(TRAFFIC) logger(LOG_INFO, "%s (%s) did not respond to UDP ping, restarting PMTU discovery", n->name, n->hostname);
74                 n->mtuprobes = 1;
75                 n->minmtu = 0;
76                 n->maxmtu = MTU;
77         }
78
79         if(n->mtuprobes >= 10 && !n->minmtu) {
80                 ifdebug(TRAFFIC) logger(LOG_INFO, "No response to MTU probes from %s (%s)", n->name, n->hostname);
81                 n->mtuprobes = 0;
82                 return;
83         }
84
85         if(n->mtuprobes == 30 || (n->mtuprobes < 30 && n->minmtu >= n->maxmtu)) {
86                 if(n->minmtu > n->maxmtu)
87                         n->minmtu = n->maxmtu;
88                 else
89                         n->maxmtu = n->minmtu;
90                 n->mtu = n->minmtu;
91                 ifdebug(TRAFFIC) logger(LOG_INFO, "Fixing MTU of %s (%s) to %d after %d probes", n->name, n->hostname, n->mtu, n->mtuprobes);
92                 n->mtuprobes = 31;
93         }
94
95         if(n->mtuprobes == 31) {
96                 timeout = pinginterval;
97                 goto end;
98         } else if(n->mtuprobes == 32) {
99                 timeout = pingtimeout;
100         }
101
102         for(i = 0; i < 3; i++) {
103                 if(n->maxmtu <= n->minmtu)
104                         len = n->maxmtu;
105                 else
106                         len = n->minmtu + 1 + rand() % (n->maxmtu - n->minmtu);
107
108                 if(len < 64)
109                         len = 64;
110                 
111                 memset(packet.data, 0, 14);
112                 randomize(packet.data + 14, len - 14);
113                 packet.len = len;
114                 packet.priority = 0;
115
116                 ifdebug(TRAFFIC) logger(LOG_INFO, "Sending MTU probe length %d to %s (%s)", len, n->name, n->hostname);
117
118                 send_udppacket(n, &packet);
119         }
120
121 end:
122         event_add(&n->mtuevent, &(struct timeval){timeout, 0});
123 }
124
125 void send_mtu_probe(node_t *n) {
126         if(!timeout_initialized(&n->mtuevent))
127                 timeout_set(&n->mtuevent, send_mtu_probe_handler, n);
128         send_mtu_probe_handler(0, 0, n);
129 }
130
131 void mtu_probe_h(node_t *n, vpn_packet_t *packet, length_t len) {
132         ifdebug(TRAFFIC) logger(LOG_INFO, "Got MTU probe length %d from %s (%s)", packet->len, n->name, n->hostname);
133
134         if(!packet->data[0]) {
135                 packet->data[0] = 1;
136                 send_udppacket(n, packet);
137         } else {
138                 if(len > n->maxmtu)
139                         len = n->maxmtu;
140                 if(n->minmtu < len)
141                         n->minmtu = len;
142                 if(n->mtuprobes > 30)
143                         n->mtuprobes = 30;
144         }
145 }
146
147 static length_t compress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level) {
148         if(level == 10) {
149                 lzo_uint lzolen = MAXSIZE;
150                 lzo1x_1_compress(source, len, dest, &lzolen, lzo_wrkmem);
151                 return lzolen;
152         } else if(level < 10) {
153                 unsigned long destlen = MAXSIZE;
154                 if(compress2(dest, &destlen, source, len, level) == Z_OK)
155                         return destlen;
156                 else
157                         return -1;
158         } else {
159                 lzo_uint lzolen = MAXSIZE;
160                 lzo1x_999_compress(source, len, dest, &lzolen, lzo_wrkmem);
161                 return lzolen;
162         }
163         
164         return -1;
165 }
166
167 static length_t uncompress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level) {
168         if(level > 9) {
169                 lzo_uint lzolen = MAXSIZE;
170                 if(lzo1x_decompress_safe(source, len, dest, &lzolen, NULL) == LZO_E_OK)
171                         return lzolen;
172                 else
173                         return -1;
174         } else {
175                 unsigned long destlen = MAXSIZE;
176                 if(uncompress(dest, &destlen, source, len) == Z_OK)
177                         return destlen;
178                 else
179                         return -1;
180         }
181         
182         return -1;
183 }
184
185 /* VPN packet I/O */
186
187 static void receive_packet(node_t *n, vpn_packet_t *packet) {
188         ifdebug(TRAFFIC) logger(LOG_DEBUG, "Received packet of %d bytes from %s (%s)",
189                            packet->len, n->name, n->hostname);
190
191         route(n, packet);
192 }
193
194 static bool try_mac(node_t *n, const vpn_packet_t *inpkt) {
195         if(!digest_active(&n->indigest) || inpkt->len < sizeof inpkt->seqno + digest_length(&n->indigest))
196                 return false;
197
198         return digest_verify(&n->indigest, &inpkt->seqno, inpkt->len - n->indigest.maclength, (const char *)&inpkt->seqno + inpkt->len - n->indigest.maclength);
199 }
200
201 static void receive_udppacket(node_t *n, vpn_packet_t *inpkt) {
202         vpn_packet_t pkt1, pkt2;
203         vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
204         int nextpkt = 0;
205         vpn_packet_t *outpkt = pkt[0];
206         size_t outlen;
207         int i;
208
209         if(!cipher_active(&n->incipher)) {
210                 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Got packet from %s (%s) but he hasn't got our key yet",
211                                         n->name, n->hostname);
212                 return;
213         }
214
215         /* Check packet length */
216
217         if(inpkt->len < sizeof inpkt->seqno + digest_length(&n->indigest)) {
218                 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Got too short packet from %s (%s)",
219                                         n->name, n->hostname);
220                 return;
221         }
222
223         /* Check the message authentication code */
224
225         if(digest_active(&n->indigest)) {
226                 inpkt->len -= n->indigest.maclength;
227                 if(!digest_verify(&n->indigest, &inpkt->seqno, inpkt->len, (const char *)&inpkt->seqno + inpkt->len)) {
228                         ifdebug(TRAFFIC) logger(LOG_DEBUG, "Got unauthenticated packet from %s (%s)", n->name, n->hostname);
229                         return;
230                 }
231         }
232         /* Decrypt the packet */
233
234         if(cipher_active(&n->incipher)) {
235                 outpkt = pkt[nextpkt++];
236                 outlen = MAXSIZE;
237
238                 if(!cipher_decrypt(&n->incipher, &inpkt->seqno, inpkt->len, &outpkt->seqno, &outlen, true)) {
239                         ifdebug(TRAFFIC) logger(LOG_DEBUG, "Error decrypting packet from %s (%s)", n->name, n->hostname);
240                         return;
241                 }
242                 
243                 outpkt->len = outlen;
244                 inpkt = outpkt;
245         }
246
247         /* Check the sequence number */
248
249         inpkt->len -= sizeof inpkt->seqno;
250         inpkt->seqno = ntohl(inpkt->seqno);
251
252         if(inpkt->seqno != n->received_seqno + 1) {
253                 if(inpkt->seqno >= n->received_seqno + sizeof n->late * 8) {
254                         logger(LOG_WARNING, "Lost %d packets from %s (%s)",
255                                            inpkt->seqno - n->received_seqno - 1, n->name, n->hostname);
256                         
257                         memset(n->late, 0, sizeof n->late);
258                 } else if (inpkt->seqno <= n->received_seqno) {
259                         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))) {
260                                 logger(LOG_WARNING, "Got late or replayed packet from %s (%s), seqno %d, last received %d",
261                                            n->name, n->hostname, inpkt->seqno, n->received_seqno);
262                                 return;
263                         }
264                 } else {
265                         for(i = n->received_seqno + 1; i < inpkt->seqno; i++)
266                                 n->late[(i / 8) % sizeof n->late] |= 1 << i % 8;
267                 }
268         }
269         
270         n->late[(inpkt->seqno / 8) % sizeof n->late] &= ~(1 << inpkt->seqno % 8);
271
272         if(inpkt->seqno > n->received_seqno)
273                 n->received_seqno = inpkt->seqno;
274                         
275         if(n->received_seqno > MAX_SEQNO)
276                 regenerate_key();
277
278         /* Decompress the packet */
279
280         length_t origlen = inpkt->len;
281
282         if(n->incompression) {
283                 outpkt = pkt[nextpkt++];
284
285                 if((outpkt->len = uncompress_packet(outpkt->data, inpkt->data, inpkt->len, n->incompression)) < 0) {
286                         ifdebug(TRAFFIC) logger(LOG_ERR, "Error while uncompressing packet from %s (%s)",
287                                                  n->name, n->hostname);
288                         return;
289                 }
290
291                 inpkt = outpkt;
292
293                 origlen -= MTU/64 + 20;
294         }
295
296         inpkt->priority = 0;
297
298         if(!inpkt->data[12] && !inpkt->data[13])
299                 mtu_probe_h(n, inpkt, origlen);
300         else
301                 receive_packet(n, inpkt);
302 }
303
304 void receive_tcppacket(connection_t *c, char *buffer, int len) {
305         vpn_packet_t outpkt;
306
307         outpkt.len = len;
308         if(c->options & OPTION_TCPONLY)
309                 outpkt.priority = 0;
310         else
311                 outpkt.priority = -1;
312         memcpy(outpkt.data, buffer, len);
313
314         receive_packet(c->node, &outpkt);
315 }
316
317 static void send_udppacket(node_t *n, vpn_packet_t *origpkt) {
318         vpn_packet_t pkt1, pkt2;
319         vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
320         vpn_packet_t *inpkt = origpkt;
321         int nextpkt = 0;
322         vpn_packet_t *outpkt;
323         int origlen;
324         size_t outlen;
325         static int priority = 0;
326         int origpriority;
327         int sock;
328
329         if(!n->status.reachable) {
330                 ifdebug(TRAFFIC) logger(LOG_INFO, "Trying to send UDP packet to unreachable node %s (%s)", n->name, n->hostname);
331                 return;
332         }
333
334         /* Make sure we have a valid key */
335
336         if(!n->status.validkey) {
337                 ifdebug(TRAFFIC) logger(LOG_INFO,
338                                    "No valid key known yet for %s (%s), forwarding via TCP",
339                                    n->name, n->hostname);
340
341                 if(!n->status.waitingforkey)
342                         send_req_key(n);
343
344                 n->status.waitingforkey = true;
345
346                 send_tcppacket(n->nexthop->connection, origpkt);
347
348                 return;
349         }
350
351         if(n->options & OPTION_PMTU_DISCOVERY && inpkt->len > n->minmtu && (inpkt->data[12] | inpkt->data[13])) {
352                 ifdebug(TRAFFIC) logger(LOG_INFO,
353                                 "Packet for %s (%s) larger than minimum MTU, forwarding via %s",
354                                 n->name, n->hostname, n != n->nexthop ? n->nexthop->name : "TCP");
355
356                 if(n != n->nexthop)
357                         send_packet(n->nexthop, origpkt);
358                 else
359                         send_tcppacket(n->nexthop->connection, origpkt);
360
361                 return;
362         }
363
364         origlen = inpkt->len;
365         origpriority = inpkt->priority;
366
367         /* Compress the packet */
368
369         if(n->outcompression) {
370                 outpkt = pkt[nextpkt++];
371
372                 if((outpkt->len = compress_packet(outpkt->data, inpkt->data, inpkt->len, n->outcompression)) < 0) {
373                         ifdebug(TRAFFIC) logger(LOG_ERR, "Error while compressing packet to %s (%s)",
374                                    n->name, n->hostname);
375                         return;
376                 }
377
378                 inpkt = outpkt;
379         }
380
381         /* Add sequence number */
382
383         inpkt->seqno = htonl(++(n->sent_seqno));
384         inpkt->len += sizeof inpkt->seqno;
385
386         /* Encrypt the packet */
387
388         if(cipher_active(&n->outcipher)) {
389                 outpkt = pkt[nextpkt++];
390                 outlen = MAXSIZE;
391
392                 if(!cipher_encrypt(&n->outcipher, &inpkt->seqno, inpkt->len, &outpkt->seqno, &outlen, true)) {
393                         ifdebug(TRAFFIC) logger(LOG_ERR, "Error while encrypting packet to %s (%s)", n->name, n->hostname);
394                         goto end;
395                 }
396
397                 outpkt->len = outlen;
398                 inpkt = outpkt;
399         }
400
401         /* Add the message authentication code */
402
403         if(digest_active(&n->outdigest)) {
404                 digest_create(&n->outdigest, &inpkt->seqno, inpkt->len, (char *)&inpkt->seqno + inpkt->len);
405                 inpkt->len += digest_length(&n->outdigest);
406         }
407
408         /* Determine which socket we have to use */
409
410         for(sock = 0; sock < listen_sockets; sock++)
411                 if(n->address.sa.sa_family == listen_socket[sock].sa.sa.sa_family)
412                         break;
413
414         if(sock >= listen_sockets)
415                 sock = 0;                               /* If none is available, just use the first and hope for the best. */
416
417         /* Send the packet */
418
419 #if defined(SOL_IP) && defined(IP_TOS)
420         if(priorityinheritance && origpriority != priority
421            && listen_socket[sock].sa.sa.sa_family == AF_INET) {
422                 priority = origpriority;
423                 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Setting outgoing packet priority to %d", priority);
424                 if(setsockopt(listen_socket[sock].udp, SOL_IP, IP_TOS, &priority, sizeof priority))     /* SO_PRIORITY doesn't seem to work */
425                         logger(LOG_ERR, "System call `%s' failed: %s", "setsockopt", strerror(errno));
426         }
427 #endif
428
429         if(sendto(listen_socket[sock].udp, (char *) &inpkt->seqno, inpkt->len, 0, &(n->address.sa), SALEN(n->address.sa)) < 0 && !sockwouldblock(sockerrno)) {
430                 if(sockmsgsize(sockerrno)) {
431                         if(n->maxmtu >= origlen)
432                                 n->maxmtu = origlen - 1;
433                         if(n->mtu >= origlen)
434                                 n->mtu = origlen - 1;
435                 } else
436                         logger(LOG_ERR, "Error sending packet to %s (%s): %s", n->name, n->hostname, sockstrerror(sockerrno));
437         }
438
439 end:
440         origpkt->len = origlen;
441 }
442
443 /*
444   send a packet to the given vpn ip.
445 */
446 void send_packet(const node_t *n, vpn_packet_t *packet) {
447         node_t *via;
448
449         if(n == myself) {
450                 if(overwrite_mac)
451                          memcpy(packet->data, mymac.x, ETH_ALEN);
452                 write_packet(packet);
453                 return;
454         }
455
456         ifdebug(TRAFFIC) logger(LOG_ERR, "Sending packet of %d bytes to %s (%s)",
457                            packet->len, n->name, n->hostname);
458
459         if(!n->status.reachable) {
460                 ifdebug(TRAFFIC) logger(LOG_INFO, "Node %s (%s) is not reachable",
461                                    n->name, n->hostname);
462                 return;
463         }
464
465         via = (packet->priority == -1 || n->via == myself) ? n->nexthop : n->via;
466
467         if(via != n)
468                 ifdebug(TRAFFIC) logger(LOG_INFO, "Sending packet to %s via %s (%s)",
469                            n->name, via->name, n->via->hostname);
470
471         if(packet->priority == -1 || ((myself->options | via->options) & OPTION_TCPONLY)) {
472                 if(!send_tcppacket(via->connection, packet))
473                         terminate_connection(via->connection, true);
474         } else
475                 send_udppacket(via, packet);
476 }
477
478 /* Broadcast a packet using the minimum spanning tree */
479
480 void broadcast_packet(const node_t *from, vpn_packet_t *packet) {
481         splay_node_t *node;
482         connection_t *c;
483
484         ifdebug(TRAFFIC) logger(LOG_INFO, "Broadcasting packet of %d bytes from %s (%s)",
485                            packet->len, from->name, from->hostname);
486
487         if(from != myself) {
488                 send_packet(myself, packet);
489
490                 // In TunnelServer mode, do not forward broadcast packets.
491                 // The MST might not be valid and create loops.
492                 if(tunnelserver)
493                         return;
494         }
495
496         for(node = connection_tree->head; node; node = node->next) {
497                 c = node->data;
498
499                 if(c->status.active && c->status.mst && c != from->nexthop->connection)
500                         send_packet(c->node, packet);
501         }
502 }
503
504 static node_t *try_harder(const sockaddr_t *from, const vpn_packet_t *pkt) {
505         splay_node_t *node;
506         node_t *n, *found = NULL;
507         static time_t last_hard_try = 0;
508         time_t now = time(NULL);
509
510         if(last_hard_try == now)
511                 return NULL;
512         else
513                 last_hard_try = now;
514
515         for(node = node_tree->head; node; node = node->next) {
516                 n = node->data;
517
518                 if(n == myself || !n->status.reachable || !digest_active(&n->indigest))
519                         continue;
520
521                 if(try_mac(n, pkt)) {
522                         found = n;
523                         break;
524                 }
525         }
526
527         return found;
528 }
529
530 void handle_incoming_vpn_data(int sock, short events, void *data) {
531         vpn_packet_t pkt;
532         char *hostname;
533         sockaddr_t from;
534         socklen_t fromlen = sizeof from;
535         node_t *n;
536         int len;
537
538         len = recvfrom(sock, (char *) &pkt.seqno, MAXSIZE, 0, &from.sa, &fromlen);
539
540         if(len <= 0 || len > MAXSIZE) {
541                 if(!sockwouldblock(sockerrno))
542                         logger(LOG_ERR, "Receiving packet failed: %s", sockstrerror(sockerrno));
543                 return;
544         }
545
546         pkt.len = len;
547
548         sockaddrunmap(&from);           /* Some braindead IPv6 implementations do stupid things. */
549
550         n = lookup_node_udp(&from);
551
552         if(!n) {
553                 n = try_harder(&from, &pkt);
554                 if(n)
555                         update_node_udp(n, &from);
556                 else ifdebug(PROTOCOL) {
557                         hostname = sockaddr2hostname(&from);
558                         logger(LOG_WARNING, "Received UDP packet from unknown source %s", hostname);
559                         free(hostname);
560                         return;
561                 }
562                 else
563                         return;
564         }
565
566         receive_udppacket(n, &pkt);
567 }
568
569 void handle_device_data(int sock, short events, void *data) {
570         vpn_packet_t packet;
571
572         if(read_packet(&packet))
573                 route(myself, &packet);
574 }