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