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