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