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