- Avoid memory leak caused by OpenSSL 0.9.7a.
[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.26 2003/03/28 13:41:49 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
99         cp();
100
101         /* Check the message authentication code */
102
103         if(myself->digest && myself->maclength) {
104                 inpkt->len -= myself->maclength;
105                 HMAC(myself->digest, myself->key, myself->keylength,
106                          (char *) &inpkt->seqno, inpkt->len, hmac, NULL);
107
108                 if(memcmp(hmac, (char *) &inpkt->seqno + inpkt->len, myself->maclength)) {
109                         if(debug_lvl >= DEBUG_TRAFFIC)
110                                 syslog(LOG_DEBUG, _("Got unauthenticated packet from %s (%s)"),
111                                            n->name, n->hostname);
112                         return;
113                 }
114         }
115
116         /* Decrypt the packet */
117
118         if(myself->cipher) {
119                 outpkt = pkt[nextpkt++];
120
121                 EVP_DecryptInit_ex(&packet_ctx, myself->cipher, NULL, myself->key,
122                                                 myself->key + myself->cipher->key_len);
123                 EVP_DecryptUpdate(&packet_ctx, (char *) &outpkt->seqno, &outlen,
124                                                   (char *) &inpkt->seqno, inpkt->len);
125                 EVP_DecryptFinal_ex(&packet_ctx, (char *) &outpkt->seqno + outlen, &outpad);
126                 
127                 outpkt->len = outlen + outpad;
128                 inpkt = outpkt;
129         }
130
131         /* Check the sequence number */
132
133         inpkt->len -= sizeof(inpkt->seqno);
134         inpkt->seqno = ntohl(inpkt->seqno);
135
136         if(inpkt->seqno <= n->received_seqno) {
137                 if(debug_lvl >= DEBUG_TRAFFIC)
138                         syslog(LOG_DEBUG,
139                                    _("Got late or replayed packet from %s (%s), seqno %d"),
140                                    n->name, n->hostname, inpkt->seqno);
141                 return;
142         }
143
144         n->received_seqno = inpkt->seqno;
145
146         if(n->received_seqno > MAX_SEQNO)
147                 keyexpires = 0;
148
149         /* Decompress the packet */
150
151         if(myself->compression) {
152                 outpkt = pkt[nextpkt++];
153
154                 if(uncompress(outpkt->data, &complen, inpkt->data, inpkt->len) != Z_OK) {
155                         syslog(LOG_ERR, _("Error while uncompressing packet from %s (%s)"),
156                                    n->name, n->hostname);
157                         return;
158                 }
159
160                 outpkt->len = complen;
161                 inpkt = outpkt;
162         }
163
164         receive_packet(n, inpkt);
165 }
166
167 void receive_tcppacket(connection_t *c, char *buffer, int len)
168 {
169         vpn_packet_t outpkt;
170
171         cp();
172
173         outpkt.len = len;
174         memcpy(outpkt.data, buffer, len);
175
176         receive_packet(c->node, &outpkt);
177 }
178
179 void receive_packet(node_t *n, vpn_packet_t *packet)
180 {
181         cp();
182
183         if(debug_lvl >= DEBUG_TRAFFIC)
184                 syslog(LOG_DEBUG, _("Received packet of %d bytes from %s (%s)"),
185                            packet->len, n->name, n->hostname);
186
187         route_incoming(n, packet);
188 }
189
190 void send_udppacket(node_t *n, vpn_packet_t *inpkt)
191 {
192         vpn_packet_t pkt1, pkt2;
193         vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
194         int nextpkt = 0;
195         vpn_packet_t *outpkt;
196         int origlen;
197         int outlen, outpad;
198         long int complen = MTU + 12;
199         vpn_packet_t *copy;
200         static int priority = 0;
201         int origpriority;
202         int sock;
203
204         cp();
205
206         /* Make sure we have a valid key */
207
208         if(!n->status.validkey) {
209                 if(debug_lvl >= DEBUG_TRAFFIC)
210                         syslog(LOG_INFO,
211                                    _("No valid key known yet for %s (%s), queueing packet"),
212                                    n->name, n->hostname);
213
214                 /* Since packet is on the stack of handle_tap_input(), we have to make a copy of it first. */
215
216                 copy = xmalloc(sizeof(vpn_packet_t));
217                 memcpy(copy, inpkt, sizeof(vpn_packet_t));
218
219                 list_insert_tail(n->queue, copy);
220
221                 if(n->queue->count > MAXQUEUELENGTH)
222                         list_delete_head(n->queue);
223
224                 if(!n->status.waitingforkey)
225                         send_req_key(n->nexthop->connection, myself, n);
226
227                 n->status.waitingforkey = 1;
228
229                 return;
230         }
231
232         origlen = inpkt->len;
233         origpriority = inpkt->priority;
234
235         /* Compress the packet */
236
237         if(n->compression) {
238                 outpkt = pkt[nextpkt++];
239
240                 if(compress2
241                    (outpkt->data, &complen, inpkt->data, inpkt->len,
242                         n->compression) != Z_OK) {
243                         syslog(LOG_ERR, _("Error while compressing packet to %s (%s)"),
244                                    n->name, n->hostname);
245                         return;
246                 }
247
248                 outpkt->len = complen;
249                 inpkt = outpkt;
250         }
251
252         /* Add sequence number */
253
254         inpkt->seqno = htonl(++(n->sent_seqno));
255         inpkt->len += sizeof(inpkt->seqno);
256
257         /* Encrypt the packet */
258
259         if(n->cipher) {
260                 outpkt = pkt[nextpkt++];
261
262                 EVP_EncryptInit_ex(&packet_ctx, n->cipher, NULL, n->key, n->key + n->cipher->key_len);
263                 EVP_EncryptUpdate(&packet_ctx, (char *) &outpkt->seqno, &outlen,
264                                                   (char *) &inpkt->seqno, inpkt->len);
265                 EVP_EncryptFinal_ex(&packet_ctx, (char *) &outpkt->seqno + outlen, &outpad);
266
267                 outpkt->len = outlen + outpad;
268                 inpkt = outpkt;
269         }
270
271         /* Add the message authentication code */
272
273         if(n->digest && n->maclength) {
274                 HMAC(n->digest, n->key, n->keylength, (char *) &inpkt->seqno,
275                          inpkt->len, (char *) &inpkt->seqno + inpkt->len, &outlen);
276                 inpkt->len += n->maclength;
277         }
278
279         /* Determine which socket we have to use */
280
281         for(sock = 0; sock < listen_sockets; sock++)
282                 if(n->address.sa.sa_family == listen_socket[sock].sa.sa.sa_family)
283                         break;
284
285         if(sock >= listen_sockets)
286                 sock = 0;                               /* If none is available, just use the first and hope for the best. */
287
288         /* Send the packet */
289
290 #if defined(SOL_IP) && defined(IP_TOS)
291         if(priorityinheritance && origpriority != priority
292            && listen_socket[sock].sa.sa.sa_family == AF_INET) {
293                 priority = origpriority;
294                 if(debug_lvl >= DEBUG_TRAFFIC)
295                         syslog(LOG_DEBUG, _("Setting outgoing packet priority to %d"),
296                                    priority);
297                 if(setsockopt(listen_socket[sock].udp, SOL_IP, IP_TOS, &priority, sizeof(priority)))    /* SO_PRIORITY doesn't seem to work */
298                         syslog(LOG_ERR, _("System call `%s' failed: %s"), "setsockopt",
299                                    strerror(errno));
300         }
301 #endif
302
303         if((sendto(listen_socket[sock].udp, (char *) &inpkt->seqno, inpkt->len, 0, &(n->address.sa), SALEN(n->address.sa))) < 0) {
304                 syslog(LOG_ERR, _("Error sending packet to %s (%s): %s"), n->name,
305                            n->hostname, strerror(errno));
306                 return;
307         }
308
309         inpkt->len = origlen;
310 }
311
312 /*
313   send a packet to the given vpn ip.
314 */
315 void send_packet(node_t *n, vpn_packet_t *packet)
316 {
317         node_t *via;
318
319         cp();
320
321         if(debug_lvl >= DEBUG_TRAFFIC)
322                 syslog(LOG_ERR, _("Sending packet of %d bytes to %s (%s)"),
323                            packet->len, n->name, n->hostname);
324
325         if(n == myself) {
326                 if(debug_lvl >= DEBUG_TRAFFIC)
327                         syslog(LOG_NOTICE, _("Packet is looping back to us!"));
328
329                 return;
330         }
331
332         if(!n->status.reachable) {
333                 if(debug_lvl >= DEBUG_TRAFFIC)
334                         syslog(LOG_INFO, _("Node %s (%s) is not reachable"),
335                                    n->name, n->hostname);
336
337                 return;
338         }
339
340         via = (n->via == myself) ? n->nexthop : n->via;
341
342         if(via != n && debug_lvl >= DEBUG_TRAFFIC)
343                 syslog(LOG_ERR, _("Sending packet to %s via %s (%s)"),
344                            n->name, via->name, n->via->hostname);
345
346         if((myself->options | via->options) & OPTION_TCPONLY) {
347                 if(send_tcppacket(via->connection, packet))
348                         terminate_connection(via->connection, 1);
349         } else
350                 send_udppacket(via, packet);
351 }
352
353 /* Broadcast a packet using the minimum spanning tree */
354
355 void broadcast_packet(node_t *from, vpn_packet_t *packet)
356 {
357         avl_node_t *node;
358         connection_t *c;
359
360         cp();
361
362         if(debug_lvl >= DEBUG_TRAFFIC)
363                 syslog(LOG_INFO, _("Broadcasting packet of %d bytes from %s (%s)"),
364                            packet->len, from->name, from->hostname);
365
366         for(node = connection_tree->head; node; node = node->next) {
367                 c = (connection_t *) node->data;
368
369                 if(c->status.active && c->status.mst && c != from->nexthop->connection)
370                         send_packet(c->node, packet);
371         }
372 }
373
374 void flush_queue(node_t *n)
375 {
376         list_node_t *node, *next;
377
378         cp();
379
380         if(debug_lvl >= DEBUG_TRAFFIC)
381                 syslog(LOG_INFO, _("Flushing queue for %s (%s)"), n->name, n->hostname);
382
383         for(node = n->queue->head; node; node = next) {
384                 next = node->next;
385                 send_udppacket(n, (vpn_packet_t *) node->data);
386                 list_delete_node(n->queue, node);
387         }
388 }
389
390 void handle_incoming_vpn_data(int sock)
391 {
392         vpn_packet_t pkt;
393         int x, l = sizeof(x);
394         char *hostname;
395         sockaddr_t from;
396         socklen_t fromlen = sizeof(from);
397         node_t *n;
398
399         cp();
400
401         if(getsockopt(sock, SOL_SOCKET, SO_ERROR, &x, &l) < 0) {
402                 syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%s"),
403                            __FILE__, __LINE__, sock, strerror(errno));
404                 cp_trace();
405                 exit(1);
406         }
407
408         if(x) {
409                 syslog(LOG_ERR, _("Incoming data socket error: %s"), strerror(x));
410                 return;
411         }
412
413         pkt.len = recvfrom(sock, (char *) &pkt.seqno, MAXSIZE, 0, &from.sa, &fromlen);
414
415         if(pkt.len <= 0) {
416                 syslog(LOG_ERR, _("Receiving packet failed: %s"), strerror(errno));
417                 return;
418         }
419
420         sockaddrunmap(&from);           /* Some braindead IPv6 implementations do stupid things. */
421
422         n = lookup_node_udp(&from);
423
424         if(!n) {
425                 hostname = sockaddr2hostname(&from);
426                 syslog(LOG_WARNING, _("Received UDP packet from unknown source %s"),
427                            hostname);
428                 free(hostname);
429                 return;
430         }
431
432         if(n->connection)
433                 n->connection->last_ping_time = now;
434
435         receive_udppacket(n, &pkt);
436 }