Better handling of late packets.
[oweals/tinc.git] / src / net_packet.c
1 /*
2     net_packet.c -- Handles in- and outgoing VPN packets
3     Copyright (C) 1998-2002 Ivo Timmermans <ivo@o2w.nl>,
4                   2000-2002 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.27 2003/04/18 21:18:36 guus Exp $
21 */
22
23 #include "config.h"
24
25 #include <errno.h>
26 #include <fcntl.h>
27 #include <netdb.h>
28 #include <netinet/in.h>
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <signal.h>
33 #include <sys/time.h>
34 #include <sys/types.h>
35 #include <syslog.h>
36 #include <unistd.h>
37 #include <sys/ioctl.h>
38 /* SunOS really wants sys/socket.h BEFORE net/if.h,
39    and FreeBSD wants these lines below the rest. */
40 #include <arpa/inet.h>
41 #include <sys/socket.h>
42 #include <net/if.h>
43 #ifdef HAVE_NETINET_IN_SYSTM_H
44 #include <netinet/in_systm.h>
45 #endif
46 #ifdef HAVE_NETINET_IP_H
47 #include <netinet/ip.h>
48 #endif
49 #ifdef HAVE_NETINET_TCP_H
50 #include <netinet/tcp.h>
51 #endif
52
53 #include <openssl/rand.h>
54 #include <openssl/evp.h>
55 #include <openssl/pem.h>
56 #include <openssl/hmac.h>
57
58 #include <zlib.h>
59
60 #include <utils.h>
61 #include <xalloc.h>
62 #include <avl_tree.h>
63 #include <list.h>
64
65 #include "conf.h"
66 #include "connection.h"
67 #include "meta.h"
68 #include "net.h"
69 #include "netutl.h"
70 #include "process.h"
71 #include "protocol.h"
72 #include "subnet.h"
73 #include "graph.h"
74 #include "process.h"
75 #include "route.h"
76 #include "device.h"
77 #include "event.h"
78
79 #include "system.h"
80
81 int keylifetime = 0;
82 int keyexpires = 0;
83 EVP_CIPHER_CTX packet_ctx;
84
85 #define MAX_SEQNO 1073741824
86
87 /* VPN packet I/O */
88
89 void receive_udppacket(node_t *n, vpn_packet_t *inpkt)
90 {
91         vpn_packet_t pkt1, pkt2;
92         vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
93         int nextpkt = 0;
94         vpn_packet_t *outpkt = pkt[0];
95         int outlen, outpad;
96         long int complen = MTU + 12;
97         char hmac[EVP_MAX_MD_SIZE];
98         int i;
99
100         cp();
101
102         /* Check the message authentication code */
103
104         if(myself->digest && myself->maclength) {
105                 inpkt->len -= myself->maclength;
106                 HMAC(myself->digest, myself->key, myself->keylength,
107                          (char *) &inpkt->seqno, inpkt->len, hmac, NULL);
108
109                 if(memcmp(hmac, (char *) &inpkt->seqno + inpkt->len, myself->maclength)) {
110                         if(debug_lvl >= DEBUG_TRAFFIC)
111                                 syslog(LOG_DEBUG, _("Got unauthenticated packet from %s (%s)"),
112                                            n->name, n->hostname);
113                         return;
114                 }
115         }
116
117         /* Decrypt the packet */
118
119         if(myself->cipher) {
120                 outpkt = pkt[nextpkt++];
121
122                 EVP_DecryptInit_ex(&packet_ctx, myself->cipher, NULL, myself->key,
123                                                 myself->key + myself->cipher->key_len);
124                 EVP_DecryptUpdate(&packet_ctx, (char *) &outpkt->seqno, &outlen,
125                                                   (char *) &inpkt->seqno, inpkt->len);
126                 EVP_DecryptFinal_ex(&packet_ctx, (char *) &outpkt->seqno + outlen, &outpad);
127                 
128                 outpkt->len = outlen + outpad;
129                 inpkt = outpkt;
130         }
131
132         /* Check the sequence number */
133
134         inpkt->len -= sizeof(inpkt->seqno);
135         inpkt->seqno = ntohl(inpkt->seqno);
136
137         if(inpkt->seqno != n->received_seqno + 1) {
138                 if(inpkt->seqno >= n->received_seqno + sizeof(n->late) * 8) {
139                         if(debug_lvl >= DEBUG_TRAFFIC)
140                                 syslog(LOG_WARNING, _("Lost %d packets from %s (%s)"),
141                                            inpkt->seqno - n->received_seqno - 1, n->name, n->hostname);
142                         
143                         memset(n->late, 0, sizeof(n->late));
144                 } else if (inpkt->seqno <= n->received_seqno) {
145                         if(inpkt->seqno <= n->received_seqno - sizeof(n->late) * 8 || !(n->late[(inpkt->seqno / 8) % sizeof(n->late)] & (1 << inpkt->seqno % 8))) {
146                                 syslog(LOG_WARNING, _("Got late or replayed packet from %s (%s), seqno %d, last received %d"),
147                                            n->name, n->hostname, inpkt->seqno, n->received_seqno, n->late[(inpkt->seqno / 8) % sizeof(n->late)]);
148                         } else
149                                 for(i = n->received_seqno + 1; i < inpkt->seqno; i++)
150                                         n->late[(inpkt->seqno / 8) % sizeof(n->late)] |= 1 << i % 8;
151                 }
152         }
153         
154         n->received_seqno = inpkt->seqno;
155         n->late[(n->received_seqno / 8) % sizeof(n->late)] &= ~(1 << n->received_seqno % 8);
156                         
157         if(n->received_seqno > MAX_SEQNO)
158                 keyexpires = 0;
159
160         /* Decompress the packet */
161
162         if(myself->compression) {
163                 outpkt = pkt[nextpkt++];
164
165                 if(uncompress(outpkt->data, &complen, inpkt->data, inpkt->len) != Z_OK) {
166                         syslog(LOG_ERR, _("Error while uncompressing packet from %s (%s)"),
167                                    n->name, n->hostname);
168                         return;
169                 }
170
171                 outpkt->len = complen;
172                 inpkt = outpkt;
173         }
174
175         receive_packet(n, inpkt);
176 }
177
178 void receive_tcppacket(connection_t *c, char *buffer, int len)
179 {
180         vpn_packet_t outpkt;
181
182         cp();
183
184         outpkt.len = len;
185         memcpy(outpkt.data, buffer, len);
186
187         receive_packet(c->node, &outpkt);
188 }
189
190 void receive_packet(node_t *n, vpn_packet_t *packet)
191 {
192         cp();
193
194         if(debug_lvl >= DEBUG_TRAFFIC)
195                 syslog(LOG_DEBUG, _("Received packet of %d bytes from %s (%s)"),
196                            packet->len, n->name, n->hostname);
197
198         route_incoming(n, packet);
199 }
200
201 void send_udppacket(node_t *n, vpn_packet_t *inpkt)
202 {
203         vpn_packet_t pkt1, pkt2;
204         vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
205         int nextpkt = 0;
206         vpn_packet_t *outpkt;
207         int origlen;
208         int outlen, outpad;
209         long int complen = MTU + 12;
210         vpn_packet_t *copy;
211         static int priority = 0;
212         int origpriority;
213         int sock;
214
215         cp();
216
217         /* Make sure we have a valid key */
218
219         if(!n->status.validkey) {
220                 if(debug_lvl >= DEBUG_TRAFFIC)
221                         syslog(LOG_INFO,
222                                    _("No valid key known yet for %s (%s), queueing packet"),
223                                    n->name, n->hostname);
224
225                 /* Since packet is on the stack of handle_tap_input(), we have to make a copy of it first. */
226
227                 copy = xmalloc(sizeof(vpn_packet_t));
228                 memcpy(copy, inpkt, sizeof(vpn_packet_t));
229
230                 list_insert_tail(n->queue, copy);
231
232                 if(n->queue->count > MAXQUEUELENGTH)
233                         list_delete_head(n->queue);
234
235                 if(!n->status.waitingforkey)
236                         send_req_key(n->nexthop->connection, myself, n);
237
238                 n->status.waitingforkey = 1;
239
240                 return;
241         }
242
243         origlen = inpkt->len;
244         origpriority = inpkt->priority;
245
246         /* Compress the packet */
247
248         if(n->compression) {
249                 outpkt = pkt[nextpkt++];
250
251                 if(compress2
252                    (outpkt->data, &complen, inpkt->data, inpkt->len,
253                         n->compression) != Z_OK) {
254                         syslog(LOG_ERR, _("Error while compressing packet to %s (%s)"),
255                                    n->name, n->hostname);
256                         return;
257                 }
258
259                 outpkt->len = complen;
260                 inpkt = outpkt;
261         }
262
263         /* Add sequence number */
264
265         inpkt->seqno = htonl(++(n->sent_seqno));
266         inpkt->len += sizeof(inpkt->seqno);
267
268         /* Encrypt the packet */
269
270         if(n->cipher) {
271                 outpkt = pkt[nextpkt++];
272
273                 EVP_EncryptInit_ex(&packet_ctx, n->cipher, NULL, n->key, n->key + n->cipher->key_len);
274                 EVP_EncryptUpdate(&packet_ctx, (char *) &outpkt->seqno, &outlen,
275                                                   (char *) &inpkt->seqno, inpkt->len);
276                 EVP_EncryptFinal_ex(&packet_ctx, (char *) &outpkt->seqno + outlen, &outpad);
277
278                 outpkt->len = outlen + outpad;
279                 inpkt = outpkt;
280         }
281
282         /* Add the message authentication code */
283
284         if(n->digest && n->maclength) {
285                 HMAC(n->digest, n->key, n->keylength, (char *) &inpkt->seqno,
286                          inpkt->len, (char *) &inpkt->seqno + inpkt->len, &outlen);
287                 inpkt->len += n->maclength;
288         }
289
290         /* Determine which socket we have to use */
291
292         for(sock = 0; sock < listen_sockets; sock++)
293                 if(n->address.sa.sa_family == listen_socket[sock].sa.sa.sa_family)
294                         break;
295
296         if(sock >= listen_sockets)
297                 sock = 0;                               /* If none is available, just use the first and hope for the best. */
298
299         /* Send the packet */
300
301 #if defined(SOL_IP) && defined(IP_TOS)
302         if(priorityinheritance && origpriority != priority
303            && listen_socket[sock].sa.sa.sa_family == AF_INET) {
304                 priority = origpriority;
305                 if(debug_lvl >= DEBUG_TRAFFIC)
306                         syslog(LOG_DEBUG, _("Setting outgoing packet priority to %d"),
307                                    priority);
308                 if(setsockopt(listen_socket[sock].udp, SOL_IP, IP_TOS, &priority, sizeof(priority)))    /* SO_PRIORITY doesn't seem to work */
309                         syslog(LOG_ERR, _("System call `%s' failed: %s"), "setsockopt",
310                                    strerror(errno));
311         }
312 #endif
313
314         if((sendto(listen_socket[sock].udp, (char *) &inpkt->seqno, inpkt->len, 0, &(n->address.sa), SALEN(n->address.sa))) < 0) {
315                 syslog(LOG_ERR, _("Error sending packet to %s (%s): %s"), n->name,
316                            n->hostname, strerror(errno));
317                 return;
318         }
319
320         inpkt->len = origlen;
321 }
322
323 /*
324   send a packet to the given vpn ip.
325 */
326 void send_packet(node_t *n, vpn_packet_t *packet)
327 {
328         node_t *via;
329
330         cp();
331
332         if(debug_lvl >= DEBUG_TRAFFIC)
333                 syslog(LOG_ERR, _("Sending packet of %d bytes to %s (%s)"),
334                            packet->len, n->name, n->hostname);
335
336         if(n == myself) {
337                 if(debug_lvl >= DEBUG_TRAFFIC)
338                         syslog(LOG_NOTICE, _("Packet is looping back to us!"));
339
340                 return;
341         }
342
343         if(!n->status.reachable) {
344                 if(debug_lvl >= DEBUG_TRAFFIC)
345                         syslog(LOG_INFO, _("Node %s (%s) is not reachable"),
346                                    n->name, n->hostname);
347
348                 return;
349         }
350
351         via = (n->via == myself) ? n->nexthop : n->via;
352
353         if(via != n && debug_lvl >= DEBUG_TRAFFIC)
354                 syslog(LOG_ERR, _("Sending packet to %s via %s (%s)"),
355                            n->name, via->name, n->via->hostname);
356
357         if((myself->options | via->options) & OPTION_TCPONLY) {
358                 if(send_tcppacket(via->connection, packet))
359                         terminate_connection(via->connection, 1);
360         } else
361                 send_udppacket(via, packet);
362 }
363
364 /* Broadcast a packet using the minimum spanning tree */
365
366 void broadcast_packet(node_t *from, vpn_packet_t *packet)
367 {
368         avl_node_t *node;
369         connection_t *c;
370
371         cp();
372
373         if(debug_lvl >= DEBUG_TRAFFIC)
374                 syslog(LOG_INFO, _("Broadcasting packet of %d bytes from %s (%s)"),
375                            packet->len, from->name, from->hostname);
376
377         for(node = connection_tree->head; node; node = node->next) {
378                 c = (connection_t *) node->data;
379
380                 if(c->status.active && c->status.mst && c != from->nexthop->connection)
381                         send_packet(c->node, packet);
382         }
383 }
384
385 void flush_queue(node_t *n)
386 {
387         list_node_t *node, *next;
388
389         cp();
390
391         if(debug_lvl >= DEBUG_TRAFFIC)
392                 syslog(LOG_INFO, _("Flushing queue for %s (%s)"), n->name, n->hostname);
393
394         for(node = n->queue->head; node; node = next) {
395                 next = node->next;
396                 send_udppacket(n, (vpn_packet_t *) node->data);
397                 list_delete_node(n->queue, node);
398         }
399 }
400
401 void handle_incoming_vpn_data(int sock)
402 {
403         vpn_packet_t pkt;
404         int x, l = sizeof(x);
405         char *hostname;
406         sockaddr_t from;
407         socklen_t fromlen = sizeof(from);
408         node_t *n;
409
410         cp();
411
412         if(getsockopt(sock, SOL_SOCKET, SO_ERROR, &x, &l) < 0) {
413                 syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%s"),
414                            __FILE__, __LINE__, sock, strerror(errno));
415                 cp_trace();
416                 exit(1);
417         }
418
419         if(x) {
420                 syslog(LOG_ERR, _("Incoming data socket error: %s"), strerror(x));
421                 return;
422         }
423
424         pkt.len = recvfrom(sock, (char *) &pkt.seqno, MAXSIZE, 0, &from.sa, &fromlen);
425
426         if(pkt.len <= 0) {
427                 syslog(LOG_ERR, _("Receiving packet failed: %s"), strerror(errno));
428                 return;
429         }
430
431         sockaddrunmap(&from);           /* Some braindead IPv6 implementations do stupid things. */
432
433         n = lookup_node_udp(&from);
434
435         if(!n) {
436                 hostname = sockaddr2hostname(&from);
437                 syslog(LOG_WARNING, _("Received UDP packet from unknown source %s"),
438                            hostname);
439                 free(hostname);
440                 return;
441         }
442
443         if(n->connection)
444                 n->connection->last_ping_time = now;
445
446         receive_udppacket(n, &pkt);
447 }