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