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