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