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