1 /* $OpenBSD: sa.c,v 1.98 2005/04/08 23:15:26 hshoexer Exp $	 */
2 /* $EOM: sa.c,v 1.112 2000/12/12 00:22:52 niklas Exp $	 */
3 
4 /*
5  * Copyright (c) 1998, 1999, 2000, 2001 Niklas Hallqvist.  All rights reserved.
6  * Copyright (c) 1999, 2001 Angelos D. Keromytis.  All rights reserved.
7  * Copyright (c) 2003, 2004 H�kan Olsson.  All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
22  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
23  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
29 
30 /*
31  * This code was written under funding by Ericsson Radio Systems.
32  */
33 
34 #include <sys/types.h>
35 #include <stdlib.h>
36 #include <string.h>
37 
38 #include <regex.h>
39 #include <keynote.h>
40 
41 #include "sysdep.h"
42 
43 #include "attribute.h"
44 #include "conf.h"
45 #include "connection.h"
46 #include "cookie.h"
47 #include "doi.h"
48 #include "exchange.h"
49 #include "isakmp.h"
50 #include "log.h"
51 #include "message.h"
52 #include "monitor.h"
53 #include "sa.h"
54 #include "timer.h"
55 #include "transport.h"
56 #include "util.h"
57 #include "cert.h"
58 #include "policy.h"
59 #include "key.h"
60 #include "ipsec.h"
61 #include "ipsec_num.h"
62 
63 /* Initial number of bits from the cookies used as hash.  */
64 #define INITIAL_BUCKET_BITS 6
65 
66 /*
67  * Don't try to use more bits than this as a hash.
68  * We only XOR 16 bits so going above that means changing the code below
69  * too.
70  */
71 #define MAX_BUCKET_BITS 16
72 
73 #if 0
74 static void     sa_resize(void);
75 #endif
76 static void     sa_soft_expire(void *);
77 static void     sa_hard_expire(void *);
78 
LIST_HEAD(sa_list,sa)79 static		LIST_HEAD(sa_list, sa) *sa_tab;
80 
81 /* Works both as a maximum index and a mask.  */
82 static int      bucket_mask;
83 
84 void
85 sa_init(void)
86 {
87 	int	i;
88 
89 	bucket_mask = (1 << INITIAL_BUCKET_BITS) - 1;
90 	sa_tab = malloc((bucket_mask + 1) * sizeof(struct sa_list));
91 	if (!sa_tab)
92 		log_fatal("sa_init: malloc (%lu) failed",
93 		    (bucket_mask + 1) * (unsigned long)sizeof(struct sa_list));
94 	for (i = 0; i <= bucket_mask; i++)
95 		LIST_INIT(&sa_tab[i]);
96 }
97 
98 #if 0
99 /* XXX We don't yet resize.  */
100 static void
101 sa_resize(void)
102 {
103 	int	new_mask = (bucket_mask + 1) * 2 - 1;
104 	int	i;
105 	struct sa_list *new_tab;
106 
107 	new_tab = realloc(sa_tab, (new_mask + 1) * sizeof(struct sa_list));
108 	if (!new_tab)
109 		return;
110 	sa_tab = new_tab;
111 	for (i = bucket_mask + 1; i <= new_mask; i++)
112 		LIST_INIT(&sa_tab[i]);
113 	bucket_mask = new_mask;
114 
115 	/* XXX Rehash existing entries.  */
116 }
117 #endif
118 
119 /* Lookup an SA with the help from a user-supplied checking function.  */
120 struct sa *
sa_find(int (* check)(struct sa *,void *),void * arg)121 sa_find(int (*check) (struct sa*, void *), void *arg)
122 {
123 	int             i;
124 	struct sa      *sa;
125 
126 	for (i = 0; i <= bucket_mask; i++)
127 		for (sa = LIST_FIRST(&sa_tab[i]); sa; sa = LIST_NEXT(sa, link))
128 			if (check(sa, arg)) {
129 				LOG_DBG((LOG_SA, 90, "sa_find: return SA %p",
130 				    sa));
131 				return sa;
132 			}
133 	LOG_DBG((LOG_SA, 90, "sa_find: no SA matched query"));
134 	return 0;
135 }
136 
137 /* Check if SA is an ISAKMP SA with an initiator cookie equal to ICOOKIE.  */
138 static int
sa_check_icookie(struct sa * sa,void * icookie)139 sa_check_icookie(struct sa *sa, void *icookie)
140 {
141 	return sa->phase == 1 &&
142 	    memcmp(sa->cookies, icookie, ISAKMP_HDR_ICOOKIE_LEN) == 0;
143 }
144 
145 /* Lookup an ISAKMP SA out of just the initiator cookie.  */
146 struct sa *
sa_lookup_from_icookie(u_int8_t * cookie)147 sa_lookup_from_icookie(u_int8_t *cookie)
148 {
149 	return sa_find(sa_check_icookie, cookie);
150 }
151 
152 struct name_phase_arg {
153 	char           *name;
154 	u_int8_t        phase;
155 };
156 
157 /* Check if SA has the name and phase given by V_ARG.  */
158 static int
sa_check_name_phase(struct sa * sa,void * v_arg)159 sa_check_name_phase(struct sa *sa, void *v_arg)
160 {
161 	struct name_phase_arg *arg = v_arg;
162 
163 	return sa->name && strcasecmp(sa->name, arg->name) == 0 &&
164 	    sa->phase == arg->phase && !(sa->flags & SA_FLAG_REPLACED);
165 }
166 
167 /* Lookup an SA by name, case-independent, and phase.  */
168 struct sa *
sa_lookup_by_name(char * name,int phase)169 sa_lookup_by_name(char *name, int phase)
170 {
171 	struct name_phase_arg arg;
172 
173 	arg.name = name;
174 	arg.phase = phase;
175 	return sa_find(sa_check_name_phase, &arg);
176 }
177 
178 struct addr_arg {
179 	struct sockaddr *addr;
180 	socklen_t       len;
181 	int             phase;
182 	int             flags;
183 };
184 
185 /*
186  * Check if SA is ready and has a peer with an address equal the one given
187  * by V_ADDR.  Furthermore if we are searching for a specific phase, check
188  * that too.
189  */
190 static int
sa_check_peer(struct sa * sa,void * v_addr)191 sa_check_peer(struct sa *sa, void *v_addr)
192 {
193 	struct addr_arg *addr = v_addr;
194 	struct sockaddr *dst;
195 
196 	if (!sa->transport || (sa->flags & SA_FLAG_READY) == 0 ||
197 	    (addr->phase && addr->phase != sa->phase))
198 		return 0;
199 
200 	sa->transport->vtbl->get_dst(sa->transport, &dst);
201 	return SA_LEN(dst) == addr->len &&
202 	    memcmp(dst, addr->addr, SA_LEN(dst)) == 0;
203 }
204 
205 struct dst_isakmpspi_arg {
206 	struct sockaddr *dst;
207 	u_int8_t       *spi;	/* must be ISAKMP_SPI_SIZE octets */
208 };
209 
210 /*
211  * Check if SA matches what we are asking for through V_ARG.  It has to
212  * be a finished phaes 1 (ISAKMP) SA.
213  */
214 static int
isakmp_sa_check(struct sa * sa,void * v_arg)215 isakmp_sa_check(struct sa *sa, void *v_arg)
216 {
217 	struct dst_isakmpspi_arg *arg = v_arg;
218 	struct sockaddr		*dst, *src;
219 
220 	if (sa->phase != 1 || !(sa->flags & SA_FLAG_READY))
221 		return 0;
222 
223 	/* verify address is either src or dst for this sa */
224 	sa->transport->vtbl->get_dst(sa->transport, &dst);
225 	sa->transport->vtbl->get_src(sa->transport, &src);
226 	if (memcmp(src, arg->dst, SA_LEN(src)) &&
227 	    memcmp(dst, arg->dst, SA_LEN(dst)))
228 		return 0;
229 
230 	/* match icookie+rcookie against spi */
231 	if (memcmp(sa->cookies, arg->spi, ISAKMP_HDR_COOKIES_LEN) == 0)
232 		return 1;
233 
234 	return 0;
235 }
236 
237 /*
238  * Find an ISAKMP SA with a "name" of DST & SPI.
239  */
240 struct sa *
sa_lookup_isakmp_sa(struct sockaddr * dst,u_int8_t * spi)241 sa_lookup_isakmp_sa(struct sockaddr *dst, u_int8_t *spi)
242 {
243 	struct dst_isakmpspi_arg arg;
244 
245 	arg.dst = dst;
246 	arg.spi = spi;
247 
248 	return sa_find(isakmp_sa_check, &arg);
249 }
250 
251 /* Lookup a ready SA by the peer's address.  */
252 struct sa *
sa_lookup_by_peer(struct sockaddr * dst,socklen_t dstlen)253 sa_lookup_by_peer(struct sockaddr *dst, socklen_t dstlen)
254 {
255 	struct addr_arg arg;
256 
257 	arg.addr = dst;
258 	arg.len = dstlen;
259 	arg.phase = 0;
260 
261 	return sa_find(sa_check_peer, &arg);
262 }
263 
264 /* Lookup a ready ISAKMP SA given its peer address.  */
265 struct sa *
sa_isakmp_lookup_by_peer(struct sockaddr * dst,socklen_t dstlen)266 sa_isakmp_lookup_by_peer(struct sockaddr *dst, socklen_t dstlen)
267 {
268 	struct addr_arg arg;
269 
270 	arg.addr = dst;
271 	arg.len = dstlen;
272 	arg.phase = 1;
273 
274 	return sa_find(sa_check_peer, &arg);
275 }
276 
277 int
sa_enter(struct sa * sa)278 sa_enter(struct sa *sa)
279 {
280 	u_int16_t       bucket = 0;
281 	int             i;
282 	u_int8_t       *cp;
283 
284 	/* XXX We might resize if we are crossing a certain threshold */
285 
286 	for (i = 0; i < ISAKMP_HDR_COOKIES_LEN; i += 2) {
287 		cp = sa->cookies + i;
288 		/* Doing it this way avoids alignment problems.  */
289 		bucket ^= cp[0] | cp[1] << 8;
290 	}
291 	for (i = 0; i < ISAKMP_HDR_MESSAGE_ID_LEN; i += 2) {
292 		cp = sa->message_id + i;
293 		/* Doing it this way avoids alignment problems.  */
294 		bucket ^= cp[0] | cp[1] << 8;
295 	}
296 	bucket &= bucket_mask;
297 	LIST_INSERT_HEAD(&sa_tab[bucket], sa, link);
298 	sa_reference(sa);
299 	LOG_DBG((LOG_SA, 70, "sa_enter: SA %p added to SA list", sa));
300 	return 1;
301 }
302 
303 /*
304  * Lookup the SA given by the header fields MSG.  PHASE2 is false when
305  * looking for phase 1 SAa and true otherwise.
306  */
307 struct sa *
sa_lookup_by_header(u_int8_t * msg,int phase2)308 sa_lookup_by_header(u_int8_t *msg, int phase2)
309 {
310 	return sa_lookup(msg + ISAKMP_HDR_COOKIES_OFF,
311 	    phase2 ? msg + ISAKMP_HDR_MESSAGE_ID_OFF : 0);
312 }
313 
314 /*
315  * Lookup the SA given by the COOKIES and possibly the MESSAGE_ID unless
316  * a null pointer, meaning we are looking for phase 1 SAs.
317  */
318 struct sa *
sa_lookup(u_int8_t * cookies,u_int8_t * message_id)319 sa_lookup(u_int8_t *cookies, u_int8_t *message_id)
320 {
321 	u_int16_t       bucket = 0;
322 	int             i;
323 	struct sa      *sa;
324 	u_int8_t       *cp;
325 
326 	/*
327 	 * We use the cookies to get bits to use as an index into sa_tab, as at
328 	 * least one (our cookie) is a good hash, xoring all the bits, 16 at a
329 	 * time, and then masking, should do.  Doing it this way means we can
330 	 * validate cookies very fast thus delimiting the effects of "Denial of
331 	 * service"-attacks using packet flooding.
332          */
333 	for (i = 0; i < ISAKMP_HDR_COOKIES_LEN; i += 2) {
334 		cp = cookies + i;
335 		/* Doing it this way avoids alignment problems.  */
336 		bucket ^= cp[0] | cp[1] << 8;
337 	}
338 	if (message_id)
339 		for (i = 0; i < ISAKMP_HDR_MESSAGE_ID_LEN; i += 2) {
340 			cp = message_id + i;
341 			/* Doing it this way avoids alignment problems.  */
342 			bucket ^= cp[0] | cp[1] << 8;
343 		}
344 	bucket &= bucket_mask;
345 	for (sa = LIST_FIRST(&sa_tab[bucket]);
346 	    sa && (memcmp(cookies, sa->cookies, ISAKMP_HDR_COOKIES_LEN) != 0 ||
347 	    (message_id && memcmp(message_id, sa->message_id,
348 	    ISAKMP_HDR_MESSAGE_ID_LEN) != 0) ||
349 	    (!message_id && !zero_test(sa->message_id, ISAKMP_HDR_MESSAGE_ID_LEN)));
350 	    sa = LIST_NEXT(sa, link))
351 		;
352 
353 	return sa;
354 }
355 
356 /* Create an SA.  */
357 int
sa_create(struct exchange * exchange,struct transport * t)358 sa_create(struct exchange *exchange, struct transport *t)
359 {
360 	struct sa      *sa;
361 
362 	/*
363 	 * We want the SA zeroed for sa_free to be able to find out what fields
364 	 * have been filled-in.
365          */
366 	sa = calloc(1, sizeof *sa);
367 	if (!sa) {
368 		log_error("sa_create: calloc (1, %lu) failed",
369 		    (unsigned long)sizeof *sa);
370 		return -1;
371 	}
372 	sa->transport = t;
373 	if (t)
374 		transport_reference(t);
375 	sa->phase = exchange->phase;
376 	memcpy(sa->cookies, exchange->cookies, ISAKMP_HDR_COOKIES_LEN);
377 	memcpy(sa->message_id, exchange->message_id,
378 	    ISAKMP_HDR_MESSAGE_ID_LEN);
379 	sa->doi = exchange->doi;
380 	sa->policy_id = -1;
381 
382 	if (sa->doi->sa_size) {
383 		/*
384 		 * Allocate the DOI-specific structure and initialize it to
385 		 * zeroes.
386 		 */
387 		sa->data = calloc(1, sa->doi->sa_size);
388 		if (!sa->data) {
389 			log_error("sa_create: calloc (1, %lu) failed",
390 			    (unsigned long)sa->doi->sa_size);
391 			free(sa);
392 			return -1;
393 		}
394 	}
395 	TAILQ_INIT(&sa->protos);
396 
397 	sa_enter(sa);
398 	TAILQ_INSERT_TAIL(&exchange->sa_list, sa, next);
399 	sa_reference(sa);
400 
401 	LOG_DBG((LOG_SA, 60,
402 	    "sa_create: sa %p phase %d added to exchange %p (%s)", sa,
403 	    sa->phase, exchange,
404 	    exchange->name ? exchange->name : "<unnamed>"));
405 	return 0;
406 }
407 
408 /*
409  * Dump the internal state of SA to the report channel, with HEADER
410  * prepended to each line.
411  */
412 void
sa_dump(int cls,int level,char * header,struct sa * sa)413 sa_dump(int cls, int level, char *header, struct sa *sa)
414 {
415 	struct proto   *proto;
416 	char            spi_header[80];
417 	int             i;
418 
419 	LOG_DBG((cls, level, "%s: %p %s phase %d doi %d flags 0x%x", header,
420 	    sa, sa->name ? sa->name : "<unnamed>", sa->phase, sa->doi->id,
421 	    sa->flags));
422 	LOG_DBG((cls, level, "%s: icookie %08x%08x rcookie %08x%08x", header,
423 	    decode_32(sa->cookies), decode_32(sa->cookies + 4),
424 	    decode_32(sa->cookies + 8), decode_32(sa->cookies + 12)));
425 	LOG_DBG((cls, level, "%s: msgid %08x refcnt %d", header,
426 	    decode_32(sa->message_id), sa->refcnt));
427 	LOG_DBG((cls, level, "%s: life secs %llu kb %llu", header, sa->seconds,
428 	    sa->kilobytes));
429 	for (proto = TAILQ_FIRST(&sa->protos); proto;
430 	    proto = TAILQ_NEXT(proto, link)) {
431 		LOG_DBG((cls, level, "%s: suite %d proto %d", header,
432 		    proto->no, proto->proto));
433 		LOG_DBG((cls, level,
434 		    "%s: spi_sz[0] %d spi[0] %p spi_sz[1] %d spi[1] %p",
435 		    header, proto->spi_sz[0], proto->spi[0], proto->spi_sz[1],
436 		    proto->spi[1]));
437 		LOG_DBG((cls, level, "%s: %s, %s", header,
438 		    !sa->doi ? "<nodoi>" :
439 		    sa->doi->decode_ids("initiator id: %s, responder id: %s",
440 		    sa->id_i, sa->id_i_len,
441 		    sa->id_r, sa->id_r_len, 0),
442 		    !sa->transport ? "<no transport>" :
443 		    sa->transport->vtbl->decode_ids(sa->transport)));
444 		for (i = 0; i < 2; i++)
445 			if (proto->spi[i]) {
446 				snprintf(spi_header, sizeof spi_header,
447 				    "%s: spi[%d]", header, i);
448 				LOG_DBG_BUF((cls, level, spi_header,
449 				    proto->spi[i], proto->spi_sz[i]));
450 			}
451 	}
452 }
453 
454 /*
455  * Display the SA's two SPI values.
456  */
457 static void
report_spi(FILE * fd,const u_int8_t * buf,size_t sz,int spi)458 report_spi(FILE *fd, const u_int8_t *buf, size_t sz, int spi)
459 {
460 #define SBUFSZ (2 * 32 + 9)
461 	char	s[SBUFSZ];
462 	size_t	i, j;
463 
464 	for (i = j = 0; i < sz;) {
465 		snprintf(s + j, sizeof s - j, "%02x", buf[i++]);
466 		j += 2;
467 		if (i % 4 == 0) {
468 			if (i % 32 == 0) {
469 				s[j] = '\0';
470 				fprintf(fd, "%s", s);
471 				j = 0;
472 			} else
473 				s[j++] = ' ';
474 		}
475 	}
476 
477 	if (j) {
478 		s[j] = '\0';
479 		fprintf(fd, "SPI %d: %s\n", spi, s);
480 	}
481 }
482 
483 /*
484  * Display the transform names to file.
485  * Structure is taken from pf_key_v2.c, pf_key_v2_set_spi.
486  * Transform names are taken from /usr/src/sys/crypto/xform.c.
487  */
488 static void
report_proto(FILE * fd,struct proto * proto)489 report_proto(FILE *fd, struct proto *proto)
490 {
491 	struct ipsec_proto *iproto = proto->data;
492 	int	keylen, hashlen;
493 
494 	switch (proto->proto) {
495 	case IPSEC_PROTO_IPSEC_ESP:
496 		keylen = ipsec_esp_enckeylength(proto);
497 		hashlen = ipsec_esp_authkeylength(proto);
498 		fprintf(fd, "Transform: IPsec ESP\n");
499 		fprintf(fd, "Encryption key length: %d\n", keylen);
500 		fprintf(fd, "Authentication key length: %d\n", hashlen);
501 
502 		fprintf(fd, "Encryption algorithm: ");
503 		switch (proto->id) {
504 		case IPSEC_ESP_DES:
505 		case IPSEC_ESP_DES_IV32:
506 		case IPSEC_ESP_DES_IV64:
507 			fprintf(fd, "DES\n");
508 			break;
509 
510 		case IPSEC_ESP_3DES:
511 			fprintf(fd, "3DES\n");
512 			break;
513 
514 		case IPSEC_ESP_AES:
515 			fprintf(fd, "AES-128 (CBC)\n");
516 			break;
517 
518 		case IPSEC_ESP_AES_128_CTR:
519 			fprintf(fd, "AES-128 (CTR)\n");
520 			break;
521 
522 		case IPSEC_ESP_CAST:
523 			fprintf(fd, "Cast-128\n");
524 			break;
525 
526 		case IPSEC_ESP_BLOWFISH:
527 			fprintf(fd, "Blowfish\n");
528 			break;
529 
530 		default:
531 			fprintf(fd, "unknown (%d)\n", proto->id);
532 		}
533 
534 		fprintf(fd, "Authentication algorithm: ");
535 		switch (iproto->auth) {
536 		case IPSEC_AUTH_HMAC_MD5:
537 			fprintf(fd, "HMAC-MD5\n");
538 			break;
539 
540 		case IPSEC_AUTH_HMAC_SHA:
541 			fprintf(fd, "HMAC-SHA1\n");
542 			break;
543 
544 		case IPSEC_AUTH_HMAC_RIPEMD:
545 			fprintf(fd, "HMAC-RIPEMD-160\n");
546 			break;
547 
548 		case IPSEC_AUTH_HMAC_SHA2_256:
549 			fprintf(fd, "HMAC-SHA2-256\n");
550 			break;
551 
552 		case IPSEC_AUTH_HMAC_SHA2_384:
553 			fprintf(fd, "HMAC-SHA2-384\n");
554 			break;
555 
556 		case IPSEC_AUTH_HMAC_SHA2_512:
557 			fprintf(fd, "HMAC-SHA2-512\n");
558 			break;
559 
560 		case IPSEC_AUTH_DES_MAC:
561 		case IPSEC_AUTH_KPDK:
562 			/* XXX We should be supporting KPDK */
563 			fprintf(fd, "unknown (%d)", iproto->auth);
564 			break;
565 
566 		default:
567 			fprintf(fd, "none\n");
568 		}
569 		break;
570 
571 	case IPSEC_PROTO_IPSEC_AH:
572 		hashlen = ipsec_ah_keylength(proto);
573 		fprintf(fd, "Transform: IPsec AH\n");
574 		fprintf(fd, "Encryption not used.\n");
575 		fprintf(fd, "Authentication key length: %d\n", hashlen);
576 
577 		fprintf(fd, "Authentication algorithm: ");
578 		switch (proto->id) {
579 		case IPSEC_AH_MD5:
580 			fprintf(fd, "HMAC-MD5\n");
581 			break;
582 
583 		case IPSEC_AH_SHA:
584 			fprintf(fd, "HMAC-SHA1\n");
585 			break;
586 
587 		case IPSEC_AH_RIPEMD:
588 			fprintf(fd, "HMAC-RIPEMD-160\n");
589 			break;
590 
591 		case IPSEC_AH_SHA2_256:
592 			fprintf(fd, "HMAC-SHA2-256\n");
593 			break;
594 
595 		case IPSEC_AH_SHA2_384:
596 			fprintf(fd, "HMAC-SHA2-384\n");
597 			break;
598 
599 		case IPSEC_AH_SHA2_512:
600 			fprintf(fd, "HMAC-SHA2-512\n");
601 			break;
602 
603 		default:
604 			fprintf(fd, "unknown (%d)", proto->id);
605 		}
606 		break;
607 
608 	default:
609 		fprintf(fd, "report_proto: invalid proto %d\n", proto->proto);
610 	}
611 }
612 
613 /* Report all the SAs to the report channel.  */
614 void
sa_report(void)615 sa_report(void)
616 {
617 	struct sa      *sa;
618 	int             i;
619 
620 	for (i = 0; i <= bucket_mask; i++)
621 		for (sa = LIST_FIRST(&sa_tab[i]); sa; sa = LIST_NEXT(sa, link))
622 			sa_dump(LOG_REPORT, 0, "sa_report", sa);
623 }
624 
625 
626 /*
627  * Print an SA's connection details to file SA_FILE.
628  */
629 static void
sa_dump_all(FILE * fd,struct sa * sa)630 sa_dump_all(FILE *fd, struct sa *sa)
631 {
632 	struct proto   *proto;
633 	int             i;
634 
635 	/* SA name and phase. */
636 	fprintf(fd, "SA name: %s", sa->name ? sa->name : "<unnamed>");
637 	fprintf(fd, " (Phase %d)\n", sa->phase);
638 
639 	/* Source and destination IPs. */
640 	fprintf(fd, "%s", sa->transport == NULL ? "<no transport>" :
641 	    sa->transport->vtbl->decode_ids(sa->transport));
642 	fprintf(fd, "\n");
643 
644 	/* Transform information. */
645 	for (proto = TAILQ_FIRST(&sa->protos); proto;
646 	    proto = TAILQ_NEXT(proto, link)) {
647 		/* SPI values. */
648 		for (i = 0; i < 2; i++)
649 			if (proto->spi[i])
650 				report_spi(fd, proto->spi[i], proto->spi_sz[i],
651 				    i);
652 			else
653 				fprintf(fd, "SPI %d not defined.", i);
654 
655 		/* Proto values. */
656 		report_proto(fd, proto);
657 
658 		/* SA separator. */
659 		fprintf(fd, "\n");
660 	}
661 }
662 
663 /* Report info of all SAs to file 'fd'.  */
664 void
sa_report_all(FILE * fd)665 sa_report_all(FILE *fd)
666 {
667 	struct sa      *sa;
668 	int             i;
669 
670 	for (i = 0; i <= bucket_mask; i++)
671 		for (sa = LIST_FIRST(&sa_tab[i]); sa; sa = LIST_NEXT(sa, link))
672 			if (sa->phase == 1)
673 				fprintf(fd, "SA name: none (phase 1)\n\n");
674 			else
675 				sa_dump_all(fd, sa);
676 }
677 
678 /* Free the protocol structure pointed to by PROTO.  */
679 void
proto_free(struct proto * proto)680 proto_free(struct proto *proto)
681 {
682 	struct proto_attr *pa;
683 	struct sa      *sa = proto->sa;
684 	int             i;
685 
686 	for (i = 0; i < 2; i++)
687 		if (proto->spi[i]) {
688 			if (sa->doi->delete_spi)
689 				sa->doi->delete_spi(sa, proto, i);
690 			free(proto->spi[i]);
691 		}
692 	TAILQ_REMOVE(&sa->protos, proto, link);
693 	if (proto->data) {
694 		if (sa->doi && sa->doi->free_proto_data)
695 			sa->doi->free_proto_data(proto->data);
696 		free(proto->data);
697 	}
698 	if (proto->xf_cnt)
699 		while ((pa = TAILQ_FIRST(&proto->xfs)) != NULL) {
700 			if (pa->attrs)
701 				free(pa->attrs);
702 			TAILQ_REMOVE(&proto->xfs, pa, next);
703 			free(pa);
704 		}
705 
706 	LOG_DBG((LOG_SA, 90, "proto_free: freeing %p", proto));
707 	free(proto);
708 }
709 
710 /* Release all resources this SA is using.  */
711 void
sa_free(struct sa * sa)712 sa_free(struct sa *sa)
713 {
714 	if (sa->death) {
715 		timer_remove_event(sa->death);
716 		sa->death = 0;
717 		sa->refcnt--;
718 	}
719 	if (sa->soft_death) {
720 		timer_remove_event(sa->soft_death);
721 		sa->soft_death = 0;
722 		sa->refcnt--;
723 	}
724 	if (sa->dpd_event) {
725 		timer_remove_event(sa->dpd_event);
726 		sa->dpd_event = 0;
727 	}
728 	sa_remove(sa);
729 }
730 
731 /* Remove the SA from the hash table of live SAs.  */
732 void
sa_remove(struct sa * sa)733 sa_remove(struct sa *sa)
734 {
735 	LIST_REMOVE(sa, link);
736 	LOG_DBG((LOG_SA, 70, "sa_remove: SA %p removed from SA list", sa));
737 	sa_release(sa);
738 }
739 
740 /* Raise the reference count of SA.  */
741 void
sa_reference(struct sa * sa)742 sa_reference(struct sa *sa)
743 {
744 	sa->refcnt++;
745 	LOG_DBG((LOG_SA, 80, "sa_reference: SA %p now has %d references",
746 	    sa, sa->refcnt));
747 }
748 
749 /* Release a reference to SA.  */
750 void
sa_release(struct sa * sa)751 sa_release(struct sa *sa)
752 {
753 	struct cert_handler *handler;
754 	struct proto   *proto;
755 
756 	LOG_DBG((LOG_SA, 80, "sa_release: SA %p had %d references",
757 	    sa, sa->refcnt));
758 
759 	if (--sa->refcnt)
760 		return;
761 
762 	LOG_DBG((LOG_SA, 60, "sa_release: freeing SA %p", sa));
763 
764 	while ((proto = TAILQ_FIRST(&sa->protos)) != 0)
765 		proto_free(proto);
766 	if (sa->data) {
767 		if (sa->doi && sa->doi->free_sa_data)
768 			sa->doi->free_sa_data(sa->data);
769 		free(sa->data);
770 	}
771 	if (sa->id_i)
772 		free(sa->id_i);
773 	if (sa->id_r)
774 		free(sa->id_r);
775 	if (sa->recv_cert) {
776 		handler = cert_get(sa->recv_certtype);
777 		if (handler)
778 			handler->cert_free(sa->recv_cert);
779 	}
780 	if (sa->sent_cert) {
781 		handler = cert_get(sa->sent_certtype);
782 		if (handler)
783 			handler->cert_free(sa->sent_cert);
784 	}
785 	if (sa->recv_key)
786 		key_free(sa->recv_keytype, ISAKMP_KEYTYPE_PUBLIC,
787 		    sa->recv_key);
788 	if (sa->keynote_key)
789 		free(sa->keynote_key);	/* This is just a string */
790 	if (sa->policy_id != -1)
791 		kn_close(sa->policy_id);
792 	if (sa->name)
793 		free(sa->name);
794 	if (sa->keystate)
795 		free(sa->keystate);
796 	if (sa->nat_t_keepalive)
797 		timer_remove_event(sa->nat_t_keepalive);
798 	if (sa->dpd_event)
799 		timer_remove_event(sa->dpd_event);
800 	if (sa->transport)
801 		transport_release(sa->transport);
802 	free(sa);
803 }
804 
805 /*
806  * Rehash the ISAKMP SA this MSG is negotiating with the responder cookie
807  * filled in.
808  */
809 void
sa_isakmp_upgrade(struct message * msg)810 sa_isakmp_upgrade(struct message *msg)
811 {
812 	struct sa      *sa = TAILQ_FIRST(&msg->exchange->sa_list);
813 
814 	sa_remove(sa);
815 	GET_ISAKMP_HDR_RCOOKIE(msg->iov[0].iov_base,
816 	    sa->cookies + ISAKMP_HDR_ICOOKIE_LEN);
817 
818 	/*
819 	 * We don't install a transport in the initiator case as we don't know
820 	 * what local address will be chosen.  Do it now instead.
821          */
822 	sa->transport = msg->transport;
823 	transport_reference(sa->transport);
824 	sa_enter(sa);
825 }
826 
827 #define ATTRS_SIZE (IKE_ATTR_BLOCK_SIZE + 1)	/* XXX Should be dynamic.  */
828 
829 struct attr_validation_state {
830 	u_int8_t       *attrp[ATTRS_SIZE];
831 	u_int8_t        checked[ATTRS_SIZE];
832 	int             phase;	/* IKE (1) or IPSEC (2) attrs? */
833 	int             mode;	/* 0 = 'load', 1 = check */
834 };
835 
836 /* Validate an attribute. Return 0 on match.  */
837 static int
sa_validate_xf_attrs(u_int16_t type,u_int8_t * value,u_int16_t len,void * arg)838 sa_validate_xf_attrs(u_int16_t type, u_int8_t *value, u_int16_t len,
839     void *arg)
840 {
841 	struct attr_validation_state *avs =
842 	    (struct attr_validation_state *)arg;
843 
844 	LOG_DBG((LOG_SA, 95, "sa_validate_xf_attrs: phase %d mode %d type %d "
845 	    "len %d", avs->phase, avs->mode, type, len));
846 
847 	/* Make sure the phase and type are valid.  */
848 	if (avs->phase == 1) {
849 		if (type < IKE_ATTR_ENCRYPTION_ALGORITHM ||
850 		    type > IKE_ATTR_BLOCK_SIZE)
851 			return 1;
852 	} else if (avs->phase == 2) {
853 		if (type < IPSEC_ATTR_SA_LIFE_TYPE ||
854 		    type > IPSEC_ATTR_ECN_TUNNEL)
855 			return 1;
856 	} else
857 		return 1;
858 
859 	if (avs->mode == 0) {	/* Load attrs.  */
860 		avs->attrp[type] = value;
861 		return 0;
862 	}
863 	/* Checking for a missing attribute is an immediate failure.  */
864 	if (!avs->attrp[type])
865 		return 1;
866 
867 	/* Match the loaded attribute against this one, mark it as checked.  */
868 	avs->checked[type]++;
869 	return memcmp(avs->attrp[type], value, len);
870 }
871 
872 /*
873  * This function is used to validate the returned proposal (protection suite)
874  * we get from the responder against a proposal we sent. Only run as initiator.
875  * We return 0 if a match is found (in any transform of this proposal), 1
876  * otherwise. Also see note in sa_add_transform() below.
877  */
878 static int
sa_validate_proto_xf(struct proto * match,struct payload * xf,int phase)879 sa_validate_proto_xf(struct proto *match, struct payload *xf, int phase)
880 {
881 	struct attr_validation_state *avs;
882 	struct proto_attr *pa;
883 	int             found = 0;
884 	size_t          i;
885 	u_int8_t        xf_id;
886 
887 	if (!match->xf_cnt)
888 		return 0;
889 
890 	if (match->proto != GET_ISAKMP_PROP_PROTO(xf->context->p)) {
891 		LOG_DBG((LOG_SA, 70, "sa_validate_proto_xf: proto %p (#%d) "
892 		    "protocol mismatch", match, match->no));
893 		return 1;
894 	}
895 	avs = (struct attr_validation_state *)calloc(1, sizeof *avs);
896 	if (!avs) {
897 		log_error("sa_validate_proto_xf: calloc (1, %lu)",
898 		    (unsigned long)sizeof *avs);
899 		return 1;
900 	}
901 	avs->phase = phase;
902 
903 	/* Load the "proposal candidate" attribute set.  */
904 	(void) attribute_map(xf->p + ISAKMP_TRANSFORM_SA_ATTRS_OFF,
905 	    GET_ISAKMP_GEN_LENGTH(xf->p) - ISAKMP_TRANSFORM_SA_ATTRS_OFF,
906 	    sa_validate_xf_attrs, avs);
907 	xf_id = GET_ISAKMP_TRANSFORM_ID(xf->p);
908 
909 	/* Check against the transforms we suggested.  */
910 	avs->mode++;
911 	for (pa = TAILQ_FIRST(&match->xfs); pa && !found;
912 	    pa = TAILQ_NEXT(pa, next)) {
913 		if (xf_id != GET_ISAKMP_TRANSFORM_ID(pa->attrs))
914 			continue;
915 
916 		bzero(avs->checked, sizeof avs->checked);
917 		if (attribute_map(pa->attrs + ISAKMP_TRANSFORM_SA_ATTRS_OFF,
918 		    pa->len - ISAKMP_TRANSFORM_SA_ATTRS_OFF,
919 		    sa_validate_xf_attrs, avs) == 0)
920 			found++;
921 
922 		LOG_DBG((LOG_SA, 80, "sa_validate_proto_xf: attr_map "
923 		    "xf %p proto %p pa %p found %d", xf, match, pa, found));
924 
925 		if (!found)
926 			continue;
927 
928 		/*
929 		 * Require all attributes present and checked.  XXX perhaps
930 		 * not?
931 		 */
932 		for (i = 0; i < sizeof avs->checked; i++)
933 			if (avs->attrp[i] && !avs->checked[i])
934 				found = 0;
935 
936 		LOG_DBG((LOG_SA, 80, "sa_validate_proto_xf: req_attr "
937 		    "xf %p proto %p pa %p found %d", xf, match, pa, found));
938 	}
939 	free(avs);
940 	return found ? 0 : 1;
941 }
942 
943 /*
944  * Register the chosen transform XF into SA.  As a side effect set PROTOP
945  * to point at the corresponding proto structure.  INITIATOR is true if we
946  * are the initiator.
947  */
948 int
sa_add_transform(struct sa * sa,struct payload * xf,int initiator,struct proto ** protop)949 sa_add_transform(struct sa *sa, struct payload *xf, int initiator,
950     struct proto **protop)
951 {
952 	struct proto   *proto;
953 	struct payload *prop = xf->context;
954 
955 	*protop = 0;
956 	if (!initiator) {
957 		proto = calloc(1, sizeof *proto);
958 		if (!proto)
959 			log_error("sa_add_transform: calloc (1, %lu) failed",
960 			    (unsigned long)sizeof *proto);
961 	} else {
962 		/*
963 		 * RFC 2408, section 4.2 states the responder SHOULD use the
964 		 * proposal number from the initiator (i.e us), in it's
965 		 * selected proposal to make this lookup easier. Most vendors
966 		 * follow this. One noted exception is the CiscoPIX (and
967 		 * perhaps other Cisco products).
968 		 *
969 		 * We start by matching on the proposal number, as before.
970 		 */
971 		for (proto = TAILQ_FIRST(&sa->protos);
972 		    proto && proto->no != GET_ISAKMP_PROP_NO(prop->p);
973 		    proto = TAILQ_NEXT(proto, link))
974 			;
975 		/*
976 		 * If we did not find a match, search through all proposals
977 		 * and xforms.
978 		 */
979 		if (!proto || sa_validate_proto_xf(proto, xf, sa->phase) != 0)
980 			for (proto = TAILQ_FIRST(&sa->protos);
981 			    proto && sa_validate_proto_xf(proto, xf, sa->phase) != 0;
982 			    proto = TAILQ_NEXT(proto, link))
983 				;
984 	}
985 	if (!proto)
986 		return -1;
987 	*protop = proto;
988 
989 	/* Allocate DOI-specific part.  */
990 	if (!initiator) {
991 		proto->data = calloc(1, sa->doi->proto_size);
992 		if (!proto->data) {
993 			log_error("sa_add_transform: calloc (1, %lu) failed",
994 			    (unsigned long)sa->doi->proto_size);
995 			goto cleanup;
996 		}
997 	}
998 	proto->no = GET_ISAKMP_PROP_NO(prop->p);
999 	proto->proto = GET_ISAKMP_PROP_PROTO(prop->p);
1000 	proto->spi_sz[0] = GET_ISAKMP_PROP_SPI_SZ(prop->p);
1001 	if (proto->spi_sz[0]) {
1002 		proto->spi[0] = malloc(proto->spi_sz[0]);
1003 		if (!proto->spi[0])
1004 			goto cleanup;
1005 		memcpy(proto->spi[0], prop->p + ISAKMP_PROP_SPI_OFF,
1006 		    proto->spi_sz[0]);
1007 	}
1008 	proto->chosen = xf;
1009 	proto->sa = sa;
1010 	proto->id = GET_ISAKMP_TRANSFORM_ID(xf->p);
1011 	if (!initiator)
1012 		TAILQ_INSERT_TAIL(&sa->protos, proto, link);
1013 
1014 	/* Let the DOI get at proto for initializing its own data.  */
1015 	if (sa->doi->proto_init)
1016 		sa->doi->proto_init(proto, 0);
1017 
1018 	LOG_DBG((LOG_SA, 80,
1019 	    "sa_add_transform: "
1020 	    "proto %p no %d proto %d chosen %p sa %p id %d",
1021 	    proto, proto->no, proto->proto, proto->chosen, proto->sa,
1022 	    proto->id));
1023 
1024 	return 0;
1025 
1026 cleanup:
1027 	if (!initiator) {
1028 		if (proto->data)
1029 			free(proto->data);
1030 		free(proto);
1031 	}
1032 	*protop = 0;
1033 	return -1;
1034 }
1035 
1036 /* Delete an SA.  Tell the peer if NOTIFY is set.  */
1037 void
sa_delete(struct sa * sa,int notify)1038 sa_delete(struct sa *sa, int notify)
1039 {
1040 	if (notify)
1041 		message_send_delete(sa);
1042 	sa_free(sa);
1043 }
1044 
1045 
1046 /* Teardown all SAs.  */
1047 void
sa_teardown_all(void)1048 sa_teardown_all(void)
1049 {
1050 	int             i;
1051 	struct sa      *sa, *next = 0;
1052 
1053 	LOG_DBG((LOG_SA, 70, "sa_teardown_all:"));
1054 	/* Get Phase 2 SAs.  */
1055 	for (i = 0; i <= bucket_mask; i++)
1056 		for (sa = LIST_FIRST(&sa_tab[i]); sa; sa = next) {
1057 			next = LIST_NEXT(sa, link);
1058 			if (sa->phase == 2) {
1059 				/*
1060 				 * Teardown the phase 2 SAs by name, similar
1061 				 * to ui_teardown.
1062 				 */
1063 				LOG_DBG((LOG_SA, 70,
1064 				    "sa_teardown_all: tearing down SA %s",
1065 				    sa->name ? sa->name : "<unnamed>"));
1066 				if (sa->name)
1067 					connection_teardown(sa->name);
1068 				sa_delete(sa, 1);
1069 			}
1070 		}
1071 }
1072 
1073 /*
1074  * This function will get called when we are closing in on the death time of SA
1075  */
1076 static void
sa_soft_expire(void * v_sa)1077 sa_soft_expire(void *v_sa)
1078 {
1079 	struct sa      *sa = v_sa;
1080 
1081 	sa->soft_death = 0;
1082 	sa_release(sa);
1083 
1084 	if ((sa->flags & (SA_FLAG_STAYALIVE | SA_FLAG_REPLACED)) ==
1085 	    SA_FLAG_STAYALIVE)
1086 		exchange_establish(sa->name, 0, 0);
1087 	else
1088 		/*
1089 		 * Start to watch the use of this SA, so a renegotiation can
1090 		 * happen as soon as it is shown to be alive.
1091 		 */
1092 		sa->flags |= SA_FLAG_FADING;
1093 }
1094 
1095 /* SA has passed its best before date.  */
1096 static void
sa_hard_expire(void * v_sa)1097 sa_hard_expire(void *v_sa)
1098 {
1099 	struct sa      *sa = v_sa;
1100 
1101 	sa->death = 0;
1102 	sa_release(sa);
1103 
1104 	if ((sa->flags & (SA_FLAG_STAYALIVE | SA_FLAG_REPLACED)) ==
1105 	    SA_FLAG_STAYALIVE)
1106 		exchange_establish(sa->name, 0, 0);
1107 
1108 	sa_delete(sa, 1);
1109 }
1110 
1111 void
sa_reinit(void)1112 sa_reinit(void)
1113 {
1114 	struct sa      *sa;
1115 	char           *tag;
1116 	int             i;
1117 
1118 	/* For now; only do this if we have the proper tag configured.  */
1119 	tag = conf_get_str("General", "Renegotiate-on-HUP");
1120 	if (!tag)
1121 		return;
1122 
1123 	LOG_DBG((LOG_SA, 30, "sa_reinit: renegotiating active connections"));
1124 
1125 	/*
1126 	 * Get phase 2 SAs. Soft expire those without active exchanges.  Do
1127 	 * not touch a phase 2 SA where the soft expiration is not set, ie.
1128 	 * the SA is not yet established.
1129 	 */
1130 	for (i = 0; i <= bucket_mask; i++)
1131 		for (sa = LIST_FIRST(&sa_tab[i]); sa; sa = LIST_NEXT(sa, link))
1132 			if (sa->phase == 2)
1133 				if (exchange_lookup_by_name(sa->name,
1134 				    sa->phase) == 0 && sa->soft_death) {
1135 					timer_remove_event(sa->soft_death);
1136 					sa_soft_expire(sa);
1137 				}
1138 }
1139 
1140 /*
1141  * Get an SA attribute's flag value out of textual description.
1142  */
1143 int
sa_flag(char * attr)1144 sa_flag(char *attr)
1145 {
1146 	static struct sa_flag_map {
1147 		char           *name;
1148 		int             flag;
1149 	} sa_flag_map[] = {
1150 		{
1151 			"active-only", SA_FLAG_ACTIVE_ONLY
1152 		},
1153 
1154 		/*
1155 		 * Below this point are flags that are internal to the
1156 		 * implementation.
1157 		 */
1158 		{
1159 			"__ondemand", SA_FLAG_ONDEMAND
1160 		},
1161 		{
1162 			"ikecfg", SA_FLAG_IKECFG
1163 		},
1164 	};
1165 	size_t	i;
1166 
1167 	for (i = 0; i < sizeof sa_flag_map / sizeof sa_flag_map[0]; i++)
1168 		if (strcasecmp(attr, sa_flag_map[i].name) == 0)
1169 			return sa_flag_map[i].flag;
1170 	log_print("sa_flag: attribute \"%s\" unknown", attr);
1171 	return 0;
1172 }
1173 
1174 /* Mark SA as replaced.  */
1175 void
sa_mark_replaced(struct sa * sa)1176 sa_mark_replaced(struct sa *sa)
1177 {
1178 	LOG_DBG((LOG_SA, 60, "sa_mark_replaced: SA %p (%s) marked as replaced",
1179 	    sa, sa->name ? sa->name : "unnamed"));
1180 	if (sa->dpd_event) {
1181 		timer_remove_event(sa->dpd_event);
1182 		sa->dpd_event = 0;
1183 	}
1184 	sa->flags |= SA_FLAG_REPLACED;
1185 }
1186 
1187 /*
1188  * Setup expiration timers for SA.  This is used for ISAKMP SAs, but also
1189  * possible to use for application SAs if the application does not deal
1190  * with expirations itself.  An example is the Linux FreeS/WAN KLIPS IPsec
1191  * stack.
1192  */
1193 int
sa_setup_expirations(struct sa * sa)1194 sa_setup_expirations(struct sa *sa)
1195 {
1196 	struct timeval  expiration;
1197 	u_int64_t       seconds = sa->seconds;
1198 
1199 	/*
1200 	 * Set the soft timeout to a random percentage between 85 & 95 of
1201 	 * the negotiated lifetime to break strictly synchronized
1202 	 * renegotiations.  This works better when the randomization is on the
1203 	 * order of processing plus network-roundtrip times, or larger.
1204 	 * I.e. it depends on configuration and negotiated lifetimes.
1205 	 * It is not good to do the decrease on the hard timeout, because then
1206 	 * we may drop our SA before our peer.
1207 	 * XXX Better scheme to come?
1208          */
1209 	if (!sa->soft_death) {
1210 		gettimeofday(&expiration, 0);
1211 		/*
1212 		 * XXX This should probably be configuration controlled
1213 		 * somehow.
1214 		 */
1215 		seconds = sa->seconds * (850 + rand_32() % 100) / 1000;
1216 		LOG_DBG((LOG_TIMER, 95,
1217 		    "sa_setup_expirations: SA %p soft timeout in %llu seconds",
1218 		    sa, seconds));
1219 		expiration.tv_sec += seconds;
1220 		sa->soft_death = timer_add_event("sa_soft_expire",
1221 		    sa_soft_expire, sa, &expiration);
1222 		if (!sa->soft_death) {
1223 			/* If we don't give up we might start leaking...  */
1224 			sa_delete(sa, 1);
1225 			return -1;
1226 		}
1227 		sa_reference(sa);
1228 	}
1229 	if (!sa->death) {
1230 		gettimeofday(&expiration, 0);
1231 		LOG_DBG((LOG_TIMER, 95,
1232 		    "sa_setup_expirations: SA %p hard timeout in %llu seconds",
1233 		    sa, sa->seconds));
1234 		expiration.tv_sec += sa->seconds;
1235 		sa->death = timer_add_event("sa_hard_expire", sa_hard_expire,
1236 		    sa, &expiration);
1237 		if (!sa->death) {
1238 			/* If we don't give up we might start leaking...  */
1239 			sa_delete(sa, 1);
1240 			return -1;
1241 		}
1242 		sa_reference(sa);
1243 	}
1244 	return 0;
1245 }
1246