xref: /titanic_50/usr/src/uts/common/inet/ip/sadb.c (revision 35fe197b91640f2efc8c0b3849eee882e373c729)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2006 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #pragma ident	"%Z%%M%	%I%	%E% SMI"
27 
28 #include <sys/types.h>
29 #include <sys/stream.h>
30 #include <sys/stropts.h>
31 #include <sys/ddi.h>
32 #include <sys/debug.h>
33 #include <sys/cmn_err.h>
34 #include <sys/stream.h>
35 #include <sys/strlog.h>
36 #include <sys/kmem.h>
37 #include <sys/sunddi.h>
38 #include <sys/tihdr.h>
39 #include <sys/atomic.h>
40 #include <sys/socket.h>
41 #include <sys/sysmacros.h>
42 #include <sys/crypto/common.h>
43 #include <sys/crypto/api.h>
44 #include <sys/zone.h>
45 #include <netinet/in.h>
46 #include <net/if.h>
47 #include <net/pfkeyv2.h>
48 #include <inet/common.h>
49 #include <netinet/ip6.h>
50 #include <inet/ip.h>
51 #include <inet/ip6.h>
52 #include <inet/ipsec_info.h>
53 #include <inet/ipsec_impl.h>
54 #include <inet/tcp.h>
55 #include <inet/sadb.h>
56 #include <inet/ipsecah.h>
57 #include <inet/ipsecesp.h>
58 #include <sys/random.h>
59 #include <sys/dlpi.h>
60 #include <sys/iphada.h>
61 #include <inet/ip_if.h>
62 #include <inet/ipdrop.h>
63 #include <inet/ipclassifier.h>
64 #include <inet/sctp_ip.h>
65 
66 /*
67  * This source file contains Security Association Database (SADB) common
68  * routines.  They are linked in with the AH module.  Since AH has no chance
69  * of falling under export control, it was safe to link it in there.
70  */
71 
72 /* Packet dropper for generic SADB drops. */
73 static ipdropper_t sadb_dropper;
74 
75 static mblk_t *sadb_extended_acquire(ipsec_selector_t *, ipsec_policy_t *,
76     ipsec_action_t *, uint32_t, uint32_t);
77 static void sadb_ill_df(ill_t *, mblk_t *, isaf_t *, int, boolean_t);
78 static ipsa_t *sadb_torch_assoc(isaf_t *, ipsa_t *, boolean_t, mblk_t **);
79 static void sadb_drain_torchq(queue_t *q, mblk_t *);
80 static void sadb_destroy_acqlist(iacqf_t **, uint_t, boolean_t);
81 static void sadb_destroy(sadb_t *sp);
82 
83 static time_t sadb_add_time(time_t base, uint64_t delta);
84 
85 /*
86  * ipsacq_maxpackets is defined here to make it tunable
87  * from /etc/system.
88  */
89 extern uint64_t ipsacq_maxpackets;
90 
91 #define	SET_EXPIRE(sa, delta, exp) {				\
92 	if (((sa)->ipsa_ ## delta) != 0) {				\
93 		(sa)->ipsa_ ## exp = sadb_add_time((sa)->ipsa_addtime,	\
94 			(sa)->ipsa_ ## delta);				\
95 	}								\
96 }
97 
98 #define	UPDATE_EXPIRE(sa, delta, exp) {					\
99 	if (((sa)->ipsa_ ## delta) != 0) {				\
100 		time_t tmp = sadb_add_time((sa)->ipsa_usetime,		\
101 			(sa)->ipsa_ ## delta);				\
102 		if (((sa)->ipsa_ ## exp) == 0)				\
103 			(sa)->ipsa_ ## exp = tmp;			\
104 		else							\
105 			(sa)->ipsa_ ## exp = 				\
106 			    MIN((sa)->ipsa_ ## exp, tmp); 		\
107 	}								\
108 }
109 
110 
111 /* wrap the macro so we can pass it as a function pointer */
112 void
113 sadb_sa_refrele(void *target)
114 {
115 	IPSA_REFRELE(((ipsa_t *)target));
116 }
117 
118 /*
119  * We presume that sizeof (long) == sizeof (time_t) and that time_t is
120  * a signed type.
121  */
122 #define	TIME_MAX LONG_MAX
123 
124 /*
125  * PF_KEY gives us lifetimes in uint64_t seconds.  We presume that
126  * time_t is defined to be a signed type with the same range as
127  * "long".  On ILP32 systems, we thus run the risk of wrapping around
128  * at end of time, as well as "overwrapping" the clock back around
129  * into a seemingly valid but incorrect future date earlier than the
130  * desired expiration.
131  *
132  * In order to avoid odd behavior (either negative lifetimes or loss
133  * of high order bits) when someone asks for bizarrely long SA
134  * lifetimes, we do a saturating add for expire times.
135  *
136  * We presume that ILP32 systems will be past end of support life when
137  * the 32-bit time_t overflows (a dangerous assumption, mind you..).
138  *
139  * On LP64, 2^64 seconds are about 5.8e11 years, at which point we
140  * will hopefully have figured out clever ways to avoid the use of
141  * fixed-sized integers in computation.
142  */
143 static time_t
144 sadb_add_time(time_t base, uint64_t delta)
145 {
146 	time_t sum;
147 
148 	/*
149 	 * Clip delta to the maximum possible time_t value to
150 	 * prevent "overwrapping" back into a shorter-than-desired
151 	 * future time.
152 	 */
153 	if (delta > TIME_MAX)
154 		delta = TIME_MAX;
155 	/*
156 	 * This sum may still overflow.
157 	 */
158 	sum = base + delta;
159 
160 	/*
161 	 * .. so if the result is less than the base, we overflowed.
162 	 */
163 	if (sum < base)
164 		sum = TIME_MAX;
165 
166 	return (sum);
167 }
168 
169 /*
170  * Callers of this function have already created a working security
171  * association, and have found the appropriate table & hash chain.  All this
172  * function does is check duplicates, and insert the SA.  The caller needs to
173  * hold the hash bucket lock and increment the refcnt before insertion.
174  *
175  * Return 0 if success, EEXIST if collision.
176  */
177 int
178 sadb_insertassoc(ipsa_t *ipsa, isaf_t *bucket)
179 {
180 	ipsa_t **ptpn = NULL;
181 	ipsa_t *walker;
182 	boolean_t unspecsrc;
183 
184 	ASSERT(MUTEX_HELD(&bucket->isaf_lock));
185 
186 	unspecsrc = IPSA_IS_ADDR_UNSPEC(ipsa->ipsa_srcaddr, ipsa->ipsa_addrfam);
187 
188 	walker = bucket->isaf_ipsa;
189 	ASSERT(walker == NULL || ipsa->ipsa_addrfam == walker->ipsa_addrfam);
190 
191 	/*
192 	 * Find insertion point (pointed to with **ptpn).  Insert at the head
193 	 * of the list unless there's an unspecified source address, then
194 	 * insert it after the last SA with a specified source address.
195 	 *
196 	 * BTW, you'll have to walk the whole chain, matching on {DST, SPI}
197 	 * checking for collisions.
198 	 */
199 
200 	while (walker != NULL) {
201 		if (IPSA_ARE_ADDR_EQUAL(walker->ipsa_dstaddr,
202 		    ipsa->ipsa_dstaddr, ipsa->ipsa_addrfam)) {
203 			if (walker->ipsa_spi == ipsa->ipsa_spi)
204 				return (EEXIST);
205 
206 			mutex_enter(&walker->ipsa_lock);
207 			if (ipsa->ipsa_state == IPSA_STATE_MATURE &&
208 			    (walker->ipsa_flags & IPSA_F_USED) &&
209 			    ((walker->ipsa_unique_id &
210 				walker->ipsa_unique_mask) ==
211 				(ipsa->ipsa_unique_id &
212 				    ipsa->ipsa_unique_mask))) {
213 				walker->ipsa_flags |= IPSA_F_CINVALID;
214 			}
215 			mutex_exit(&walker->ipsa_lock);
216 		}
217 
218 		if (ptpn == NULL && unspecsrc) {
219 			if (IPSA_IS_ADDR_UNSPEC(walker->ipsa_srcaddr,
220 			    walker->ipsa_addrfam))
221 				ptpn = walker->ipsa_ptpn;
222 			else if (walker->ipsa_next == NULL)
223 				ptpn = &walker->ipsa_next;
224 		}
225 
226 		walker = walker->ipsa_next;
227 	}
228 
229 	if (ptpn == NULL)
230 		ptpn = &bucket->isaf_ipsa;
231 	ipsa->ipsa_next = *ptpn;
232 	ipsa->ipsa_ptpn = ptpn;
233 	if (ipsa->ipsa_next != NULL)
234 		ipsa->ipsa_next->ipsa_ptpn = &ipsa->ipsa_next;
235 	*ptpn = ipsa;
236 	ipsa->ipsa_linklock = &bucket->isaf_lock;
237 
238 	return (0);
239 }
240 
241 /*
242  * Free a security association.  Its reference count is 0, which means
243  * I must free it.  The SA must be unlocked and must not be linked into
244  * any fanout list.
245  */
246 static void
247 sadb_freeassoc(ipsa_t *ipsa)
248 {
249 	ASSERT(!MUTEX_HELD(&ipsa->ipsa_lock));
250 	ASSERT(ipsa->ipsa_refcnt == 0);
251 	ASSERT(ipsa->ipsa_next == NULL);
252 	ASSERT(ipsa->ipsa_ptpn == NULL);
253 
254 	ip_drop_packet(sadb_clear_lpkt(ipsa), B_TRUE, NULL, NULL,
255 	    &ipdrops_sadb_inlarval_timeout, &sadb_dropper);
256 
257 	mutex_enter(&ipsa->ipsa_lock);
258 
259 	if (ipsa->ipsa_natt_ka_timer != 0)
260 		(void) quntimeout(ipsa->ipsa_natt_q, ipsa->ipsa_natt_ka_timer);
261 
262 	ipsec_destroy_ctx_tmpl(ipsa, IPSEC_ALG_AUTH);
263 	ipsec_destroy_ctx_tmpl(ipsa, IPSEC_ALG_ENCR);
264 	mutex_exit(&ipsa->ipsa_lock);
265 
266 	/* bzero() these fields for paranoia's sake. */
267 	if (ipsa->ipsa_authkey != NULL) {
268 		bzero(ipsa->ipsa_authkey, ipsa->ipsa_authkeylen);
269 		kmem_free(ipsa->ipsa_authkey, ipsa->ipsa_authkeylen);
270 	}
271 	if (ipsa->ipsa_encrkey != NULL) {
272 		bzero(ipsa->ipsa_encrkey, ipsa->ipsa_encrkeylen);
273 		kmem_free(ipsa->ipsa_encrkey, ipsa->ipsa_encrkeylen);
274 	}
275 	if (ipsa->ipsa_src_cid != NULL) {
276 		IPSID_REFRELE(ipsa->ipsa_src_cid);
277 	}
278 	if (ipsa->ipsa_dst_cid != NULL) {
279 		IPSID_REFRELE(ipsa->ipsa_dst_cid);
280 	}
281 	if (ipsa->ipsa_proxy_cid != NULL) {
282 		IPSID_REFRELE(ipsa->ipsa_proxy_cid);
283 	}
284 	if (ipsa->ipsa_integ != NULL)
285 		kmem_free(ipsa->ipsa_integ, ipsa->ipsa_integlen);
286 	if (ipsa->ipsa_sens != NULL)
287 		kmem_free(ipsa->ipsa_sens, ipsa->ipsa_senslen);
288 
289 	mutex_destroy(&ipsa->ipsa_lock);
290 	kmem_free(ipsa, sizeof (*ipsa));
291 }
292 
293 /*
294  * Unlink a security association from a hash bucket.  Assume the hash bucket
295  * lock is held, but the association's lock is not.
296  *
297  * Note that we do not bump the bucket's generation number here because
298  * we might not be making a visible change to the set of visible SA's.
299  * All callers MUST bump the bucket's generation number before they unlock
300  * the bucket if they use sadb_unlinkassoc to permanetly remove an SA which
301  * was present in the bucket at the time it was locked.
302  */
303 void
304 sadb_unlinkassoc(ipsa_t *ipsa)
305 {
306 	ASSERT(ipsa->ipsa_linklock != NULL);
307 	ASSERT(MUTEX_HELD(ipsa->ipsa_linklock));
308 
309 	/* These fields are protected by the link lock. */
310 	*(ipsa->ipsa_ptpn) = ipsa->ipsa_next;
311 	if (ipsa->ipsa_next != NULL) {
312 		ipsa->ipsa_next->ipsa_ptpn = ipsa->ipsa_ptpn;
313 		ipsa->ipsa_next = NULL;
314 	}
315 
316 	ipsa->ipsa_ptpn = NULL;
317 
318 	/* This may destroy the SA. */
319 	IPSA_REFRELE(ipsa);
320 }
321 
322 /*
323  * Create a larval security association with the specified SPI.	 All other
324  * fields are zeroed.
325  */
326 static ipsa_t *
327 sadb_makelarvalassoc(uint32_t spi, uint32_t *src, uint32_t *dst, int addrfam)
328 {
329 	ipsa_t *newbie;
330 
331 	/*
332 	 * Allocate...
333 	 */
334 
335 	newbie = (ipsa_t *)kmem_zalloc(sizeof (ipsa_t), KM_NOSLEEP);
336 	if (newbie == NULL) {
337 		/* Can't make new larval SA. */
338 		return (NULL);
339 	}
340 
341 	/* Assigned requested SPI, assume caller does SPI allocation magic. */
342 	newbie->ipsa_spi = spi;
343 
344 	/*
345 	 * Copy addresses...
346 	 */
347 
348 	IPSA_COPY_ADDR(newbie->ipsa_srcaddr, src, addrfam);
349 	IPSA_COPY_ADDR(newbie->ipsa_dstaddr, dst, addrfam);
350 
351 	newbie->ipsa_addrfam = addrfam;
352 
353 	/*
354 	 * Set common initialization values, including refcnt.
355 	 */
356 	mutex_init(&newbie->ipsa_lock, NULL, MUTEX_DEFAULT, NULL);
357 	newbie->ipsa_state = IPSA_STATE_LARVAL;
358 	newbie->ipsa_refcnt = 1;
359 	newbie->ipsa_freefunc = sadb_freeassoc;
360 
361 	/*
362 	 * There aren't a lot of other common initialization values, as
363 	 * they are copied in from the PF_KEY message.
364 	 */
365 
366 	return (newbie);
367 }
368 
369 /*
370  * Call me to initialize a security association fanout.
371  */
372 static int
373 sadb_init_fanout(isaf_t **tablep, uint_t size, int kmflag)
374 {
375 	isaf_t *table;
376 	int i;
377 
378 	table = (isaf_t *)kmem_alloc(size * sizeof (*table), kmflag);
379 	*tablep = table;
380 
381 	if (table == NULL)
382 		return (ENOMEM);
383 
384 	for (i = 0; i < size; i++) {
385 		mutex_init(&(table[i].isaf_lock), NULL, MUTEX_DEFAULT, NULL);
386 		table[i].isaf_ipsa = NULL;
387 		table[i].isaf_gen = 0;
388 	}
389 
390 	return (0);
391 }
392 
393 /*
394  * Call me to initialize an acquire fanout
395  */
396 static int
397 sadb_init_acfanout(iacqf_t **tablep, uint_t size, int kmflag)
398 {
399 	iacqf_t *table;
400 	int i;
401 
402 	table = (iacqf_t *)kmem_alloc(size * sizeof (*table), kmflag);
403 	*tablep = table;
404 
405 	if (table == NULL)
406 		return (ENOMEM);
407 
408 	for (i = 0; i < size; i++) {
409 		mutex_init(&(table[i].iacqf_lock), NULL, MUTEX_DEFAULT, NULL);
410 		table[i].iacqf_ipsacq = NULL;
411 	}
412 
413 	return (0);
414 }
415 
416 /*
417  * Attempt to initialize an SADB instance.  On failure, return ENOMEM;
418  * caller must clean up partial allocations.
419  */
420 static int
421 sadb_init_trial(sadb_t *sp, uint_t size, int kmflag)
422 {
423 	ASSERT(sp->sdb_of == NULL);
424 	ASSERT(sp->sdb_if == NULL);
425 	ASSERT(sp->sdb_acq == NULL);
426 
427 	sp->sdb_hashsize = size;
428 	if (sadb_init_fanout(&sp->sdb_of, size, kmflag) != 0)
429 		return (ENOMEM);
430 	if (sadb_init_fanout(&sp->sdb_if, size, kmflag) != 0)
431 		return (ENOMEM);
432 	if (sadb_init_acfanout(&sp->sdb_acq, size, kmflag) != 0)
433 		return (ENOMEM);
434 
435 	return (0);
436 }
437 
438 /*
439  * Call me to initialize an SADB instance; fall back to default size on failure.
440  */
441 static void
442 sadb_init(const char *name, sadb_t *sp, uint_t size, uint_t ver)
443 {
444 	ASSERT(sp->sdb_of == NULL);
445 	ASSERT(sp->sdb_if == NULL);
446 	ASSERT(sp->sdb_acq == NULL);
447 
448 	if (size < IPSEC_DEFAULT_HASH_SIZE)
449 		size = IPSEC_DEFAULT_HASH_SIZE;
450 
451 	if (sadb_init_trial(sp, size, KM_NOSLEEP) != 0) {
452 
453 		cmn_err(CE_WARN,
454 		    "Unable to allocate %u entry IPv%u %s SADB hash table",
455 		    size, ver, name);
456 
457 		sadb_destroy(sp);
458 		size = IPSEC_DEFAULT_HASH_SIZE;
459 		cmn_err(CE_WARN, "Falling back to %d entries", size);
460 		(void) sadb_init_trial(sp, size, KM_SLEEP);
461 	}
462 }
463 
464 
465 /*
466  * Initialize an SADB-pair.
467  */
468 void
469 sadbp_init(const char *name, sadbp_t *sp, int type, int size)
470 {
471 	sadb_init(name, &sp->s_v4, size, 4);
472 	sadb_init(name, &sp->s_v6, size, 6);
473 
474 	sp->s_satype = type;
475 
476 	ASSERT((type == SADB_SATYPE_AH) || (type == SADB_SATYPE_ESP));
477 	if (type == SADB_SATYPE_AH)
478 		ip_drop_register(&sadb_dropper, "IPsec SADB");
479 }
480 
481 /*
482  * Deliver a single SADB_DUMP message representing a single SA.  This is
483  * called many times by sadb_dump().
484  *
485  * If the return value of this is ENOBUFS (not the same as ENOMEM), then
486  * the caller should take that as a hint that dupb() on the "original answer"
487  * failed, and that perhaps the caller should try again with a copyb()ed
488  * "original answer".
489  */
490 static int
491 sadb_dump_deliver(queue_t *pfkey_q, mblk_t *original_answer, ipsa_t *ipsa,
492     sadb_msg_t *samsg)
493 {
494 	mblk_t *answer;
495 
496 	answer = dupb(original_answer);
497 	if (answer == NULL)
498 		return (ENOBUFS);
499 	answer->b_cont = sadb_sa2msg(ipsa, samsg);
500 	if (answer->b_cont == NULL) {
501 		freeb(answer);
502 		return (ENOMEM);
503 	}
504 
505 	/* Just do a putnext, and let keysock deal with flow control. */
506 	putnext(pfkey_q, answer);
507 	return (0);
508 }
509 
510 /*
511  * Common function to allocate and prepare a keysock_out_t M_CTL message.
512  */
513 mblk_t *
514 sadb_keysock_out(minor_t serial)
515 {
516 	mblk_t *mp;
517 	keysock_out_t *kso;
518 
519 	mp = allocb(sizeof (ipsec_info_t), BPRI_HI);
520 	if (mp != NULL) {
521 		mp->b_datap->db_type = M_CTL;
522 		mp->b_wptr += sizeof (ipsec_info_t);
523 		kso = (keysock_out_t *)mp->b_rptr;
524 		kso->ks_out_type = KEYSOCK_OUT;
525 		kso->ks_out_len = sizeof (*kso);
526 		kso->ks_out_serial = serial;
527 	}
528 
529 	return (mp);
530 }
531 
532 /*
533  * Perform an SADB_DUMP, spewing out every SA in an array of SA fanouts
534  * to keysock.
535  */
536 static int
537 sadb_dump_fanout(queue_t *pfkey_q, mblk_t *mp, minor_t serial, isaf_t *fanout,
538     int num_entries, boolean_t do_peers)
539 {
540 	int i, error = 0;
541 	mblk_t *original_answer;
542 	ipsa_t *walker;
543 	sadb_msg_t *samsg;
544 
545 	/*
546 	 * For each IPSA hash bucket do:
547 	 *	- Hold the mutex
548 	 *	- Walk each entry, doing an sadb_dump_deliver() on it.
549 	 */
550 	ASSERT(mp->b_cont != NULL);
551 	samsg = (sadb_msg_t *)mp->b_cont->b_rptr;
552 
553 	original_answer = sadb_keysock_out(serial);
554 	if (original_answer == NULL)
555 		return (ENOMEM);
556 
557 	for (i = 0; i < num_entries; i++) {
558 		mutex_enter(&fanout[i].isaf_lock);
559 		for (walker = fanout[i].isaf_ipsa; walker != NULL;
560 		    walker = walker->ipsa_next) {
561 			if (!do_peers && walker->ipsa_haspeer)
562 				continue;
563 			error = sadb_dump_deliver(pfkey_q, original_answer,
564 			    walker, samsg);
565 			if (error == ENOBUFS) {
566 				mblk_t *new_original_answer;
567 
568 				/* Ran out of dupb's.  Try a copyb. */
569 				new_original_answer = copyb(original_answer);
570 				if (new_original_answer == NULL) {
571 					error = ENOMEM;
572 				} else {
573 					freeb(original_answer);
574 					original_answer = new_original_answer;
575 					error = sadb_dump_deliver(pfkey_q,
576 					    original_answer, walker, samsg);
577 				}
578 			}
579 			if (error != 0)
580 				break;	/* out of for loop. */
581 		}
582 		mutex_exit(&fanout[i].isaf_lock);
583 		if (error != 0)
584 			break;	/* out of for loop. */
585 	}
586 
587 	freeb(original_answer);
588 	return (error);
589 }
590 
591 /*
592  * Dump an entire SADB; outbound first, then inbound.
593  */
594 
595 int
596 sadb_dump(queue_t *pfkey_q, mblk_t *mp, minor_t serial, sadb_t *sp)
597 {
598 	int error;
599 
600 	/* Dump outbound */
601 	error = sadb_dump_fanout(pfkey_q, mp, serial, sp->sdb_of,
602 	    sp->sdb_hashsize, B_TRUE);
603 	if (error)
604 		return (error);
605 
606 	/* Dump inbound */
607 	return sadb_dump_fanout(pfkey_q, mp, serial, sp->sdb_if,
608 	    sp->sdb_hashsize, B_FALSE);
609 }
610 
611 /*
612  * Generic sadb table walker.
613  *
614  * Call "walkfn" for each SA in each bucket in "table"; pass the
615  * bucket, the entry and "cookie" to the callback function.
616  * Take care to ensure that walkfn can delete the SA without screwing
617  * up our traverse.
618  *
619  * The bucket is locked for the duration of the callback, both so that the
620  * callback can just call sadb_unlinkassoc() when it wants to delete something,
621  * and so that no new entries are added while we're walking the list.
622  */
623 static void
624 sadb_walker(isaf_t *table, uint_t numentries,
625     void (*walkfn)(isaf_t *head, ipsa_t *entry, void *cookie),
626     void *cookie)
627 {
628 	int i;
629 	for (i = 0; i < numentries; i++) {
630 		ipsa_t *entry, *next;
631 
632 		mutex_enter(&table[i].isaf_lock);
633 
634 		for (entry = table[i].isaf_ipsa; entry != NULL;
635 		    entry = next) {
636 			next = entry->ipsa_next;
637 			(*walkfn)(&table[i], entry, cookie);
638 		}
639 		mutex_exit(&table[i].isaf_lock);
640 	}
641 }
642 
643 /*
644  * From the given SA, construct a dl_ct_ipsec_key and
645  * a dl_ct_ipsec structures to be sent to the adapter as part
646  * of a DL_CONTROL_REQ.
647  *
648  * ct_sa must point to the storage allocated for the key
649  * structure and must be followed by storage allocated
650  * for the SA information that must be sent to the driver
651  * as part of the DL_CONTROL_REQ request.
652  *
653  * The is_inbound boolean indicates whether the specified
654  * SA is part of an inbound SA table.
655  *
656  * Returns B_TRUE if the corresponding SA must be passed to
657  * a provider, B_FALSE otherwise; frees *mp if it returns B_FALSE.
658  */
659 static boolean_t
660 sadb_req_from_sa(ipsa_t *sa, mblk_t *mp, boolean_t is_inbound)
661 {
662 	dl_ct_ipsec_key_t *keyp;
663 	dl_ct_ipsec_t *sap;
664 	void *ct_sa = mp->b_wptr;
665 
666 	ASSERT(MUTEX_HELD(&sa->ipsa_lock));
667 
668 	keyp = (dl_ct_ipsec_key_t *)(ct_sa);
669 	sap = (dl_ct_ipsec_t *)(keyp + 1);
670 
671 	IPSECHW_DEBUG(IPSECHW_CAPAB, ("sadb_req_from_sa: "
672 	    "is_inbound = %d\n", is_inbound));
673 
674 	/* initialize flag */
675 	sap->sadb_sa_flags = 0;
676 	if (is_inbound) {
677 		sap->sadb_sa_flags |= DL_CT_IPSEC_INBOUND;
678 		/*
679 		 * If an inbound SA has a peer, then mark it has being
680 		 * an outbound SA as well.
681 		 */
682 		if (sa->ipsa_haspeer)
683 			sap->sadb_sa_flags |= DL_CT_IPSEC_OUTBOUND;
684 	} else {
685 		/*
686 		 * If an outbound SA has a peer, then don't send it,
687 		 * since we will send the copy from the inbound table.
688 		 */
689 		if (sa->ipsa_haspeer) {
690 			freemsg(mp);
691 			return (B_FALSE);
692 		}
693 		sap->sadb_sa_flags |= DL_CT_IPSEC_OUTBOUND;
694 	}
695 
696 	keyp->dl_key_spi = sa->ipsa_spi;
697 	bcopy(sa->ipsa_dstaddr, keyp->dl_key_dest_addr,
698 	    DL_CTL_IPSEC_ADDR_LEN);
699 	keyp->dl_key_addr_family = sa->ipsa_addrfam;
700 
701 	sap->sadb_sa_auth = sa->ipsa_auth_alg;
702 	sap->sadb_sa_encrypt = sa->ipsa_encr_alg;
703 
704 	sap->sadb_key_len_a = sa->ipsa_authkeylen;
705 	sap->sadb_key_bits_a = sa->ipsa_authkeybits;
706 	bcopy(sa->ipsa_authkey,
707 	    sap->sadb_key_data_a, sap->sadb_key_len_a);
708 
709 	sap->sadb_key_len_e = sa->ipsa_encrkeylen;
710 	sap->sadb_key_bits_e = sa->ipsa_encrkeybits;
711 	bcopy(sa->ipsa_encrkey,
712 	    sap->sadb_key_data_e, sap->sadb_key_len_e);
713 
714 	mp->b_wptr += sizeof (dl_ct_ipsec_t) + sizeof (dl_ct_ipsec_key_t);
715 	return (B_TRUE);
716 }
717 
718 /*
719  * Called from AH or ESP to format a message which will be used to inform
720  * IPsec-acceleration-capable ills of a SADB change.
721  * (It is not possible to send the message to IP directly from this function
722  * since the SA, if any, is locked during the call).
723  *
724  * dl_operation: DL_CONTROL_REQ operation (add, delete, update, etc)
725  * sa_type: identifies whether the operation applies to AH or ESP
726  *	(must be one of SADB_SATYPE_AH or SADB_SATYPE_ESP)
727  * sa: Pointer to an SA.  Must be non-NULL and locked
728  *	for ADD, DELETE, GET, and UPDATE operations.
729  * This function returns an mblk chain that must be passed to IP
730  * for forwarding to the IPsec capable providers.
731  */
732 mblk_t *
733 sadb_fmt_sa_req(uint_t dl_operation, uint_t sa_type, ipsa_t *sa,
734     boolean_t is_inbound)
735 {
736 	mblk_t *mp;
737 	dl_control_req_t *ctrl;
738 	boolean_t need_key = B_FALSE;
739 	mblk_t *ctl_mp = NULL;
740 	ipsec_ctl_t *ctl;
741 
742 	/*
743 	 * 1 allocate and initialize DL_CONTROL_REQ M_PROTO
744 	 * 2 if a key is needed for the operation
745 	 *    2.1 initialize key
746 	 *    2.2 if a full SA is needed for the operation
747 	 *	2.2.1 initialize full SA info
748 	 * 3 return message; caller will call ill_ipsec_capab_send_all()
749 	 * to send the resulting message to IPsec capable ills.
750 	 */
751 
752 	ASSERT(sa_type == SADB_SATYPE_AH || sa_type == SADB_SATYPE_ESP);
753 
754 	/*
755 	 * Allocate DL_CONTROL_REQ M_PROTO
756 	 * We allocate room for the SA even if it's not needed
757 	 * by some of the operations (for example flush)
758 	 */
759 	mp = allocb(sizeof (dl_control_req_t) +
760 	    sizeof (dl_ct_ipsec_key_t) + sizeof (dl_ct_ipsec_t), BPRI_HI);
761 	if (mp == NULL)
762 		return (NULL);
763 	mp->b_datap->db_type = M_PROTO;
764 
765 	/* initialize dl_control_req_t */
766 	ctrl = (dl_control_req_t *)mp->b_wptr;
767 	ctrl->dl_primitive = DL_CONTROL_REQ;
768 	ctrl->dl_operation = dl_operation;
769 	ctrl->dl_type = sa_type == SADB_SATYPE_AH ? DL_CT_IPSEC_AH :
770 	    DL_CT_IPSEC_ESP;
771 	ctrl->dl_key_offset = sizeof (dl_control_req_t);
772 	ctrl->dl_key_length = sizeof (dl_ct_ipsec_key_t);
773 	ctrl->dl_data_offset = sizeof (dl_control_req_t) +
774 	    sizeof (dl_ct_ipsec_key_t);
775 	ctrl->dl_data_length = sizeof (dl_ct_ipsec_t);
776 	mp->b_wptr += sizeof (dl_control_req_t);
777 
778 	if ((dl_operation == DL_CO_SET) || (dl_operation == DL_CO_DELETE)) {
779 		ASSERT(sa != NULL);
780 		ASSERT(MUTEX_HELD(&sa->ipsa_lock));
781 
782 		need_key = B_TRUE;
783 
784 		/*
785 		 * Initialize key and SA data. Note that for some
786 		 * operations the SA data is ignored by the provider
787 		 * (delete, etc.)
788 		 */
789 		if (!sadb_req_from_sa(sa, mp, is_inbound))
790 			return (NULL);
791 	}
792 
793 	/* construct control message */
794 	ctl_mp = allocb(sizeof (ipsec_ctl_t), BPRI_HI);
795 	if (ctl_mp == NULL) {
796 		cmn_err(CE_WARN, "sadb_fmt_sa_req: allocb failed\n");
797 		freemsg(mp);
798 		return (NULL);
799 	}
800 
801 	ctl_mp->b_datap->db_type = M_CTL;
802 	ctl_mp->b_wptr += sizeof (ipsec_ctl_t);
803 	ctl_mp->b_cont = mp;
804 
805 	ctl = (ipsec_ctl_t *)ctl_mp->b_rptr;
806 	ctl->ipsec_ctl_type = IPSEC_CTL;
807 	ctl->ipsec_ctl_len  = sizeof (ipsec_ctl_t);
808 	ctl->ipsec_ctl_sa_type = sa_type;
809 
810 	if (need_key) {
811 		/*
812 		 * Keep an additional reference on SA, since it will be
813 		 * needed by IP to send control messages corresponding
814 		 * to that SA from its perimeter. IP will do a
815 		 * IPSA_REFRELE when done with the request.
816 		 */
817 		ASSERT(MUTEX_HELD(&sa->ipsa_lock));
818 		IPSA_REFHOLD(sa);
819 		ctl->ipsec_ctl_sa = sa;
820 	} else
821 		ctl->ipsec_ctl_sa = NULL;
822 
823 	return (ctl_mp);
824 }
825 
826 
827 /*
828  * Called by sadb_ill_download() to dump the entries for a specific
829  * fanout table.  For each SA entry in the table passed as argument,
830  * use mp as a template and constructs a full DL_CONTROL message, and
831  * call ill_dlpi_send(), provided by IP, to send the resulting
832  * messages to the ill.
833  */
834 static void
835 sadb_ill_df(ill_t *ill, mblk_t *mp, isaf_t *fanout, int num_entries,
836     boolean_t is_inbound)
837 {
838 	ipsa_t *walker;
839 	mblk_t *nmp, *salist;
840 	int i, error = 0;
841 
842 	IPSECHW_DEBUG(IPSECHW_SADB, ("sadb_ill_df: fanout at 0x%p ne=%d\n",
843 	    (void *)fanout, num_entries));
844 	/*
845 	 * For each IPSA hash bucket do:
846 	 *	- Hold the mutex
847 	 *	- Walk each entry, sending a corresponding request to IP
848 	 *	  for it.
849 	 */
850 	ASSERT(mp->b_datap->db_type == M_PROTO);
851 
852 	for (i = 0; i < num_entries; i++) {
853 		mutex_enter(&fanout[i].isaf_lock);
854 		salist = NULL;
855 
856 		for (walker = fanout[i].isaf_ipsa; walker != NULL;
857 		    walker = walker->ipsa_next) {
858 			IPSECHW_DEBUG(IPSECHW_SADB,
859 			    ("sadb_ill_df: sending SA to ill via IP \n"));
860 			/*
861 			 * Duplicate the template mp passed and
862 			 * complete DL_CONTROL_REQ data.
863 			 * To be more memory efficient, we could use
864 			 * dupb() for the M_CTL and copyb() for the M_PROTO
865 			 * as the M_CTL, since the M_CTL is the same for
866 			 * every SA entry passed down to IP for the same ill.
867 			 *
868 			 * Note that copymsg/copyb ensure that the new mblk
869 			 * is at least as large as the source mblk even if it's
870 			 * not using all its storage -- therefore, nmp
871 			 * has trailing space for sadb_req_from_sa to add
872 			 * the SA-specific bits.
873 			 */
874 			mutex_enter(&walker->ipsa_lock);
875 			if (ipsec_capab_match(ill,
876 			    ill->ill_phyint->phyint_ifindex, ill->ill_isv6,
877 			    walker)) {
878 				nmp = copymsg(mp);
879 				if (nmp == NULL) {
880 					IPSECHW_DEBUG(IPSECHW_SADB,
881 					    ("sadb_ill_df: alloc error\n"));
882 					error = ENOMEM;
883 					mutex_exit(&walker->ipsa_lock);
884 					break;
885 				}
886 				if (sadb_req_from_sa(walker, nmp, is_inbound)) {
887 					nmp->b_next = salist;
888 					salist = nmp;
889 				}
890 			}
891 			mutex_exit(&walker->ipsa_lock);
892 		}
893 		mutex_exit(&fanout[i].isaf_lock);
894 		while (salist != NULL) {
895 			nmp = salist;
896 			salist = nmp->b_next;
897 			nmp->b_next = NULL;
898 			ill_dlpi_send(ill, nmp);
899 		}
900 		if (error != 0)
901 			break;	/* out of for loop. */
902 	}
903 }
904 
905 /*
906  * Called by ill_ipsec_capab_add(). Sends a copy of the SADB of
907  * the type specified by sa_type to the specified ill.
908  *
909  * We call for each fanout table defined by the SADB (one per
910  * protocol). sadb_ill_df() finally calls ill_dlpi_send() for
911  * each SADB entry in order to send a corresponding DL_CONTROL_REQ
912  * message to the ill.
913  */
914 void
915 sadb_ill_download(ill_t *ill, uint_t sa_type)
916 {
917 	mblk_t *protomp;	/* prototype message */
918 	dl_control_req_t *ctrl;
919 	sadbp_t *spp;
920 	sadb_t *sp;
921 	int dlt;
922 
923 	ASSERT(sa_type == SADB_SATYPE_AH || sa_type == SADB_SATYPE_ESP);
924 
925 	/*
926 	 * Allocate and initialize prototype answer. A duplicate for
927 	 * each SA is sent down to the interface.
928 	 */
929 
930 	/* DL_CONTROL_REQ M_PROTO mblk_t */
931 	protomp = allocb(sizeof (dl_control_req_t) +
932 	    sizeof (dl_ct_ipsec_key_t) + sizeof (dl_ct_ipsec_t), BPRI_HI);
933 	if (protomp == NULL)
934 		return;
935 	protomp->b_datap->db_type = M_PROTO;
936 
937 	dlt = (sa_type == SADB_SATYPE_AH) ? DL_CT_IPSEC_AH : DL_CT_IPSEC_ESP;
938 	spp = (sa_type == SADB_SATYPE_ESP) ? &esp_sadb : &ah_sadb;
939 
940 	ctrl = (dl_control_req_t *)protomp->b_wptr;
941 	ctrl->dl_primitive = DL_CONTROL_REQ;
942 	ctrl->dl_operation = DL_CO_SET;
943 	ctrl->dl_type = dlt;
944 	ctrl->dl_key_offset = sizeof (dl_control_req_t);
945 	ctrl->dl_key_length = sizeof (dl_ct_ipsec_key_t);
946 	ctrl->dl_data_offset = sizeof (dl_control_req_t) +
947 	    sizeof (dl_ct_ipsec_key_t);
948 	ctrl->dl_data_length = sizeof (dl_ct_ipsec_t);
949 	protomp->b_wptr += sizeof (dl_control_req_t);
950 
951 	/*
952 	 * then for each SADB entry, we fill out the dl_ct_ipsec_key_t
953 	 * and dl_ct_ipsec_t
954 	 */
955 	sp = ill->ill_isv6 ? &(spp->s_v6) : &(spp->s_v4);
956 	sadb_ill_df(ill, protomp, sp->sdb_of, sp->sdb_hashsize, B_FALSE);
957 	sadb_ill_df(ill, protomp, sp->sdb_if, sp->sdb_hashsize, B_TRUE);
958 	freemsg(protomp);
959 }
960 
961 /*
962  * Call me to free up a security association fanout.  Use the forever
963  * variable to indicate freeing up the SAs (forever == B_FALSE, e.g.
964  * an SADB_FLUSH message), or destroying everything (forever == B_TRUE,
965  * when a module is unloaded).
966  */
967 static void
968 sadb_destroyer(isaf_t **tablep, uint_t numentries, boolean_t forever)
969 {
970 	int i;
971 	isaf_t *table = *tablep;
972 
973 	if (table == NULL)
974 		return;
975 
976 	for (i = 0; i < numentries; i++) {
977 		mutex_enter(&table[i].isaf_lock);
978 		while (table[i].isaf_ipsa != NULL)
979 			sadb_unlinkassoc(table[i].isaf_ipsa);
980 		table[i].isaf_gen++;
981 		mutex_exit(&table[i].isaf_lock);
982 		if (forever)
983 			mutex_destroy(&(table[i].isaf_lock));
984 	}
985 
986 	if (forever) {
987 		*tablep = NULL;
988 		kmem_free(table, numentries * sizeof (*table));
989 	}
990 }
991 
992 /*
993  * Entry points to sadb_destroyer().
994  */
995 static void
996 sadb_flush(sadb_t *sp)
997 {
998 	/*
999 	 * Flush out each bucket, one at a time.  Were it not for keysock's
1000 	 * enforcement, there would be a subtlety where I could add on the
1001 	 * heels of a flush.  With keysock's enforcement, however, this
1002 	 * makes ESP's job easy.
1003 	 */
1004 	sadb_destroyer(&sp->sdb_of, sp->sdb_hashsize, B_FALSE);
1005 	sadb_destroyer(&sp->sdb_if, sp->sdb_hashsize, B_FALSE);
1006 
1007 	/* For each acquire, destroy it; leave the bucket mutex alone. */
1008 	sadb_destroy_acqlist(&sp->sdb_acq, sp->sdb_hashsize, B_FALSE);
1009 }
1010 
1011 static void
1012 sadb_destroy(sadb_t *sp)
1013 {
1014 	sadb_destroyer(&sp->sdb_of, sp->sdb_hashsize, B_TRUE);
1015 	sadb_destroyer(&sp->sdb_if, sp->sdb_hashsize, B_TRUE);
1016 
1017 	/* For each acquire, destroy it, including the bucket mutex. */
1018 	sadb_destroy_acqlist(&sp->sdb_acq, sp->sdb_hashsize, B_TRUE);
1019 
1020 	ASSERT(sp->sdb_of == NULL);
1021 	ASSERT(sp->sdb_if == NULL);
1022 	ASSERT(sp->sdb_acq == NULL);
1023 }
1024 
1025 static void
1026 sadb_send_flush_req(sadbp_t *spp)
1027 {
1028 	mblk_t *ctl_mp;
1029 
1030 	/*
1031 	 * we've been unplumbed, or never were plumbed; don't go there.
1032 	 */
1033 	if (spp->s_ip_q == NULL)
1034 		return;
1035 
1036 	/* have IP send a flush msg to the IPsec accelerators */
1037 	ctl_mp = sadb_fmt_sa_req(DL_CO_FLUSH, spp->s_satype, NULL, B_TRUE);
1038 	if (ctl_mp != NULL)
1039 		putnext(spp->s_ip_q, ctl_mp);
1040 }
1041 
1042 void
1043 sadbp_flush(sadbp_t *spp)
1044 {
1045 	sadb_flush(&spp->s_v4);
1046 	sadb_flush(&spp->s_v6);
1047 
1048 	sadb_send_flush_req(spp);
1049 }
1050 
1051 void
1052 sadbp_destroy(sadbp_t *spp)
1053 {
1054 	sadb_destroy(&spp->s_v4);
1055 	sadb_destroy(&spp->s_v6);
1056 
1057 	sadb_send_flush_req(spp);
1058 	if (spp->s_satype == SADB_SATYPE_AH)
1059 		ip_drop_unregister(&sadb_dropper);
1060 }
1061 
1062 
1063 /*
1064  * Check hard vs. soft lifetimes.  If there's a reality mismatch (e.g.
1065  * soft lifetimes > hard lifetimes) return an appropriate diagnostic for
1066  * EINVAL.
1067  */
1068 int
1069 sadb_hardsoftchk(sadb_lifetime_t *hard, sadb_lifetime_t *soft)
1070 {
1071 	if (hard == NULL || soft == NULL)
1072 		return (0);
1073 
1074 	if (hard->sadb_lifetime_allocations != 0 &&
1075 	    soft->sadb_lifetime_allocations != 0 &&
1076 	    hard->sadb_lifetime_allocations < soft->sadb_lifetime_allocations)
1077 		return (SADB_X_DIAGNOSTIC_ALLOC_HSERR);
1078 
1079 	if (hard->sadb_lifetime_bytes != 0 &&
1080 	    soft->sadb_lifetime_bytes != 0 &&
1081 	    hard->sadb_lifetime_bytes < soft->sadb_lifetime_bytes)
1082 		return (SADB_X_DIAGNOSTIC_BYTES_HSERR);
1083 
1084 	if (hard->sadb_lifetime_addtime != 0 &&
1085 	    soft->sadb_lifetime_addtime != 0 &&
1086 	    hard->sadb_lifetime_addtime < soft->sadb_lifetime_addtime)
1087 		return (SADB_X_DIAGNOSTIC_ADDTIME_HSERR);
1088 
1089 	if (hard->sadb_lifetime_usetime != 0 &&
1090 	    soft->sadb_lifetime_usetime != 0 &&
1091 	    hard->sadb_lifetime_usetime < soft->sadb_lifetime_usetime)
1092 		return (SADB_X_DIAGNOSTIC_USETIME_HSERR);
1093 
1094 	return (0);
1095 }
1096 
1097 /*
1098  * Clone a security association for the purposes of inserting a single SA
1099  * into inbound and outbound tables respectively.
1100  */
1101 static ipsa_t *
1102 sadb_cloneassoc(ipsa_t *ipsa)
1103 {
1104 	ipsa_t *newbie;
1105 	boolean_t error = B_FALSE;
1106 
1107 	ASSERT(!MUTEX_HELD(&(ipsa->ipsa_lock)));
1108 
1109 	newbie = kmem_alloc(sizeof (ipsa_t), KM_NOSLEEP);
1110 	if (newbie == NULL)
1111 		return (NULL);
1112 
1113 	/* Copy over what we can. */
1114 	*newbie = *ipsa;
1115 
1116 	/* bzero and initialize locks, in case *_init() allocates... */
1117 	mutex_init(&newbie->ipsa_lock, NULL, MUTEX_DEFAULT, NULL);
1118 
1119 	/*
1120 	 * While somewhat dain-bramaged, the most graceful way to
1121 	 * recover from errors is to keep plowing through the
1122 	 * allocations, and getting what I can.  It's easier to call
1123 	 * sadb_freeassoc() on the stillborn clone when all the
1124 	 * pointers aren't pointing to the parent's data.
1125 	 */
1126 
1127 	if (ipsa->ipsa_authkey != NULL) {
1128 		newbie->ipsa_authkey = kmem_alloc(newbie->ipsa_authkeylen,
1129 		    KM_NOSLEEP);
1130 		if (newbie->ipsa_authkey == NULL) {
1131 			error = B_TRUE;
1132 		} else {
1133 			bcopy(ipsa->ipsa_authkey, newbie->ipsa_authkey,
1134 			    newbie->ipsa_authkeylen);
1135 
1136 			newbie->ipsa_kcfauthkey.ck_data =
1137 			    newbie->ipsa_authkey;
1138 		}
1139 
1140 		if (newbie->ipsa_amech.cm_param != NULL) {
1141 			newbie->ipsa_amech.cm_param =
1142 			    (char *)&newbie->ipsa_mac_len;
1143 		}
1144 	}
1145 
1146 	if (ipsa->ipsa_encrkey != NULL) {
1147 		newbie->ipsa_encrkey = kmem_alloc(newbie->ipsa_encrkeylen,
1148 		    KM_NOSLEEP);
1149 		if (newbie->ipsa_encrkey == NULL) {
1150 			error = B_TRUE;
1151 		} else {
1152 			bcopy(ipsa->ipsa_encrkey, newbie->ipsa_encrkey,
1153 			    newbie->ipsa_encrkeylen);
1154 
1155 			newbie->ipsa_kcfencrkey.ck_data =
1156 			    newbie->ipsa_encrkey;
1157 		}
1158 	}
1159 
1160 	newbie->ipsa_authtmpl = NULL;
1161 	newbie->ipsa_encrtmpl = NULL;
1162 
1163 	if (ipsa->ipsa_integ != NULL) {
1164 		newbie->ipsa_integ = kmem_alloc(newbie->ipsa_integlen,
1165 		    KM_NOSLEEP);
1166 		if (newbie->ipsa_integ == NULL) {
1167 			error = B_TRUE;
1168 		} else {
1169 			bcopy(ipsa->ipsa_integ, newbie->ipsa_integ,
1170 			    newbie->ipsa_integlen);
1171 		}
1172 	}
1173 
1174 	if (ipsa->ipsa_sens != NULL) {
1175 		newbie->ipsa_sens = kmem_alloc(newbie->ipsa_senslen,
1176 		    KM_NOSLEEP);
1177 		if (newbie->ipsa_sens == NULL) {
1178 			error = B_TRUE;
1179 		} else {
1180 			bcopy(ipsa->ipsa_sens, newbie->ipsa_sens,
1181 			    newbie->ipsa_senslen);
1182 		}
1183 	}
1184 
1185 	if (ipsa->ipsa_src_cid != NULL) {
1186 		newbie->ipsa_src_cid = ipsa->ipsa_src_cid;
1187 		IPSID_REFHOLD(ipsa->ipsa_src_cid);
1188 	}
1189 
1190 	if (ipsa->ipsa_dst_cid != NULL) {
1191 		newbie->ipsa_dst_cid = ipsa->ipsa_dst_cid;
1192 		IPSID_REFHOLD(ipsa->ipsa_dst_cid);
1193 	}
1194 
1195 #if 0 /* XXX PROXY  - Proxy identities not supported yet. */
1196 	if (ipsa->ipsa_proxy_cid != NULL) {
1197 		newbie->ipsa_proxy_cid = ipsa->ipsa_proxy_cid;
1198 		IPSID_REFHOLD(ipsa->ipsa_proxy_cid);
1199 	}
1200 #endif /* XXX PROXY */
1201 
1202 	if (error) {
1203 		sadb_freeassoc(newbie);
1204 		return (NULL);
1205 	}
1206 
1207 	return (newbie);
1208 }
1209 
1210 /*
1211  * Initialize a SADB address extension at the address specified by addrext.
1212  * Return a pointer to the end of the new address extension.
1213  */
1214 static uint8_t *
1215 sadb_make_addr_ext(uint8_t *start, uint8_t *end, uint16_t exttype,
1216     sa_family_t af, uint32_t *addr, uint16_t port, uint8_t proto)
1217 {
1218 	struct sockaddr_in *sin;
1219 	struct sockaddr_in6 *sin6;
1220 	uint8_t *cur = start;
1221 	int addrext_len;
1222 	int sin_len;
1223 	sadb_address_t *addrext	= (sadb_address_t *)cur;
1224 
1225 	if (cur == NULL)
1226 		return (NULL);
1227 
1228 	cur += sizeof (*addrext);
1229 	if (cur > end)
1230 		return (NULL);
1231 
1232 	addrext->sadb_address_proto = proto;
1233 	addrext->sadb_address_prefixlen = 0;
1234 	addrext->sadb_address_reserved = 0;
1235 	addrext->sadb_address_exttype = exttype;
1236 
1237 	switch (af) {
1238 	case AF_INET:
1239 		sin = (struct sockaddr_in *)cur;
1240 		sin_len = sizeof (*sin);
1241 		cur += sin_len;
1242 		if (cur > end)
1243 			return (NULL);
1244 
1245 		sin->sin_family = af;
1246 		bzero(sin->sin_zero, sizeof (sin->sin_zero));
1247 		sin->sin_port = port;
1248 		IPSA_COPY_ADDR(&sin->sin_addr, addr, af);
1249 		break;
1250 	case AF_INET6:
1251 		sin6 = (struct sockaddr_in6 *)cur;
1252 		sin_len = sizeof (*sin6);
1253 		cur += sin_len;
1254 		if (cur > end)
1255 			return (NULL);
1256 
1257 		bzero(sin6, sizeof (*sin6));
1258 		sin6->sin6_family = af;
1259 		sin6->sin6_port = port;
1260 		IPSA_COPY_ADDR(&sin6->sin6_addr, addr, af);
1261 		break;
1262 	}
1263 
1264 	addrext_len = roundup(cur - start, sizeof (uint64_t));
1265 	addrext->sadb_address_len = SADB_8TO64(addrext_len);
1266 
1267 	cur = start + addrext_len;
1268 	if (cur > end)
1269 		cur = NULL;
1270 
1271 	return (cur);
1272 }
1273 
1274 /*
1275  * Construct a key management cookie extension.
1276  */
1277 
1278 static uint8_t *
1279 sadb_make_kmc_ext(uint8_t *cur, uint8_t *end, uint32_t kmp, uint32_t kmc)
1280 {
1281 	sadb_x_kmc_t *kmcext = (sadb_x_kmc_t *)cur;
1282 
1283 	if (cur == NULL)
1284 		return (NULL);
1285 
1286 	cur += sizeof (*kmcext);
1287 
1288 	if (cur > end)
1289 		return (NULL);
1290 
1291 	kmcext->sadb_x_kmc_len = SADB_8TO64(sizeof (*kmcext));
1292 	kmcext->sadb_x_kmc_exttype = SADB_X_EXT_KM_COOKIE;
1293 	kmcext->sadb_x_kmc_proto = kmp;
1294 	kmcext->sadb_x_kmc_cookie = kmc;
1295 	kmcext->sadb_x_kmc_reserved = 0;
1296 
1297 	return (cur);
1298 }
1299 
1300 /*
1301  * Given an original message header with sufficient space following it, and an
1302  * SA, construct a full PF_KEY message with all of the relevant extensions.
1303  * This is mostly used for SADB_GET, and SADB_DUMP.
1304  */
1305 mblk_t *
1306 sadb_sa2msg(ipsa_t *ipsa, sadb_msg_t *samsg)
1307 {
1308 	int alloclen, addrsize, paddrsize, authsize, encrsize;
1309 	int srcidsize, dstidsize;
1310 	sa_family_t fam, pfam;	/* Address family for SADB_EXT_ADDRESS */
1311 				/* src/dst and proxy sockaddrs. */
1312 	/*
1313 	 * The following are pointers into the PF_KEY message this PF_KEY
1314 	 * message creates.
1315 	 */
1316 	sadb_msg_t *newsamsg;
1317 	sadb_sa_t *assoc;
1318 	sadb_lifetime_t *lt;
1319 	sadb_key_t *key;
1320 	sadb_ident_t *ident;
1321 	sadb_sens_t *sens;
1322 	sadb_ext_t *walker;	/* For when we need a generic ext. pointer. */
1323 	mblk_t *mp;
1324 	uint64_t *bitmap;
1325 	uint8_t *cur, *end;
1326 	/* These indicate the presence of the above extension fields. */
1327 	boolean_t soft, hard, proxy, auth, encr, sensinteg, srcid, dstid;
1328 #if 0 /* XXX PROXY see below... */
1329 	boolean_t proxyid, iv;
1330 	int proxyidsize, ivsize;
1331 #endif /* XXX PROXY */
1332 
1333 	/* First off, figure out the allocation length for this message. */
1334 
1335 	/*
1336 	 * Constant stuff.  This includes base, SA, address (src, dst),
1337 	 * and lifetime (current).
1338 	 */
1339 	alloclen = sizeof (sadb_msg_t) + sizeof (sadb_sa_t) +
1340 	    sizeof (sadb_lifetime_t);
1341 
1342 	fam = ipsa->ipsa_addrfam;
1343 	switch (fam) {
1344 	case AF_INET:
1345 		addrsize = roundup(sizeof (struct sockaddr_in) +
1346 		    sizeof (sadb_address_t), sizeof (uint64_t));
1347 		break;
1348 	case AF_INET6:
1349 		addrsize = roundup(sizeof (struct sockaddr_in6) +
1350 		    sizeof (sadb_address_t), sizeof (uint64_t));
1351 		break;
1352 	default:
1353 		return (NULL);
1354 	}
1355 	/*
1356 	 * Allocate TWO address extensions, for source and destination.
1357 	 * (Thus, the * 2.)
1358 	 */
1359 	alloclen += addrsize * 2;
1360 	if (ipsa->ipsa_flags & IPSA_F_NATT_REM)
1361 	    alloclen += addrsize;
1362 	if (ipsa->ipsa_flags & IPSA_F_NATT_LOC)
1363 	    alloclen += addrsize;
1364 
1365 
1366 	/* How 'bout other lifetimes? */
1367 	if (ipsa->ipsa_softaddlt != 0 || ipsa->ipsa_softuselt != 0 ||
1368 	    ipsa->ipsa_softbyteslt != 0 || ipsa->ipsa_softalloc != 0) {
1369 		alloclen += sizeof (sadb_lifetime_t);
1370 		soft = B_TRUE;
1371 	} else {
1372 		soft = B_FALSE;
1373 	}
1374 
1375 	if (ipsa->ipsa_hardaddlt != 0 || ipsa->ipsa_harduselt != 0 ||
1376 	    ipsa->ipsa_hardbyteslt != 0 || ipsa->ipsa_hardalloc != 0) {
1377 		alloclen += sizeof (sadb_lifetime_t);
1378 		hard = B_TRUE;
1379 	} else {
1380 		hard = B_FALSE;
1381 	}
1382 
1383 	/* Proxy address? */
1384 	if (!IPSA_IS_ADDR_UNSPEC(ipsa->ipsa_proxysrc, ipsa->ipsa_proxyfam)) {
1385 		pfam = ipsa->ipsa_proxyfam;
1386 		switch (pfam) {
1387 		case AF_INET6:
1388 			paddrsize = roundup(sizeof (struct sockaddr_in6) +
1389 			    sizeof (sadb_address_t), sizeof (uint64_t));
1390 			break;
1391 		case AF_INET:
1392 			paddrsize = roundup(sizeof (struct sockaddr_in) +
1393 			    sizeof (sadb_address_t), sizeof (uint64_t));
1394 			break;
1395 		default:
1396 			cmn_err(CE_PANIC,
1397 			    "IPsec SADB: Proxy length failure.\n");
1398 			break;
1399 		}
1400 		proxy = B_TRUE;
1401 		alloclen += paddrsize;
1402 	} else {
1403 		proxy = B_FALSE;
1404 	}
1405 
1406 	/* For the following fields, assume that length != 0 ==> stuff */
1407 	if (ipsa->ipsa_authkeylen != 0) {
1408 		authsize = roundup(sizeof (sadb_key_t) + ipsa->ipsa_authkeylen,
1409 		    sizeof (uint64_t));
1410 		alloclen += authsize;
1411 		auth = B_TRUE;
1412 	} else {
1413 		auth = B_FALSE;
1414 	}
1415 
1416 	if (ipsa->ipsa_encrkeylen != 0) {
1417 		encrsize = roundup(sizeof (sadb_key_t) + ipsa->ipsa_encrkeylen,
1418 		    sizeof (uint64_t));
1419 		alloclen += encrsize;
1420 		encr = B_TRUE;
1421 	} else {
1422 		encr = B_FALSE;
1423 	}
1424 
1425 	/* No need for roundup on sens and integ. */
1426 	if (ipsa->ipsa_integlen != 0 || ipsa->ipsa_senslen != 0) {
1427 		alloclen += sizeof (sadb_key_t) + ipsa->ipsa_integlen +
1428 		    ipsa->ipsa_senslen;
1429 		sensinteg = B_TRUE;
1430 	} else {
1431 		sensinteg = B_FALSE;
1432 	}
1433 
1434 	/*
1435 	 * Must use strlen() here for lengths.	Identities use NULL
1436 	 * pointers to indicate their nonexistence.
1437 	 */
1438 	if (ipsa->ipsa_src_cid != NULL) {
1439 		srcidsize = roundup(sizeof (sadb_ident_t) +
1440 		    strlen(ipsa->ipsa_src_cid->ipsid_cid) + 1,
1441 		    sizeof (uint64_t));
1442 		alloclen += srcidsize;
1443 		srcid = B_TRUE;
1444 	} else {
1445 		srcid = B_FALSE;
1446 	}
1447 
1448 	if (ipsa->ipsa_dst_cid != NULL) {
1449 		dstidsize = roundup(sizeof (sadb_ident_t) +
1450 		    strlen(ipsa->ipsa_dst_cid->ipsid_cid) + 1,
1451 		    sizeof (uint64_t));
1452 		alloclen += dstidsize;
1453 		dstid = B_TRUE;
1454 	} else {
1455 		dstid = B_FALSE;
1456 	}
1457 
1458 #if 0 /* XXX PROXY not yet. */
1459 	if (ipsa->ipsa_proxy_cid != NULL) {
1460 		proxyidsize = roundup(sizeof (sadb_ident_t) +
1461 		    strlen(ipsa->ipsa_proxy_cid->ipsid_cid) + 1,
1462 		    sizeof (uint64_t));
1463 		alloclen += proxyidsize;
1464 		proxyid = B_TRUE;
1465 	} else {
1466 		proxyid = B_FALSE;
1467 	}
1468 #endif /* XXX PROXY */
1469 	if ((ipsa->ipsa_kmp != 0) || (ipsa->ipsa_kmc != 0))
1470 		alloclen += sizeof (sadb_x_kmc_t);
1471 
1472 	/* Make sure the allocation length is a multiple of 8 bytes. */
1473 	ASSERT((alloclen & 0x7) == 0);
1474 
1475 	/* XXX Possibly make it esballoc, with a bzero-ing free_ftn. */
1476 	mp = allocb(alloclen, BPRI_HI);
1477 	if (mp == NULL)
1478 		return (NULL);
1479 
1480 	mp->b_wptr += alloclen;
1481 	end = mp->b_wptr;
1482 	newsamsg = (sadb_msg_t *)mp->b_rptr;
1483 	*newsamsg = *samsg;
1484 	newsamsg->sadb_msg_len = (uint16_t)SADB_8TO64(alloclen);
1485 
1486 	mutex_enter(&ipsa->ipsa_lock);	/* Since I'm grabbing SA fields... */
1487 
1488 	newsamsg->sadb_msg_satype = ipsa->ipsa_type;
1489 
1490 	assoc = (sadb_sa_t *)(newsamsg + 1);
1491 	assoc->sadb_sa_len = SADB_8TO64(sizeof (*assoc));
1492 	assoc->sadb_sa_exttype = SADB_EXT_SA;
1493 	assoc->sadb_sa_spi = ipsa->ipsa_spi;
1494 	assoc->sadb_sa_replay = ipsa->ipsa_replay_wsize;
1495 	assoc->sadb_sa_state = ipsa->ipsa_state;
1496 	assoc->sadb_sa_auth = ipsa->ipsa_auth_alg;
1497 	assoc->sadb_sa_encrypt = ipsa->ipsa_encr_alg;
1498 	assoc->sadb_sa_flags = ipsa->ipsa_flags;
1499 
1500 	lt = (sadb_lifetime_t *)(assoc + 1);
1501 	lt->sadb_lifetime_len = SADB_8TO64(sizeof (*lt));
1502 	lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
1503 	lt->sadb_lifetime_allocations = ipsa->ipsa_alloc;
1504 	lt->sadb_lifetime_bytes = ipsa->ipsa_bytes;
1505 	lt->sadb_lifetime_addtime = ipsa->ipsa_addtime;
1506 	lt->sadb_lifetime_usetime = ipsa->ipsa_usetime;
1507 
1508 	if (hard) {
1509 		lt++;
1510 		lt->sadb_lifetime_len = SADB_8TO64(sizeof (*lt));
1511 		lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD;
1512 		lt->sadb_lifetime_allocations = ipsa->ipsa_hardalloc;
1513 		lt->sadb_lifetime_bytes = ipsa->ipsa_hardbyteslt;
1514 		lt->sadb_lifetime_addtime = ipsa->ipsa_hardaddlt;
1515 		lt->sadb_lifetime_usetime = ipsa->ipsa_harduselt;
1516 	}
1517 
1518 	if (soft) {
1519 		lt++;
1520 		lt->sadb_lifetime_len = SADB_8TO64(sizeof (*lt));
1521 		lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_SOFT;
1522 		lt->sadb_lifetime_allocations = ipsa->ipsa_softalloc;
1523 		lt->sadb_lifetime_bytes = ipsa->ipsa_softbyteslt;
1524 		lt->sadb_lifetime_addtime = ipsa->ipsa_softaddlt;
1525 		lt->sadb_lifetime_usetime = ipsa->ipsa_softuselt;
1526 	}
1527 
1528 	cur = (uint8_t *)(lt + 1);
1529 
1530 	cur = sadb_make_addr_ext(cur, end, SADB_EXT_ADDRESS_SRC, fam,
1531 	    ipsa->ipsa_srcaddr, SA_SRCPORT(ipsa), SA_PROTO(ipsa));
1532 	if (cur == NULL) {
1533 		freemsg(mp);
1534 		mp = NULL;
1535 		goto bail;
1536 	}
1537 
1538 	cur = sadb_make_addr_ext(cur, end, SADB_EXT_ADDRESS_DST, fam,
1539 	    ipsa->ipsa_dstaddr, SA_DSTPORT(ipsa), SA_PROTO(ipsa));
1540 	if (cur == NULL) {
1541 		freemsg(mp);
1542 		mp = NULL;
1543 		goto bail;
1544 	}
1545 
1546 	if (ipsa->ipsa_flags & IPSA_F_NATT_LOC) {
1547 		cur = sadb_make_addr_ext(cur, end, SADB_X_EXT_ADDRESS_NATT_LOC,
1548 		    fam, ipsa->ipsa_natt_addr_loc, 0, 0);
1549 		if (cur == NULL) {
1550 			freemsg(mp);
1551 			mp = NULL;
1552 			goto bail;
1553 		}
1554 	}
1555 
1556 	if (ipsa->ipsa_flags & IPSA_F_NATT_REM) {
1557 		cur = sadb_make_addr_ext(cur, end, SADB_X_EXT_ADDRESS_NATT_REM,
1558 		    fam, ipsa->ipsa_natt_addr_rem, ipsa->ipsa_remote_port,
1559 		    IPPROTO_UDP);
1560 		if (cur == NULL) {
1561 			freemsg(mp);
1562 			mp = NULL;
1563 			goto bail;
1564 		}
1565 	}
1566 
1567 	if (proxy) {
1568 		/*
1569 		 * XXX PROXY When we expand the definition of proxy to include
1570 		 * both inner and outer IP addresses, this will have to
1571 		 * be expanded.
1572 		 */
1573 		cur = sadb_make_addr_ext(cur, end, SADB_EXT_ADDRESS_PROXY,
1574 		    pfam, ipsa->ipsa_proxysrc, 0, 0);
1575 		if (cur == NULL) {
1576 			freemsg(mp);
1577 			mp = NULL;
1578 			goto bail;
1579 		}
1580 	}
1581 
1582 	if ((ipsa->ipsa_kmp != 0) || (ipsa->ipsa_kmc != 0)) {
1583 		cur = sadb_make_kmc_ext(cur, end,
1584 		    ipsa->ipsa_kmp, ipsa->ipsa_kmc);
1585 		if (cur == NULL) {
1586 			freemsg(mp);
1587 			mp = NULL;
1588 			goto bail;
1589 		}
1590 	}
1591 
1592 	walker = (sadb_ext_t *)cur;
1593 	if (auth) {
1594 		key = (sadb_key_t *)walker;
1595 		key->sadb_key_len = SADB_8TO64(authsize);
1596 		key->sadb_key_exttype = SADB_EXT_KEY_AUTH;
1597 		key->sadb_key_bits = ipsa->ipsa_authkeybits;
1598 		key->sadb_key_reserved = 0;
1599 		bcopy(ipsa->ipsa_authkey, key + 1, ipsa->ipsa_authkeylen);
1600 		walker = (sadb_ext_t *)((uint64_t *)walker +
1601 		    walker->sadb_ext_len);
1602 	}
1603 
1604 	if (encr) {
1605 		key = (sadb_key_t *)walker;
1606 		key->sadb_key_len = SADB_8TO64(encrsize);
1607 		key->sadb_key_exttype = SADB_EXT_KEY_ENCRYPT;
1608 		key->sadb_key_bits = ipsa->ipsa_encrkeybits;
1609 		key->sadb_key_reserved = 0;
1610 		bcopy(ipsa->ipsa_encrkey, key + 1, ipsa->ipsa_encrkeylen);
1611 		walker = (sadb_ext_t *)((uint64_t *)walker +
1612 		    walker->sadb_ext_len);
1613 	}
1614 
1615 	if (srcid) {
1616 		ident = (sadb_ident_t *)walker;
1617 		ident->sadb_ident_len = SADB_8TO64(srcidsize);
1618 		ident->sadb_ident_exttype = SADB_EXT_IDENTITY_SRC;
1619 		ident->sadb_ident_type = ipsa->ipsa_src_cid->ipsid_type;
1620 		ident->sadb_ident_id = 0;
1621 		ident->sadb_ident_reserved = 0;
1622 		(void) strcpy((char *)(ident + 1),
1623 		    ipsa->ipsa_src_cid->ipsid_cid);
1624 		walker = (sadb_ext_t *)((uint64_t *)walker +
1625 		    walker->sadb_ext_len);
1626 	}
1627 
1628 	if (dstid) {
1629 		ident = (sadb_ident_t *)walker;
1630 		ident->sadb_ident_len = SADB_8TO64(dstidsize);
1631 		ident->sadb_ident_exttype = SADB_EXT_IDENTITY_DST;
1632 		ident->sadb_ident_type = ipsa->ipsa_dst_cid->ipsid_type;
1633 		ident->sadb_ident_id = 0;
1634 		ident->sadb_ident_reserved = 0;
1635 		(void) strcpy((char *)(ident + 1),
1636 		    ipsa->ipsa_dst_cid->ipsid_cid);
1637 		walker = (sadb_ext_t *)((uint64_t *)walker +
1638 		    walker->sadb_ext_len);
1639 	}
1640 
1641 #if 0 /* XXX PROXY not yet */
1642 	if (proxyid) {
1643 		ident = (sadb_ident_t *)walker;
1644 		ident->sadb_ident_len = SADB_8TO64(proxyidsize);
1645 		ident->sadb_ident_exttype = SADB_EXT_IDENTITY_PROXY;
1646 		ident->sadb_ident_type = ipsa->ipsa_pcid_type;
1647 		ident->sadb_ident_id = 0;
1648 		ident->sadb_ident_reserved = 0;
1649 		(void) strcpy((char *)(ident + 1), ipsa->ipsa_proxy_cid);
1650 		walker = (sadb_ext_t *)((uint64_t *)walker +
1651 		    walker->sadb_ext_len);
1652 	}
1653 #endif /* XXX PROXY */
1654 
1655 	if (sensinteg) {
1656 		sens = (sadb_sens_t *)walker;
1657 		sens->sadb_sens_len = SADB_8TO64(sizeof (sadb_sens_t *) +
1658 		    ipsa->ipsa_senslen + ipsa->ipsa_integlen);
1659 		sens->sadb_sens_dpd = ipsa->ipsa_dpd;
1660 		sens->sadb_sens_sens_level = ipsa->ipsa_senslevel;
1661 		sens->sadb_sens_integ_level = ipsa->ipsa_integlevel;
1662 		sens->sadb_sens_sens_len = SADB_8TO64(ipsa->ipsa_senslen);
1663 		sens->sadb_sens_integ_len = SADB_8TO64(ipsa->ipsa_integlen);
1664 		sens->sadb_sens_reserved = 0;
1665 		bitmap = (uint64_t *)(sens + 1);
1666 		if (ipsa->ipsa_sens != NULL) {
1667 			bcopy(ipsa->ipsa_sens, bitmap, ipsa->ipsa_senslen);
1668 			bitmap += sens->sadb_sens_sens_len;
1669 		}
1670 		if (ipsa->ipsa_integ != NULL)
1671 			bcopy(ipsa->ipsa_integ, bitmap, ipsa->ipsa_integlen);
1672 		walker = (sadb_ext_t *)((uint64_t *)walker +
1673 		    walker->sadb_ext_len);
1674 	}
1675 
1676 bail:
1677 	/* Pardon any delays... */
1678 	mutex_exit(&ipsa->ipsa_lock);
1679 
1680 	return (mp);
1681 }
1682 
1683 /*
1684  * Strip out key headers or unmarked headers (SADB_EXT_KEY_*, SADB_EXT_UNKNOWN)
1685  * and adjust base message accordingly.
1686  *
1687  * Assume message is pulled up in one piece of contiguous memory.
1688  *
1689  * Say if we start off with:
1690  *
1691  * +------+----+-------------+-----------+---------------+---------------+
1692  * | base | SA | source addr | dest addr | rsrvd. or key | soft lifetime |
1693  * +------+----+-------------+-----------+---------------+---------------+
1694  *
1695  * we will end up with
1696  *
1697  * +------+----+-------------+-----------+---------------+
1698  * | base | SA | source addr | dest addr | soft lifetime |
1699  * +------+----+-------------+-----------+---------------+
1700  */
1701 static void
1702 sadb_strip(sadb_msg_t *samsg)
1703 {
1704 	sadb_ext_t *ext;
1705 	uint8_t *target = NULL;
1706 	uint8_t *msgend;
1707 	int sofar = SADB_8TO64(sizeof (*samsg));
1708 	int copylen;
1709 
1710 	ext = (sadb_ext_t *)(samsg + 1);
1711 	msgend = (uint8_t *)samsg;
1712 	msgend += SADB_64TO8(samsg->sadb_msg_len);
1713 	while ((uint8_t *)ext < msgend) {
1714 		if (ext->sadb_ext_type == SADB_EXT_RESERVED ||
1715 		    ext->sadb_ext_type == SADB_EXT_KEY_AUTH ||
1716 		    ext->sadb_ext_type == SADB_EXT_KEY_ENCRYPT) {
1717 			/*
1718 			 * Aha!	 I found a header to be erased.
1719 			 */
1720 
1721 			if (target != NULL) {
1722 				/*
1723 				 * If I had a previous header to be erased,
1724 				 * copy over it.  I can get away with just
1725 				 * copying backwards because the target will
1726 				 * always be 8 bytes behind the source.
1727 				 */
1728 				copylen = ((uint8_t *)ext) - (target +
1729 				    SADB_64TO8(
1730 					((sadb_ext_t *)target)->sadb_ext_len));
1731 				ovbcopy(((uint8_t *)ext - copylen), target,
1732 				    copylen);
1733 				target += copylen;
1734 				((sadb_ext_t *)target)->sadb_ext_len =
1735 				    SADB_8TO64(((uint8_t *)ext) - target +
1736 					SADB_64TO8(ext->sadb_ext_len));
1737 			} else {
1738 				target = (uint8_t *)ext;
1739 			}
1740 		} else {
1741 			sofar += ext->sadb_ext_len;
1742 		}
1743 
1744 		ext = (sadb_ext_t *)(((uint64_t *)ext) + ext->sadb_ext_len);
1745 	}
1746 
1747 	ASSERT((uint8_t *)ext == msgend);
1748 
1749 	if (target != NULL) {
1750 		copylen = ((uint8_t *)ext) - (target +
1751 		    SADB_64TO8(((sadb_ext_t *)target)->sadb_ext_len));
1752 		if (copylen != 0)
1753 			ovbcopy(((uint8_t *)ext - copylen), target, copylen);
1754 	}
1755 
1756 	/* Adjust samsg. */
1757 	samsg->sadb_msg_len = (uint16_t)sofar;
1758 
1759 	/* Assume all of the rest is cleared by caller in sadb_pfkey_echo(). */
1760 }
1761 
1762 /*
1763  * AH needs to send an error to PF_KEY.	 Assume mp points to an M_CTL
1764  * followed by an M_DATA with a PF_KEY message in it.  The serial of
1765  * the sending keysock instance is included.
1766  */
1767 void
1768 sadb_pfkey_error(queue_t *pfkey_q, mblk_t *mp, int error, int diagnostic,
1769     uint_t serial)
1770 {
1771 	mblk_t *msg = mp->b_cont;
1772 	sadb_msg_t *samsg;
1773 	keysock_out_t *kso;
1774 
1775 	/*
1776 	 * Enough functions call this to merit a NULL queue check.
1777 	 */
1778 	if (pfkey_q == NULL) {
1779 		freemsg(mp);
1780 		return;
1781 	}
1782 
1783 	ASSERT(msg != NULL);
1784 	ASSERT((mp->b_wptr - mp->b_rptr) == sizeof (ipsec_info_t));
1785 	ASSERT((msg->b_wptr - msg->b_rptr) >= sizeof (sadb_msg_t));
1786 	samsg = (sadb_msg_t *)msg->b_rptr;
1787 	kso = (keysock_out_t *)mp->b_rptr;
1788 
1789 	kso->ks_out_type = KEYSOCK_OUT;
1790 	kso->ks_out_len = sizeof (*kso);
1791 	kso->ks_out_serial = serial;
1792 
1793 	/*
1794 	 * Only send the base message up in the event of an error.
1795 	 * Don't worry about bzero()-ing, because it was probably bogus
1796 	 * anyway.
1797 	 */
1798 	msg->b_wptr = msg->b_rptr + sizeof (*samsg);
1799 	samsg = (sadb_msg_t *)msg->b_rptr;
1800 	samsg->sadb_msg_len = SADB_8TO64(sizeof (*samsg));
1801 	samsg->sadb_msg_errno = (uint8_t)error;
1802 	if (diagnostic != SADB_X_DIAGNOSTIC_PRESET)
1803 		samsg->sadb_x_msg_diagnostic = (uint16_t)diagnostic;
1804 
1805 	putnext(pfkey_q, mp);
1806 }
1807 
1808 /*
1809  * Send a successful return packet back to keysock via the queue in pfkey_q.
1810  *
1811  * Often, an SA is associated with the reply message, it's passed in if needed,
1812  * and NULL if not.  BTW, that ipsa will have its refcnt appropriately held,
1813  * and the caller will release said refcnt.
1814  */
1815 void
1816 sadb_pfkey_echo(queue_t *pfkey_q, mblk_t *mp, sadb_msg_t *samsg,
1817     keysock_in_t *ksi, ipsa_t *ipsa)
1818 {
1819 	keysock_out_t *kso;
1820 	mblk_t *mp1;
1821 	sadb_msg_t *newsamsg;
1822 	uint8_t *oldend;
1823 
1824 	ASSERT((mp->b_cont != NULL) &&
1825 	    ((void *)samsg == (void *)mp->b_cont->b_rptr) &&
1826 	    ((void *)mp->b_rptr == (void *)ksi));
1827 
1828 	switch (samsg->sadb_msg_type) {
1829 	case SADB_ADD:
1830 	case SADB_UPDATE:
1831 	case SADB_FLUSH:
1832 	case SADB_DUMP:
1833 		/*
1834 		 * I have all of the message already.  I just need to strip
1835 		 * out the keying material and echo the message back.
1836 		 *
1837 		 * NOTE: for SADB_DUMP, the function sadb_dump() did the
1838 		 * work.  When DUMP reaches here, it should only be a base
1839 		 * message.
1840 		 */
1841 	justecho:
1842 		ASSERT(samsg->sadb_msg_type != SADB_DUMP ||
1843 		    samsg->sadb_msg_len == SADB_8TO64(sizeof (sadb_msg_t)));
1844 
1845 		if (ksi->ks_in_extv[SADB_EXT_KEY_AUTH] != NULL ||
1846 		    ksi->ks_in_extv[SADB_EXT_KEY_ENCRYPT] != NULL) {
1847 			sadb_strip(samsg);
1848 			/* Assume PF_KEY message is contiguous. */
1849 			ASSERT(mp->b_cont->b_cont == NULL);
1850 			oldend = mp->b_cont->b_wptr;
1851 			mp->b_cont->b_wptr = mp->b_cont->b_rptr +
1852 			    SADB_64TO8(samsg->sadb_msg_len);
1853 			bzero(mp->b_cont->b_wptr, oldend - mp->b_cont->b_wptr);
1854 		}
1855 		break;
1856 	case SADB_GET:
1857 		/*
1858 		 * Do a lot of work here, because of the ipsa I just found.
1859 		 * First abandon the PF_KEY message, then construct
1860 		 * the new one.
1861 		 */
1862 		mp1 = sadb_sa2msg(ipsa, samsg);
1863 		if (mp1 == NULL) {
1864 			sadb_pfkey_error(pfkey_q, mp, ENOMEM,
1865 			    SADB_X_DIAGNOSTIC_NONE, ksi->ks_in_serial);
1866 			return;
1867 		}
1868 		freemsg(mp->b_cont);
1869 		mp->b_cont = mp1;
1870 		break;
1871 	case SADB_DELETE:
1872 		if (ipsa == NULL)
1873 			goto justecho;
1874 		/*
1875 		 * Because listening KMds may require more info, treat
1876 		 * DELETE like a special case of GET.
1877 		 */
1878 		mp1 = sadb_sa2msg(ipsa, samsg);
1879 		if (mp1 == NULL) {
1880 			sadb_pfkey_error(pfkey_q, mp, ENOMEM,
1881 			    SADB_X_DIAGNOSTIC_NONE, ksi->ks_in_serial);
1882 			return;
1883 		}
1884 		newsamsg = (sadb_msg_t *)mp1->b_rptr;
1885 		sadb_strip(newsamsg);
1886 		oldend = mp1->b_wptr;
1887 		mp1->b_wptr = mp1->b_rptr + SADB_64TO8(newsamsg->sadb_msg_len);
1888 		bzero(mp1->b_wptr, oldend - mp1->b_wptr);
1889 		freemsg(mp->b_cont);
1890 		mp->b_cont = mp1;
1891 		break;
1892 	default:
1893 		if (mp != NULL)
1894 			freemsg(mp);
1895 		return;
1896 	}
1897 
1898 	/* ksi is now null and void. */
1899 	kso = (keysock_out_t *)ksi;
1900 	kso->ks_out_type = KEYSOCK_OUT;
1901 	kso->ks_out_len = sizeof (*kso);
1902 	kso->ks_out_serial = ksi->ks_in_serial;
1903 	/* We're ready to send... */
1904 	putnext(pfkey_q, mp);
1905 }
1906 
1907 /*
1908  * Set up a global pfkey_q instance for AH, ESP, or some other consumer.
1909  */
1910 void
1911 sadb_keysock_hello(queue_t **pfkey_qp, queue_t *q, mblk_t *mp,
1912     void (*ager)(void *), timeout_id_t *top, int satype)
1913 {
1914 	keysock_hello_ack_t *kha;
1915 	queue_t *oldq;
1916 
1917 	ASSERT(OTHERQ(q) != NULL);
1918 
1919 	/*
1920 	 * First, check atomically that I'm the first and only keysock
1921 	 * instance.
1922 	 *
1923 	 * Use OTHERQ(q), because qreply(q, mp) == putnext(OTHERQ(q), mp),
1924 	 * and I want this module to say putnext(*_pfkey_q, mp) for PF_KEY
1925 	 * messages.
1926 	 */
1927 
1928 	oldq = casptr((void **)pfkey_qp, NULL, OTHERQ(q));
1929 	if (oldq != NULL) {
1930 		ASSERT(oldq != q);
1931 		cmn_err(CE_WARN, "Danger!  Multiple keysocks on top of %s.\n",
1932 		    (satype == SADB_SATYPE_ESP)? "ESP" : "AH or other");
1933 		freemsg(mp);
1934 		return;
1935 	}
1936 
1937 	kha = (keysock_hello_ack_t *)mp->b_rptr;
1938 	kha->ks_hello_len = sizeof (keysock_hello_ack_t);
1939 	kha->ks_hello_type = KEYSOCK_HELLO_ACK;
1940 	kha->ks_hello_satype = (uint8_t)satype;
1941 
1942 	/*
1943 	 * If we made it past the casptr, then we have "exclusive" access
1944 	 * to the timeout handle.  Fire it off in 4 seconds, because it
1945 	 * just seems like a good interval.
1946 	 */
1947 	*top = qtimeout(*pfkey_qp, ager, NULL, drv_usectohz(4000000));
1948 
1949 	putnext(*pfkey_qp, mp);
1950 }
1951 
1952 /*
1953  * Send IRE_DB_REQ down to IP to get properties of address.
1954  * If I can determine the address, return the proper type.  If an error
1955  * occurs, or if I have to send down an IRE_DB_REQ, return UNKNOWN, and
1956  * the caller will just let go of mp w/o freeing it.
1957  *
1958  * To handle the compatible IPv6 addresses (i.e. ::FFFF:<v4-address>),
1959  * this function will also convert such AF_INET6 addresses into AF_INET
1960  * addresses.
1961  *
1962  * Whomever called the function will handle the return message that IP sends
1963  * in response to the message this function generates.
1964  */
1965 int
1966 sadb_addrcheck(queue_t *ip_q, queue_t *pfkey_q, mblk_t *mp, sadb_ext_t *ext,
1967     uint_t serial)
1968 {
1969 	sadb_address_t *addr = (sadb_address_t *)ext;
1970 	struct sockaddr_in *sin;
1971 	struct sockaddr_in6 *sin6;
1972 	mblk_t *ire_db_req_mp;
1973 	ire_t *ire;
1974 	int diagnostic;
1975 
1976 	ASSERT(ext != NULL);
1977 	ASSERT((ext->sadb_ext_type == SADB_EXT_ADDRESS_SRC) ||
1978 	    (ext->sadb_ext_type == SADB_EXT_ADDRESS_DST) ||
1979 	    (ext->sadb_ext_type == SADB_EXT_ADDRESS_PROXY));
1980 
1981 	ire_db_req_mp = allocb(sizeof (ire_t), BPRI_HI);
1982 	if (ire_db_req_mp == NULL) {
1983 		/* cmn_err(CE_WARN, "sadb_addrcheck: allocb() failed.\n"); */
1984 		sadb_pfkey_error(pfkey_q, mp, ENOMEM, SADB_X_DIAGNOSTIC_NONE,
1985 		    serial);
1986 		return (KS_IN_ADDR_UNKNOWN);
1987 	}
1988 
1989 	ire_db_req_mp->b_datap->db_type = IRE_DB_REQ_TYPE;
1990 	ire_db_req_mp->b_wptr += sizeof (ire_t);
1991 	ire = (ire_t *)ire_db_req_mp->b_rptr;
1992 
1993 	/* Assign both sockaddrs, the compiler will do the right thing. */
1994 	sin = (struct sockaddr_in *)(addr + 1);
1995 	sin6 = (struct sockaddr_in6 *)(addr + 1);
1996 
1997 	switch (sin->sin_family) {
1998 	case AF_INET6:
1999 		/* Because of the longer IPv6 addrs, do check first. */
2000 		if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
2001 			if (IN6_IS_ADDR_MULTICAST(&sin6->sin6_addr)) {
2002 				freemsg(ire_db_req_mp);
2003 				return (KS_IN_ADDR_MBCAST);
2004 			}
2005 			if (IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr)) {
2006 				freemsg(ire_db_req_mp);
2007 				return (KS_IN_ADDR_UNSPEC);
2008 			}
2009 			ire->ire_ipversion = IPV6_VERSION;
2010 			ire->ire_addr_v6 = sin6->sin6_addr;
2011 			break;	/* Out of switch. */
2012 		}
2013 		/*
2014 		 * Convert to an AF_INET sockaddr.  This means
2015 		 * the return messages will have the extra space, but
2016 		 * have AF_INET sockaddrs instead of AF_INET6.
2017 		 *
2018 		 * Yes, RFC 2367 isn't clear on what to do here w.r.t.
2019 		 * mapped addresses, but since AF_INET6 ::ffff:<v4> is
2020 		 * equal to AF_INET <v4>, it shouldnt be a huge
2021 		 * problem.
2022 		 */
2023 		ASSERT(&sin->sin_port == &sin6->sin6_port);
2024 		sin->sin_family = AF_INET;
2025 		IN6_V4MAPPED_TO_INADDR(&sin6->sin6_addr, &sin->sin_addr);
2026 		bzero(&sin->sin_zero, sizeof (sin->sin_zero));
2027 		/* FALLTHRU */
2028 	case AF_INET:
2029 		ire->ire_ipversion = IPV4_VERSION;
2030 		ire->ire_addr = sin->sin_addr.s_addr;
2031 		if (ire->ire_addr == INADDR_ANY) {
2032 			freemsg(ire_db_req_mp);
2033 			return (KS_IN_ADDR_UNSPEC);
2034 		}
2035 		if (CLASSD(ire->ire_addr)) {
2036 			freemsg(ire_db_req_mp);
2037 			return (KS_IN_ADDR_MBCAST);
2038 		}
2039 		break;
2040 	default:
2041 		freemsg(ire_db_req_mp);
2042 
2043 		switch (ext->sadb_ext_type) {
2044 		case SADB_EXT_ADDRESS_SRC:
2045 			diagnostic = SADB_X_DIAGNOSTIC_BAD_SRC_AF;
2046 			break;
2047 		case SADB_EXT_ADDRESS_DST:
2048 			diagnostic = SADB_X_DIAGNOSTIC_BAD_DST_AF;
2049 			break;
2050 		case SADB_EXT_ADDRESS_PROXY:
2051 			diagnostic = SADB_X_DIAGNOSTIC_BAD_PROXY_AF;
2052 			break;
2053 			/* There is no default, see above ASSERT. */
2054 		}
2055 
2056 		sadb_pfkey_error(pfkey_q, mp, EINVAL, diagnostic, serial);
2057 		return (KS_IN_ADDR_UNKNOWN);
2058 	}
2059 	ire_db_req_mp->b_cont = mp;
2060 
2061 	ASSERT(ip_q != NULL);
2062 	putnext(ip_q, ire_db_req_mp);
2063 	return (KS_IN_ADDR_UNKNOWN);
2064 }
2065 
2066 /*
2067  * For the case of src == unspecified AF_INET6, and dst == AF_INET, convert
2068  * the source to AF_INET.
2069  */
2070 void
2071 sadb_srcaddrfix(keysock_in_t *ksi)
2072 {
2073 	struct sockaddr_in *src;
2074 	struct sockaddr_in6 *dst;
2075 	sadb_address_t *srcext, *dstext;
2076 	uint16_t sport;
2077 
2078 	if (ksi->ks_in_srctype != KS_IN_ADDR_UNSPEC ||
2079 	    ksi->ks_in_dsttype == KS_IN_ADDR_NOTTHERE)
2080 		return;
2081 
2082 	dstext = (sadb_address_t *)ksi->ks_in_extv[SADB_EXT_ADDRESS_DST];
2083 	dst = (struct sockaddr_in6 *)(dstext + 1);
2084 	srcext = (sadb_address_t *)ksi->ks_in_extv[SADB_EXT_ADDRESS_SRC];
2085 	src = (struct sockaddr_in *)(srcext + 1);
2086 
2087 	/*
2088 	 * If unspecified IPv4 source, but an IPv6 dest, don't bother
2089 	 * fixing, as it should be an error.
2090 	 */
2091 	if (dst->sin6_family == src->sin_family ||
2092 	    src->sin_family == AF_INET)
2093 		return;
2094 
2095 	/*
2096 	 * Convert "src" to AF_INET INADDR_ANY.  We rely on sin_port being
2097 	 * in the same place for sockaddr_in and sockaddr_in6.
2098 	 */
2099 	sport = src->sin_port;
2100 	bzero(src, sizeof (*src));
2101 	src->sin_family = AF_INET;
2102 	src->sin_port = sport;
2103 }
2104 
2105 /*
2106  * Set the results in "addrtype", given an IRE as requested by
2107  * sadb_addrcheck().
2108  */
2109 int
2110 sadb_addrset(ire_t *ire)
2111 {
2112 	if ((ire->ire_type & IRE_BROADCAST) ||
2113 	    (ire->ire_ipversion == IPV4_VERSION && CLASSD(ire->ire_addr)) ||
2114 	    (ire->ire_ipversion == IPV6_VERSION &&
2115 		IN6_IS_ADDR_MULTICAST(&(ire->ire_addr_v6))))
2116 		return (KS_IN_ADDR_MBCAST);
2117 	if (ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK))
2118 		return (KS_IN_ADDR_ME);
2119 	return (KS_IN_ADDR_NOTME);
2120 }
2121 
2122 
2123 /*
2124  * Walker callback function to delete sa's based on src/dst address.
2125  * Assumes that we're called with *head locked, no other locks held;
2126  * Conveniently, and not coincidentally, this is both what sadb_walker
2127  * gives us and also what sadb_unlinkassoc expects.
2128  */
2129 
2130 struct sadb_purge_state
2131 {
2132 	uint32_t *src;
2133 	uint32_t *dst;
2134 	sa_family_t af;
2135 	boolean_t inbnd;
2136 	char *sidstr;
2137 	char *didstr;
2138 	uint16_t sidtype;
2139 	uint16_t didtype;
2140 	uint32_t kmproto;
2141 	mblk_t *mq;
2142 };
2143 
2144 static void
2145 sadb_purge_cb(isaf_t *head, ipsa_t *entry, void *cookie)
2146 {
2147 	struct sadb_purge_state *ps = (struct sadb_purge_state *)cookie;
2148 
2149 	ASSERT(MUTEX_HELD(&head->isaf_lock));
2150 
2151 	mutex_enter(&entry->ipsa_lock);
2152 
2153 	if ((entry->ipsa_state == IPSA_STATE_LARVAL) ||
2154 	    (ps->src != NULL &&
2155 		!IPSA_ARE_ADDR_EQUAL(entry->ipsa_srcaddr, ps->src, ps->af)) ||
2156 	    (ps->dst != NULL &&
2157 		!IPSA_ARE_ADDR_EQUAL(entry->ipsa_dstaddr, ps->dst, ps->af)) ||
2158 	    (ps->didstr != NULL &&
2159 		(entry->ipsa_dst_cid != NULL) &&
2160 		!(ps->didtype == entry->ipsa_dst_cid->ipsid_type &&
2161 		    strcmp(ps->didstr, entry->ipsa_dst_cid->ipsid_cid) == 0)) ||
2162 	    (ps->sidstr != NULL &&
2163 		(entry->ipsa_src_cid != NULL) &&
2164 		!(ps->sidtype == entry->ipsa_src_cid->ipsid_type &&
2165 		    strcmp(ps->sidstr, entry->ipsa_src_cid->ipsid_cid) == 0)) ||
2166 	    (ps->kmproto <= SADB_X_KMP_MAX && ps->kmproto != entry->ipsa_kmp)) {
2167 		mutex_exit(&entry->ipsa_lock);
2168 		return;
2169 	}
2170 
2171 	entry->ipsa_state = IPSA_STATE_DEAD;
2172 	(void) sadb_torch_assoc(head, entry, ps->inbnd, &ps->mq);
2173 }
2174 
2175 /*
2176  * Common code to purge an SA with a matching src or dst address.
2177  * Don't kill larval SA's in such a purge.
2178  */
2179 int
2180 sadb_purge_sa(mblk_t *mp, keysock_in_t *ksi, sadb_t *sp,
2181     int *diagnostic, queue_t *pfkey_q, queue_t *ip_q)
2182 {
2183 	sadb_address_t *dstext =
2184 	    (sadb_address_t *)ksi->ks_in_extv[SADB_EXT_ADDRESS_DST];
2185 	sadb_address_t *srcext =
2186 	    (sadb_address_t *)ksi->ks_in_extv[SADB_EXT_ADDRESS_SRC];
2187 	sadb_ident_t *dstid =
2188 	    (sadb_ident_t *)ksi->ks_in_extv[SADB_EXT_IDENTITY_DST];
2189 	sadb_ident_t *srcid =
2190 	    (sadb_ident_t *)ksi->ks_in_extv[SADB_EXT_IDENTITY_SRC];
2191 	sadb_x_kmc_t *kmc =
2192 	    (sadb_x_kmc_t *)ksi->ks_in_extv[SADB_X_EXT_KM_COOKIE];
2193 	struct sockaddr_in *src, *dst;
2194 	struct sockaddr_in6 *src6, *dst6;
2195 	struct sadb_purge_state ps;
2196 
2197 	/*
2198 	 * Don't worry about IPv6 v4-mapped addresses, sadb_addrcheck()
2199 	 * takes care of them.
2200 	 */
2201 
2202 	/* enforced by caller */
2203 	ASSERT((dstext != NULL) || (srcext != NULL));
2204 
2205 	ps.src = NULL;
2206 	ps.dst = NULL;
2207 #ifdef DEBUG
2208 	ps.af = (sa_family_t)-1;
2209 #endif
2210 	ps.mq = NULL;
2211 	ps.sidstr = NULL;
2212 	ps.didstr = NULL;
2213 	ps.kmproto = SADB_X_KMP_MAX + 1;
2214 
2215 	if (dstext != NULL) {
2216 		dst = (struct sockaddr_in *)(dstext + 1);
2217 		ps.af = dst->sin_family;
2218 		if (dst->sin_family == AF_INET6) {
2219 			dst6 = (struct sockaddr_in6 *)dst;
2220 			ps.dst = (uint32_t *)&dst6->sin6_addr;
2221 		} else {
2222 			ps.dst = (uint32_t *)&dst->sin_addr;
2223 		}
2224 	}
2225 
2226 	if (srcext != NULL) {
2227 		src = (struct sockaddr_in *)(srcext + 1);
2228 		ps.af = src->sin_family;
2229 		if (src->sin_family == AF_INET6) {
2230 			src6 = (struct sockaddr_in6 *)(srcext + 1);
2231 			ps.src = (uint32_t *)&src6->sin6_addr;
2232 		} else {
2233 			ps.src = (uint32_t *)&src->sin_addr;
2234 		}
2235 
2236 		if (dstext != NULL) {
2237 			if (src->sin_family != dst->sin_family) {
2238 				*diagnostic = SADB_X_DIAGNOSTIC_AF_MISMATCH;
2239 				return (EINVAL);
2240 			}
2241 		}
2242 	}
2243 	ASSERT(ps.af != (sa_family_t)-1);
2244 
2245 	if (dstid != NULL) {
2246 		/*
2247 		 * NOTE:  May need to copy string in the future
2248 		 * if the inbound keysock message disappears for some strange
2249 		 * reason.
2250 		 */
2251 		ps.didstr = (char *)(dstid + 1);
2252 		ps.didtype = dstid->sadb_ident_type;
2253 	}
2254 
2255 	if (srcid != NULL) {
2256 		/*
2257 		 * NOTE:  May need to copy string in the future
2258 		 * if the inbound keysock message disappears for some strange
2259 		 * reason.
2260 		 */
2261 		ps.sidstr = (char *)(srcid + 1);
2262 		ps.sidtype = srcid->sadb_ident_type;
2263 	}
2264 
2265 	if (kmc != NULL)
2266 		ps.kmproto = kmc->sadb_x_kmc_proto;
2267 
2268 	/*
2269 	 * This is simple, crude, and effective.
2270 	 * Unimplemented optimizations (TBD):
2271 	 * - we can limit how many places we search based on where we
2272 	 * think the SA is filed.
2273 	 * - if we get a dst address, we can hash based on dst addr to find
2274 	 * the correct bucket in the outbound table.
2275 	 */
2276 	ps.inbnd = B_TRUE;
2277 	sadb_walker(sp->sdb_if, sp->sdb_hashsize, sadb_purge_cb, &ps);
2278 	ps.inbnd = B_FALSE;
2279 	sadb_walker(sp->sdb_of, sp->sdb_hashsize, sadb_purge_cb, &ps);
2280 
2281 	if (ps.mq != NULL)
2282 		sadb_drain_torchq(ip_q, ps.mq);
2283 
2284 	ASSERT(mp->b_cont != NULL);
2285 	sadb_pfkey_echo(pfkey_q, mp, (sadb_msg_t *)mp->b_cont->b_rptr, ksi,
2286 	    NULL);
2287 	return (0);
2288 }
2289 
2290 /*
2291  * Common code to delete/get an SA.
2292  */
2293 int
2294 sadb_delget_sa(mblk_t *mp, keysock_in_t *ksi, sadbp_t *spp,
2295     int *diagnostic, queue_t *pfkey_q, boolean_t delete)
2296 {
2297 	sadb_sa_t *assoc = (sadb_sa_t *)ksi->ks_in_extv[SADB_EXT_SA];
2298 	sadb_address_t *srcext =
2299 	    (sadb_address_t *)ksi->ks_in_extv[SADB_EXT_ADDRESS_SRC];
2300 	sadb_address_t *dstext =
2301 	    (sadb_address_t *)ksi->ks_in_extv[SADB_EXT_ADDRESS_DST];
2302 	struct sockaddr_in *src, *dst;
2303 	struct sockaddr_in6 *src6, *dst6;
2304 	sadb_t *sp;
2305 	ipsa_t *outbound_target, *inbound_target;
2306 	isaf_t *inbound, *outbound;
2307 	uint32_t *srcaddr, *dstaddr;
2308 	mblk_t *torchq = NULL;
2309 	sa_family_t af;
2310 
2311 	if (dstext == NULL) {
2312 		*diagnostic = SADB_X_DIAGNOSTIC_MISSING_DST;
2313 		return (EINVAL);
2314 	}
2315 	if (assoc == NULL) {
2316 		*diagnostic = SADB_X_DIAGNOSTIC_MISSING_SA;
2317 		return (EINVAL);
2318 	}
2319 
2320 	/*
2321 	 * Don't worry about IPv6 v4-mapped addresses, sadb_addrcheck()
2322 	 * takes care of them.
2323 	 */
2324 
2325 	dst = (struct sockaddr_in *)(dstext + 1);
2326 	af = dst->sin_family;
2327 	if (af == AF_INET6) {
2328 		sp = &spp->s_v6;
2329 		dst6 = (struct sockaddr_in6 *)dst;
2330 		dstaddr = (uint32_t *)&dst6->sin6_addr;
2331 		if (srcext != NULL) {
2332 			src6 = (struct sockaddr_in6 *)(srcext + 1);
2333 			srcaddr = (uint32_t *)&src6->sin6_addr;
2334 			if (src6->sin6_family != AF_INET6) {
2335 				*diagnostic = SADB_X_DIAGNOSTIC_AF_MISMATCH;
2336 				return (EINVAL);
2337 			}
2338 		} else {
2339 			srcaddr = ALL_ZEROES_PTR;
2340 		}
2341 
2342 		outbound = OUTBOUND_BUCKET_V6(sp, *(uint32_t *)dstaddr);
2343 	} else {
2344 		sp = &spp->s_v4;
2345 		dstaddr = (uint32_t *)&dst->sin_addr;
2346 		if (srcext != NULL) {
2347 			src = (struct sockaddr_in *)(srcext + 1);
2348 			srcaddr = (uint32_t *)&src->sin_addr;
2349 			if (src->sin_family != AF_INET) {
2350 				*diagnostic = SADB_X_DIAGNOSTIC_AF_MISMATCH;
2351 				return (EINVAL);
2352 			}
2353 		} else {
2354 			srcaddr = ALL_ZEROES_PTR;
2355 		}
2356 		outbound = OUTBOUND_BUCKET_V4(sp, *(uint32_t *)dstaddr);
2357 	}
2358 
2359 	inbound = INBOUND_BUCKET(sp, assoc->sadb_sa_spi);
2360 
2361 	/* Lock down both buckets. */
2362 	mutex_enter(&outbound->isaf_lock);
2363 	mutex_enter(&inbound->isaf_lock);
2364 
2365 	/* Try outbound first. */
2366 	outbound_target = ipsec_getassocbyspi(outbound, assoc->sadb_sa_spi,
2367 	    srcaddr, dstaddr, af);
2368 
2369 	if (outbound_target == NULL || outbound_target->ipsa_haspeer) {
2370 		inbound_target = ipsec_getassocbyspi(inbound,
2371 		    assoc->sadb_sa_spi, srcaddr, dstaddr, af);
2372 	} else {
2373 		inbound_target = NULL;
2374 	}
2375 
2376 	if (outbound_target == NULL && inbound_target == NULL) {
2377 		mutex_exit(&inbound->isaf_lock);
2378 		mutex_exit(&outbound->isaf_lock);
2379 		return (ESRCH);
2380 	}
2381 
2382 	if (delete) {
2383 		/* At this point, I have one or two SAs to be deleted. */
2384 		if (outbound_target != NULL) {
2385 			mutex_enter(&outbound_target->ipsa_lock);
2386 			outbound_target->ipsa_state = IPSA_STATE_DEAD;
2387 			(void) sadb_torch_assoc(outbound, outbound_target,
2388 			    B_FALSE, &torchq);
2389 		}
2390 
2391 		if (inbound_target != NULL) {
2392 			mutex_enter(&inbound_target->ipsa_lock);
2393 			inbound_target->ipsa_state = IPSA_STATE_DEAD;
2394 			(void) sadb_torch_assoc(inbound, inbound_target,
2395 			    B_TRUE, &torchq);
2396 		}
2397 	}
2398 
2399 	mutex_exit(&inbound->isaf_lock);
2400 	mutex_exit(&outbound->isaf_lock);
2401 
2402 	if (torchq != NULL)
2403 		sadb_drain_torchq(spp->s_ip_q, torchq);
2404 
2405 	/*
2406 	 * Because of the multi-line macro nature of IPSA_REFRELE, keep
2407 	 * them in { }.
2408 	 */
2409 	ASSERT(mp->b_cont != NULL);
2410 	sadb_pfkey_echo(pfkey_q, mp, (sadb_msg_t *)mp->b_cont->b_rptr, ksi,
2411 	    (outbound_target != NULL ? outbound_target : inbound_target));
2412 
2413 	if (outbound_target != NULL) {
2414 		IPSA_REFRELE(outbound_target);
2415 	}
2416 	if (inbound_target != NULL) {
2417 		IPSA_REFRELE(inbound_target);
2418 	}
2419 
2420 	return (0);
2421 }
2422 
2423 /*
2424  * Common code to set ipsa_unique_id; used from both add and update paths.
2425  */
2426 static void
2427 sadb_set_unique(ipsa_t *sa, uint8_t proto,
2428     struct sockaddr_in *src, struct sockaddr_in *dst)
2429 {
2430 	/* Assume that ports are in the same place for INET and INET6 */
2431 	uint16_t srcport = src->sin_port;
2432 	uint16_t dstport = dst->sin_port;
2433 
2434 	sa->ipsa_unique_id = SA_UNIQUE_ID(srcport, dstport, proto);
2435 	sa->ipsa_unique_mask = SA_UNIQUE_MASK(srcport, dstport, proto);
2436 	if (sa->ipsa_unique_mask != 0)
2437 		sa->ipsa_flags |= IPSA_F_UNIQUE;
2438 }
2439 
2440 
2441 /*
2442  * Initialize the mechanism parameters associated with an SA.
2443  * These parameters can be shared by multiple packets, which saves
2444  * us from the overhead of consulting the algorithm table for
2445  * each packet.
2446  */
2447 static void
2448 sadb_init_alginfo(ipsa_t *sa)
2449 {
2450 	ipsec_alginfo_t *alg;
2451 
2452 	mutex_enter(&alg_lock);
2453 
2454 	if (sa->ipsa_encrkey != NULL) {
2455 		alg = ipsec_alglists[IPSEC_ALG_ENCR][sa->ipsa_encr_alg];
2456 		if (alg != NULL && ALG_VALID(alg)) {
2457 			sa->ipsa_emech.cm_type = alg->alg_mech_type;
2458 			sa->ipsa_emech.cm_param = NULL;
2459 			sa->ipsa_emech.cm_param_len = 0;
2460 			sa->ipsa_iv_len = alg->alg_datalen;
2461 		} else
2462 			sa->ipsa_emech.cm_type = CRYPTO_MECHANISM_INVALID;
2463 	}
2464 
2465 	if (sa->ipsa_authkey != NULL) {
2466 		alg = ipsec_alglists[IPSEC_ALG_AUTH][sa->ipsa_auth_alg];
2467 		if (alg != NULL && ALG_VALID(alg)) {
2468 			sa->ipsa_amech.cm_type = alg->alg_mech_type;
2469 			sa->ipsa_amech.cm_param = (char *)&sa->ipsa_mac_len;
2470 			sa->ipsa_amech.cm_param_len = sizeof (size_t);
2471 			sa->ipsa_mac_len = (size_t)alg->alg_datalen;
2472 		} else
2473 			sa->ipsa_amech.cm_type = CRYPTO_MECHANISM_INVALID;
2474 	}
2475 
2476 	mutex_exit(&alg_lock);
2477 }
2478 
2479 
2480 /*
2481  * This function is called from consumers that need to insert a fully-grown
2482  * security association into its tables.  This function takes into account that
2483  * SAs can be "inbound", "outbound", or "both".	 The "primary" and "secondary"
2484  * hash bucket parameters are set in order of what the SA will be most of the
2485  * time.  (For example, an SA with an unspecified source, and a multicast
2486  * destination will primarily be an outbound SA.  OTOH, if that destination
2487  * is unicast for this node, then the SA will primarily be inbound.)
2488  *
2489  * It takes a lot of parameters because even if clone is B_FALSE, this needs
2490  * to check both buckets for purposes of collision.
2491  *
2492  * Return 0 upon success.  Return various errnos (ENOMEM, EEXIST) for
2493  * various error conditions.  No need to set samsg->sadb_x_msg_diagnostic with
2494  * additional diagnostic information because ENOMEM and EEXIST are self-
2495  * explanitory.
2496  */
2497 int
2498 sadb_common_add(queue_t *ip_q, queue_t *pfkey_q, mblk_t *mp, sadb_msg_t *samsg,
2499     keysock_in_t *ksi, isaf_t *primary, isaf_t *secondary,
2500     ipsa_t *newbie, boolean_t clone, boolean_t is_inbound)
2501 {
2502 	ipsa_t *newbie_clone = NULL, *scratch;
2503 	sadb_sa_t *assoc = (sadb_sa_t *)ksi->ks_in_extv[SADB_EXT_SA];
2504 	sadb_address_t *srcext =
2505 	    (sadb_address_t *)ksi->ks_in_extv[SADB_EXT_ADDRESS_SRC];
2506 	sadb_address_t *dstext =
2507 	    (sadb_address_t *)ksi->ks_in_extv[SADB_EXT_ADDRESS_DST];
2508 	sadb_address_t *proxyext =
2509 	    (sadb_address_t *)ksi->ks_in_extv[SADB_EXT_ADDRESS_PROXY];
2510 	sadb_address_t *natt_loc_ext =
2511 	    (sadb_address_t *)ksi->ks_in_extv[SADB_X_EXT_ADDRESS_NATT_LOC];
2512 	sadb_address_t *natt_rem_ext =
2513 	    (sadb_address_t *)ksi->ks_in_extv[SADB_X_EXT_ADDRESS_NATT_REM];
2514 	sadb_x_kmc_t *kmcext =
2515 	    (sadb_x_kmc_t *)ksi->ks_in_extv[SADB_X_EXT_KM_COOKIE];
2516 	sadb_key_t *akey = (sadb_key_t *)ksi->ks_in_extv[SADB_EXT_KEY_AUTH];
2517 	sadb_key_t *ekey = (sadb_key_t *)ksi->ks_in_extv[SADB_EXT_KEY_ENCRYPT];
2518 #if 0
2519 	/*
2520 	 * XXXMLS - When Trusted Solaris or Multi-Level Secure functionality
2521 	 * comes to ON, examine these if 0'ed fragments.  Look for XXXMLS.
2522 	 */
2523 	sadb_sens_t *sens = (sadb_sens_t *);
2524 #endif
2525 	struct sockaddr_in *src, *dst, *proxy, *natt_loc, *natt_rem;
2526 	struct sockaddr_in6 *src6, *dst6, *proxy6, *natt_loc6, *natt_rem6;
2527 	sadb_lifetime_t *soft =
2528 	    (sadb_lifetime_t *)ksi->ks_in_extv[SADB_EXT_LIFETIME_SOFT];
2529 	sadb_lifetime_t *hard =
2530 	    (sadb_lifetime_t *)ksi->ks_in_extv[SADB_EXT_LIFETIME_HARD];
2531 	sa_family_t af;
2532 	int error = 0;
2533 	boolean_t isupdate = (newbie != NULL);
2534 	uint32_t *src_addr_ptr, *dst_addr_ptr, *proxy_addr_ptr;
2535 	uint32_t *natt_loc_ptr = NULL, *natt_rem_ptr = NULL;
2536 	uint32_t running_sum = 0;
2537 	mblk_t *ctl_mp = NULL;
2538 
2539 	src = (struct sockaddr_in *)(srcext + 1);
2540 	src6 = (struct sockaddr_in6 *)(srcext + 1);
2541 	dst = (struct sockaddr_in *)(dstext + 1);
2542 	dst6 = (struct sockaddr_in6 *)(dstext + 1);
2543 	if (proxyext != NULL) {
2544 		proxy = (struct sockaddr_in *)(proxyext + 1);
2545 		proxy6 = (struct sockaddr_in6 *)(proxyext + 1);
2546 	} else {
2547 		proxy = NULL;
2548 		proxy6 = NULL;
2549 	}
2550 
2551 	af = src->sin_family;
2552 
2553 	if (af == AF_INET) {
2554 		src_addr_ptr = (uint32_t *)&src->sin_addr;
2555 		dst_addr_ptr = (uint32_t *)&dst->sin_addr;
2556 	} else {
2557 		ASSERT(af == AF_INET6);
2558 		src_addr_ptr = (uint32_t *)&src6->sin6_addr;
2559 		dst_addr_ptr = (uint32_t *)&dst6->sin6_addr;
2560 	}
2561 
2562 	if (!isupdate) {
2563 		newbie = sadb_makelarvalassoc(assoc->sadb_sa_spi,
2564 		    src_addr_ptr, dst_addr_ptr, af);
2565 		if (newbie == NULL)
2566 			return (ENOMEM);
2567 	}
2568 
2569 	mutex_enter(&newbie->ipsa_lock);
2570 
2571 	if (proxy != NULL) {
2572 		if (proxy->sin_family == AF_INET) {
2573 			proxy_addr_ptr = (uint32_t *)&proxy->sin_addr;
2574 		} else {
2575 			ASSERT(proxy->sin_family == AF_INET6);
2576 			proxy_addr_ptr = (uint32_t *)&proxy6->sin6_addr;
2577 		}
2578 		newbie->ipsa_proxyfam = proxy->sin_family;
2579 
2580 		IPSA_COPY_ADDR(newbie->ipsa_proxysrc, proxy_addr_ptr,
2581 		    newbie->ipsa_proxyfam);
2582 	}
2583 
2584 #define	DOWN_SUM(x) (x) = ((x) & 0xFFFF) +	 ((x) >> 16)
2585 
2586 
2587 	if (natt_rem_ext != NULL) {
2588 		uint32_t l_src;
2589 		uint32_t l_rem;
2590 
2591 		natt_rem = (struct sockaddr_in *)(natt_rem_ext + 1);
2592 		natt_rem6 = (struct sockaddr_in6 *)(natt_rem_ext + 1);
2593 
2594 		if (natt_rem->sin_family == AF_INET) {
2595 			natt_rem_ptr = (uint32_t *)(&natt_rem->sin_addr);
2596 			newbie->ipsa_remote_port = natt_rem->sin_port;
2597 			l_src = *src_addr_ptr;
2598 			l_rem = *natt_rem_ptr;
2599 		} else {
2600 			if (!IN6_IS_ADDR_V4MAPPED(&natt_rem6->sin6_addr)) {
2601 				goto error;
2602 			}
2603 			ASSERT(natt_rem->sin_family == AF_INET6);
2604 
2605 			natt_rem_ptr = ((uint32_t *)
2606 			    (&natt_rem6->sin6_addr)) + 3;
2607 			newbie->ipsa_remote_port = natt_rem6->sin6_port;
2608 			l_src = *src_addr_ptr;
2609 			l_rem = *natt_rem_ptr;
2610 		}
2611 		IPSA_COPY_ADDR(newbie->ipsa_natt_addr_rem, natt_rem_ptr, af);
2612 
2613 		l_src = ntohl(l_src);
2614 		DOWN_SUM(l_src);
2615 		DOWN_SUM(l_src);
2616 		l_rem = ntohl(l_rem);
2617 		DOWN_SUM(l_rem);
2618 		DOWN_SUM(l_rem);
2619 
2620 		/*
2621 		 * We're 1's complement for checksums, so check for wraparound
2622 		 * here.
2623 		 */
2624 		if (l_rem > l_src)
2625 			l_src--;
2626 
2627 		running_sum += l_src - l_rem;
2628 
2629 		DOWN_SUM(running_sum);
2630 		DOWN_SUM(running_sum);
2631 	}
2632 
2633 	if (natt_loc_ext != NULL) {
2634 		uint32_t l_dst;
2635 		uint32_t l_loc;
2636 
2637 		natt_loc = (struct sockaddr_in *)(natt_loc_ext + 1);
2638 		natt_loc6 = (struct sockaddr_in6 *)(natt_loc_ext + 1);
2639 
2640 		if (natt_loc->sin_family == AF_INET) {
2641 			natt_loc_ptr = (uint32_t *)&natt_loc->sin_addr;
2642 			l_dst = *dst_addr_ptr;
2643 			l_loc = *natt_loc_ptr;
2644 
2645 		} else {
2646 			if (!IN6_IS_ADDR_V4MAPPED(&natt_loc6->sin6_addr)) {
2647 				goto error;
2648 			}
2649 			ASSERT(natt_loc->sin_family == AF_INET6);
2650 			natt_loc_ptr = ((uint32_t *)&natt_loc6->sin6_addr) + 3;
2651 			l_dst = *dst_addr_ptr;
2652 			l_loc = *natt_loc_ptr;
2653 
2654 		}
2655 		IPSA_COPY_ADDR(newbie->ipsa_natt_addr_loc, natt_loc_ptr, af);
2656 
2657 		l_loc = ntohl(l_loc);
2658 		DOWN_SUM(l_loc);
2659 		DOWN_SUM(l_loc);
2660 		l_dst = ntohl(l_dst);
2661 		DOWN_SUM(l_dst);
2662 		DOWN_SUM(l_dst);
2663 
2664 		/*
2665 		 * We're 1's complement for checksums, so check for wraparound
2666 		 * here.
2667 		 */
2668 		if (l_loc > l_dst)
2669 			l_dst--;
2670 
2671 		running_sum += l_dst - l_loc;
2672 		DOWN_SUM(running_sum);
2673 		DOWN_SUM(running_sum);
2674 	}
2675 
2676 	newbie->ipsa_inbound_cksum = running_sum;
2677 #undef DOWN_SUM
2678 
2679 	newbie->ipsa_type = samsg->sadb_msg_satype;
2680 	ASSERT(assoc->sadb_sa_state == SADB_SASTATE_MATURE);
2681 	newbie->ipsa_auth_alg = assoc->sadb_sa_auth;
2682 	newbie->ipsa_encr_alg = assoc->sadb_sa_encrypt;
2683 	newbie->ipsa_flags = assoc->sadb_sa_flags;
2684 	/*
2685 	 * If unspecified source address, force replay_wsize to 0.
2686 	 * This is because an SA that has multiple sources of secure
2687 	 * traffic cannot enforce a replay counter w/o synchronizing the
2688 	 * senders.
2689 	 */
2690 	if (ksi->ks_in_srctype != KS_IN_ADDR_UNSPEC)
2691 		newbie->ipsa_replay_wsize = assoc->sadb_sa_replay;
2692 	else
2693 		newbie->ipsa_replay_wsize = 0;
2694 
2695 	(void) drv_getparm(TIME, &newbie->ipsa_addtime);
2696 
2697 	/* Set unique value */
2698 	sadb_set_unique(newbie, dstext->sadb_address_proto, src, dst);
2699 
2700 	if (kmcext != NULL) {
2701 		newbie->ipsa_kmp = kmcext->sadb_x_kmc_proto;
2702 		newbie->ipsa_kmc = kmcext->sadb_x_kmc_cookie;
2703 	}
2704 
2705 	/*
2706 	 * XXX CURRENT lifetime checks MAY BE needed for an UPDATE.
2707 	 * The spec says that one can update current lifetimes, but
2708 	 * that seems impractical, especially in the larval-to-mature
2709 	 * update that this function performs.
2710 	 */
2711 	if (soft != NULL) {
2712 		newbie->ipsa_softaddlt = soft->sadb_lifetime_addtime;
2713 		newbie->ipsa_softuselt = soft->sadb_lifetime_usetime;
2714 		newbie->ipsa_softbyteslt = soft->sadb_lifetime_bytes;
2715 		newbie->ipsa_softalloc = soft->sadb_lifetime_allocations;
2716 		SET_EXPIRE(newbie, softaddlt, softexpiretime);
2717 	}
2718 	if (hard != NULL) {
2719 		newbie->ipsa_hardaddlt = hard->sadb_lifetime_addtime;
2720 		newbie->ipsa_harduselt = hard->sadb_lifetime_usetime;
2721 		newbie->ipsa_hardbyteslt = hard->sadb_lifetime_bytes;
2722 		newbie->ipsa_hardalloc = hard->sadb_lifetime_allocations;
2723 		SET_EXPIRE(newbie, hardaddlt, hardexpiretime);
2724 	}
2725 
2726 	newbie->ipsa_authtmpl = NULL;
2727 	newbie->ipsa_encrtmpl = NULL;
2728 
2729 	if (akey != NULL) {
2730 		newbie->ipsa_authkeybits = akey->sadb_key_bits;
2731 		newbie->ipsa_authkeylen = SADB_1TO8(akey->sadb_key_bits);
2732 		/* In case we have to round up to the next byte... */
2733 		if ((akey->sadb_key_bits & 0x7) != 0)
2734 			newbie->ipsa_authkeylen++;
2735 		newbie->ipsa_authkey = kmem_alloc(newbie->ipsa_authkeylen,
2736 		    KM_NOSLEEP);
2737 		if (newbie->ipsa_authkey == NULL) {
2738 			error = ENOMEM;
2739 			mutex_exit(&newbie->ipsa_lock);
2740 			goto error;
2741 		}
2742 		bcopy(akey + 1, newbie->ipsa_authkey, newbie->ipsa_authkeylen);
2743 		bzero(akey + 1, newbie->ipsa_authkeylen);
2744 
2745 		/*
2746 		 * Pre-initialize the kernel crypto framework key
2747 		 * structure.
2748 		 */
2749 		newbie->ipsa_kcfauthkey.ck_format = CRYPTO_KEY_RAW;
2750 		newbie->ipsa_kcfauthkey.ck_length = newbie->ipsa_authkeybits;
2751 		newbie->ipsa_kcfauthkey.ck_data = newbie->ipsa_authkey;
2752 
2753 		mutex_enter(&alg_lock);
2754 		error = ipsec_create_ctx_tmpl(newbie, IPSEC_ALG_AUTH);
2755 		mutex_exit(&alg_lock);
2756 		if (error != 0) {
2757 			mutex_exit(&newbie->ipsa_lock);
2758 			goto error;
2759 		}
2760 	}
2761 
2762 	if (ekey != NULL) {
2763 		newbie->ipsa_encrkeybits = ekey->sadb_key_bits;
2764 		newbie->ipsa_encrkeylen = SADB_1TO8(ekey->sadb_key_bits);
2765 		/* In case we have to round up to the next byte... */
2766 		if ((ekey->sadb_key_bits & 0x7) != 0)
2767 			newbie->ipsa_encrkeylen++;
2768 		newbie->ipsa_encrkey = kmem_alloc(newbie->ipsa_encrkeylen,
2769 		    KM_NOSLEEP);
2770 		if (newbie->ipsa_encrkey == NULL) {
2771 			error = ENOMEM;
2772 			mutex_exit(&newbie->ipsa_lock);
2773 			goto error;
2774 		}
2775 		bcopy(ekey + 1, newbie->ipsa_encrkey, newbie->ipsa_encrkeylen);
2776 		/* XXX is this safe w.r.t db_ref, etc? */
2777 		bzero(ekey + 1, newbie->ipsa_encrkeylen);
2778 
2779 		/*
2780 		 * Pre-initialize the kernel crypto framework key
2781 		 * structure.
2782 		 */
2783 		newbie->ipsa_kcfencrkey.ck_format = CRYPTO_KEY_RAW;
2784 		newbie->ipsa_kcfencrkey.ck_length = newbie->ipsa_encrkeybits;
2785 		newbie->ipsa_kcfencrkey.ck_data = newbie->ipsa_encrkey;
2786 
2787 		mutex_enter(&alg_lock);
2788 		error = ipsec_create_ctx_tmpl(newbie, IPSEC_ALG_ENCR);
2789 		mutex_exit(&alg_lock);
2790 		if (error != 0) {
2791 			mutex_exit(&newbie->ipsa_lock);
2792 			goto error;
2793 		}
2794 	}
2795 
2796 	sadb_init_alginfo(newbie);
2797 
2798 	/*
2799 	 * Ptrs to processing functions.
2800 	 */
2801 	if (newbie->ipsa_type == SADB_SATYPE_ESP)
2802 		ipsecesp_init_funcs(newbie);
2803 	else
2804 		ipsecah_init_funcs(newbie);
2805 	ASSERT(newbie->ipsa_output_func != NULL &&
2806 	    newbie->ipsa_input_func != NULL);
2807 
2808 	/*
2809 	 * Certificate ID stuff.
2810 	 */
2811 	if (ksi->ks_in_extv[SADB_EXT_IDENTITY_SRC] != NULL) {
2812 		sadb_ident_t *id =
2813 		    (sadb_ident_t *)ksi->ks_in_extv[SADB_EXT_IDENTITY_SRC];
2814 
2815 		/*
2816 		 * Can assume strlen() will return okay because ext_check() in
2817 		 * keysock.c prepares the string for us.
2818 		 */
2819 		newbie->ipsa_src_cid = ipsid_lookup(id->sadb_ident_type,
2820 		    (char *)(id+1));
2821 		if (newbie->ipsa_src_cid == NULL) {
2822 			error = ENOMEM;
2823 			mutex_exit(&newbie->ipsa_lock);
2824 			goto error;
2825 		}
2826 	}
2827 
2828 	if (ksi->ks_in_extv[SADB_EXT_IDENTITY_DST] != NULL) {
2829 		sadb_ident_t *id =
2830 		    (sadb_ident_t *)ksi->ks_in_extv[SADB_EXT_IDENTITY_DST];
2831 
2832 		/*
2833 		 * Can assume strlen() will return okay because ext_check() in
2834 		 * keysock.c prepares the string for us.
2835 		 */
2836 		newbie->ipsa_dst_cid = ipsid_lookup(id->sadb_ident_type,
2837 		    (char *)(id+1));
2838 		if (newbie->ipsa_dst_cid == NULL) {
2839 			error = ENOMEM;
2840 			mutex_exit(&newbie->ipsa_lock);
2841 			goto error;
2842 		}
2843 	}
2844 
2845 #if 0
2846 	/* XXXMLS  SENSITIVITY handling code. */
2847 	if (sens != NULL) {
2848 		int i;
2849 		uint64_t *bitmap = (uint64_t *)(sens + 1);
2850 
2851 		newbie->ipsa_dpd = sens->sadb_sens_dpd;
2852 		newbie->ipsa_senslevel = sens->sadb_sens_sens_level;
2853 		newbie->ipsa_integlevel = sens->sadb_sens_integ_level;
2854 		newbie->ipsa_senslen = SADB_64TO8(sens->sadb_sens_sens_len);
2855 		newbie->ipsa_integlen = SADB_64TO8(sens->sadb_sens_integ_len);
2856 		newbie->ipsa_integ = kmem_alloc(newbie->ipsa_integlen,
2857 		    KM_NOSLEEP);
2858 		if (newbie->ipsa_integ == NULL) {
2859 			error = ENOMEM;
2860 			mutex_exit(&newbie->ipsa_lock);
2861 			goto error;
2862 		}
2863 		newbie->ipsa_sens = kmem_alloc(newbie->ipsa_senslen,
2864 		    KM_NOSLEEP);
2865 		if (newbie->ipsa_sens == NULL) {
2866 			error = ENOMEM;
2867 			mutex_exit(&newbie->ipsa_lock);
2868 			goto error;
2869 		}
2870 		for (i = 0; i < sens->sadb_sens_sens_len; i++) {
2871 			newbie->ipsa_sens[i] = *bitmap;
2872 			bitmap++;
2873 		}
2874 		for (i = 0; i < sens->sadb_sens_integ_len; i++) {
2875 			newbie->ipsa_integ[i] = *bitmap;
2876 			bitmap++;
2877 		}
2878 	}
2879 
2880 #endif
2881 
2882 	/* now that the SA has been updated, set its new state */
2883 	newbie->ipsa_state = assoc->sadb_sa_state;
2884 
2885 	/*
2886 	 * The less locks I hold when doing an insertion and possible cloning,
2887 	 * the better!
2888 	 */
2889 	mutex_exit(&newbie->ipsa_lock);
2890 
2891 	if (clone) {
2892 		newbie_clone = sadb_cloneassoc(newbie);
2893 
2894 		if (newbie_clone == NULL) {
2895 			error = ENOMEM;
2896 			goto error;
2897 		}
2898 		newbie->ipsa_haspeer = B_TRUE;
2899 		newbie_clone->ipsa_haspeer = B_TRUE;
2900 	}
2901 
2902 	/*
2903 	 * Enter the bucket locks.  The order of entry is outbound,
2904 	 * inbound.  We map "primary" and "secondary" into outbound and inbound
2905 	 * based on the destination address type.  If the destination address
2906 	 * type is for a node that isn't mine (or potentially mine), the
2907 	 * "primary" bucket is the outbound one.
2908 	 */
2909 	if (ksi->ks_in_dsttype == KS_IN_ADDR_NOTME) {
2910 		/* primary == outbound */
2911 		mutex_enter(&primary->isaf_lock);
2912 		mutex_enter(&secondary->isaf_lock);
2913 	} else {
2914 		/* primary == inbound */
2915 		mutex_enter(&secondary->isaf_lock);
2916 		mutex_enter(&primary->isaf_lock);
2917 	}
2918 
2919 	IPSECHW_DEBUG(IPSECHW_SADB, ("sadb_common_add: spi = 0x%x\n",
2920 	    newbie->ipsa_spi));
2921 
2922 	/*
2923 	 * sadb_insertassoc() doesn't increment the reference
2924 	 * count.  We therefore have to increment the
2925 	 * reference count one more time to reflect the
2926 	 * pointers of the table that reference this SA.
2927 	 */
2928 	IPSA_REFHOLD(newbie);
2929 
2930 	if (isupdate) {
2931 		/*
2932 		 * Unlink from larval holding cell in the "inbound" fanout.
2933 		 */
2934 		ASSERT(newbie->ipsa_linklock == &primary->isaf_lock ||
2935 		    newbie->ipsa_linklock == &secondary->isaf_lock);
2936 		sadb_unlinkassoc(newbie);
2937 	}
2938 
2939 	mutex_enter(&newbie->ipsa_lock);
2940 	error = sadb_insertassoc(newbie, primary);
2941 	if (error == 0) {
2942 		ctl_mp = sadb_fmt_sa_req(DL_CO_SET, newbie->ipsa_type, newbie,
2943 		    is_inbound);
2944 	}
2945 	mutex_exit(&newbie->ipsa_lock);
2946 
2947 	if (error != 0) {
2948 		/*
2949 		 * Since sadb_insertassoc() failed, we must decrement the
2950 		 * refcount again so the cleanup code will actually free
2951 		 * the offending SA.
2952 		 */
2953 		IPSA_REFRELE(newbie);
2954 		goto error_unlock;
2955 	}
2956 
2957 	if (newbie_clone != NULL) {
2958 		mutex_enter(&newbie_clone->ipsa_lock);
2959 		error = sadb_insertassoc(newbie_clone, secondary);
2960 		mutex_exit(&newbie_clone->ipsa_lock);
2961 		if (error != 0) {
2962 			/* Collision in secondary table. */
2963 			sadb_unlinkassoc(newbie);  /* This does REFRELE. */
2964 			goto error_unlock;
2965 		}
2966 		IPSA_REFHOLD(newbie_clone);
2967 	} else {
2968 		ASSERT(primary != secondary);
2969 		scratch = ipsec_getassocbyspi(secondary, newbie->ipsa_spi,
2970 		    ALL_ZEROES_PTR, newbie->ipsa_dstaddr, af);
2971 		if (scratch != NULL) {
2972 			/* Collision in secondary table. */
2973 			sadb_unlinkassoc(newbie);  /* This does REFRELE. */
2974 			/* Set the error, since ipsec_getassocbyspi() can't. */
2975 			error = EEXIST;
2976 			goto error_unlock;
2977 		}
2978 	}
2979 
2980 	/* OKAY!  So let's do some reality check assertions. */
2981 
2982 	ASSERT(!MUTEX_HELD(&newbie->ipsa_lock));
2983 	ASSERT(newbie_clone == NULL || (!MUTEX_HELD(&newbie_clone->ipsa_lock)));
2984 	/*
2985 	 * If hardware acceleration could happen, send it.
2986 	 */
2987 	if (ctl_mp != NULL) {
2988 		putnext(ip_q, ctl_mp);
2989 		ctl_mp = NULL;
2990 	}
2991 
2992 error_unlock:
2993 
2994 	/*
2995 	 * We can exit the locks in any order.	Only entrance needs to
2996 	 * follow any protocol.
2997 	 */
2998 	mutex_exit(&secondary->isaf_lock);
2999 	mutex_exit(&primary->isaf_lock);
3000 
3001 	/* Common error point for this routine. */
3002 error:
3003 	if (newbie != NULL) {
3004 		IPSA_REFRELE(newbie);
3005 	}
3006 	if (newbie_clone != NULL) {
3007 		IPSA_REFRELE(newbie_clone);
3008 	}
3009 	if (ctl_mp != NULL)
3010 		freemsg(ctl_mp);
3011 
3012 	if (error == 0) {
3013 		/*
3014 		 * Construct favorable PF_KEY return message and send to
3015 		 * keysock.  (Q:  Do I need to pass "newbie"?  If I do,
3016 		 * make sure to REFHOLD, call, then REFRELE.)
3017 		 */
3018 		sadb_pfkey_echo(pfkey_q, mp, samsg, ksi, NULL);
3019 	}
3020 
3021 	return (error);
3022 }
3023 
3024 /*
3025  * Set the time of first use for a security association.  Update any
3026  * expiration times as a result.
3027  */
3028 void
3029 sadb_set_usetime(ipsa_t *assoc)
3030 {
3031 	mutex_enter(&assoc->ipsa_lock);
3032 	/*
3033 	 * Caller does check usetime before calling me usually, and
3034 	 * double-checking is better than a mutex_enter/exit hit.
3035 	 */
3036 	if (assoc->ipsa_usetime == 0) {
3037 		/*
3038 		 * This is redundant for outbound SA's, as
3039 		 * ipsec_getassocbyconn() sets the IPSA_F_USED flag already.
3040 		 * Inbound SAs, however, have no such protection.
3041 		 */
3042 		assoc->ipsa_flags |= IPSA_F_USED;
3043 
3044 		(void) drv_getparm(TIME, &assoc->ipsa_usetime);
3045 
3046 		/*
3047 		 * After setting the use time, see if we have a use lifetime
3048 		 * that would cause the actual SA expiration time to shorten.
3049 		 */
3050 		UPDATE_EXPIRE(assoc, softuselt, softexpiretime);
3051 		UPDATE_EXPIRE(assoc, harduselt, hardexpiretime);
3052 	}
3053 	mutex_exit(&assoc->ipsa_lock);
3054 }
3055 
3056 /*
3057  * Send up a PF_KEY expire message for this association.
3058  */
3059 static void
3060 sadb_expire_assoc(queue_t *pfkey_q, ipsa_t *assoc)
3061 {
3062 	mblk_t *mp, *mp1;
3063 	int alloclen, af;
3064 	sadb_msg_t *samsg;
3065 	sadb_lifetime_t *current, *expire;
3066 	sadb_sa_t *saext;
3067 	uint8_t *end;
3068 
3069 	ASSERT(MUTEX_HELD(&assoc->ipsa_lock));
3070 
3071 	/* Don't bother sending if there's no queue. */
3072 	if (pfkey_q == NULL)
3073 		return;
3074 
3075 	mp = sadb_keysock_out(0);
3076 	if (mp == NULL) {
3077 		/* cmn_err(CE_WARN, */
3078 		/*	"sadb_expire_assoc: Can't allocate KEYSOCK_OUT.\n"); */
3079 		return;
3080 	}
3081 
3082 	alloclen = sizeof (*samsg) + sizeof (*current) + sizeof (*expire) +
3083 	    2*sizeof (sadb_address_t) + sizeof (*saext);
3084 
3085 	af = assoc->ipsa_addrfam;
3086 	switch (af) {
3087 	case AF_INET:
3088 		alloclen += 2 * sizeof (struct sockaddr_in);
3089 		break;
3090 	case AF_INET6:
3091 		alloclen += 2 * sizeof (struct sockaddr_in6);
3092 		break;
3093 	default:
3094 		/* Won't happen unless there's a kernel bug. */
3095 		freeb(mp);
3096 		cmn_err(CE_WARN,
3097 		    "sadb_expire_assoc: Unknown address length.\n");
3098 		return;
3099 	}
3100 
3101 	mp->b_cont = allocb(alloclen, BPRI_HI);
3102 	if (mp->b_cont == NULL) {
3103 		freeb(mp);
3104 		/* cmn_err(CE_WARN, */
3105 		/*	"sadb_expire_assoc: Can't allocate message.\n"); */
3106 		return;
3107 	}
3108 
3109 	mp1 = mp;
3110 	mp = mp->b_cont;
3111 	end = mp->b_wptr + alloclen;
3112 
3113 	samsg = (sadb_msg_t *)mp->b_wptr;
3114 	mp->b_wptr += sizeof (*samsg);
3115 	samsg->sadb_msg_version = PF_KEY_V2;
3116 	samsg->sadb_msg_type = SADB_EXPIRE;
3117 	samsg->sadb_msg_errno = 0;
3118 	samsg->sadb_msg_satype = assoc->ipsa_type;
3119 	samsg->sadb_msg_len = SADB_8TO64(alloclen);
3120 	samsg->sadb_msg_reserved = 0;
3121 	samsg->sadb_msg_seq = 0;
3122 	samsg->sadb_msg_pid = 0;
3123 
3124 	saext = (sadb_sa_t *)mp->b_wptr;
3125 	mp->b_wptr += sizeof (*saext);
3126 	saext->sadb_sa_len = SADB_8TO64(sizeof (*saext));
3127 	saext->sadb_sa_exttype = SADB_EXT_SA;
3128 	saext->sadb_sa_spi = assoc->ipsa_spi;
3129 	saext->sadb_sa_replay = assoc->ipsa_replay_wsize;
3130 	saext->sadb_sa_state = assoc->ipsa_state;
3131 	saext->sadb_sa_auth = assoc->ipsa_auth_alg;
3132 	saext->sadb_sa_encrypt = assoc->ipsa_encr_alg;
3133 	saext->sadb_sa_flags = assoc->ipsa_flags;
3134 
3135 	current = (sadb_lifetime_t *)mp->b_wptr;
3136 	mp->b_wptr += sizeof (sadb_lifetime_t);
3137 	current->sadb_lifetime_len = SADB_8TO64(sizeof (*current));
3138 	current->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
3139 	current->sadb_lifetime_allocations = assoc->ipsa_alloc;
3140 	current->sadb_lifetime_bytes = assoc->ipsa_bytes;
3141 	current->sadb_lifetime_addtime = assoc->ipsa_addtime;
3142 	current->sadb_lifetime_usetime = assoc->ipsa_usetime;
3143 
3144 	expire = (sadb_lifetime_t *)mp->b_wptr;
3145 	mp->b_wptr += sizeof (*expire);
3146 	expire->sadb_lifetime_len = SADB_8TO64(sizeof (*expire));
3147 
3148 	if (assoc->ipsa_state == IPSA_STATE_DEAD) {
3149 		expire->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD;
3150 		expire->sadb_lifetime_allocations = assoc->ipsa_hardalloc;
3151 		expire->sadb_lifetime_bytes = assoc->ipsa_hardbyteslt;
3152 		expire->sadb_lifetime_addtime = assoc->ipsa_hardaddlt;
3153 		expire->sadb_lifetime_usetime = assoc->ipsa_harduselt;
3154 	} else {
3155 		ASSERT(assoc->ipsa_state == IPSA_STATE_DYING);
3156 		expire->sadb_lifetime_exttype = SADB_EXT_LIFETIME_SOFT;
3157 		expire->sadb_lifetime_allocations = assoc->ipsa_softalloc;
3158 		expire->sadb_lifetime_bytes = assoc->ipsa_softbyteslt;
3159 		expire->sadb_lifetime_addtime = assoc->ipsa_softaddlt;
3160 		expire->sadb_lifetime_usetime = assoc->ipsa_softuselt;
3161 	}
3162 
3163 	mp->b_wptr = sadb_make_addr_ext(mp->b_wptr, end, SADB_EXT_ADDRESS_SRC,
3164 	    af, assoc->ipsa_srcaddr, SA_SRCPORT(assoc), SA_PROTO(assoc));
3165 	ASSERT(mp->b_wptr != NULL);
3166 
3167 	mp->b_wptr = sadb_make_addr_ext(mp->b_wptr, end, SADB_EXT_ADDRESS_DST,
3168 	    af, assoc->ipsa_dstaddr, SA_DSTPORT(assoc), SA_PROTO(assoc));
3169 	ASSERT(mp->b_wptr != NULL);
3170 
3171 	/* Can just putnext, we're ready to go! */
3172 	putnext(pfkey_q, mp1);
3173 }
3174 
3175 /*
3176  * "Age" the SA with the number of bytes that was used to protect traffic.
3177  * Send an SADB_EXPIRE message if appropriate.	Return B_TRUE if there was
3178  * enough "charge" left in the SA to protect the data.	Return B_FALSE
3179  * otherwise.  (If B_FALSE is returned, the association either was, or became
3180  * DEAD.)
3181  */
3182 boolean_t
3183 sadb_age_bytes(queue_t *pfkey_q, ipsa_t *assoc, uint64_t bytes,
3184     boolean_t sendmsg)
3185 {
3186 	boolean_t rc = B_TRUE;
3187 	uint64_t newtotal;
3188 
3189 	mutex_enter(&assoc->ipsa_lock);
3190 	newtotal = assoc->ipsa_bytes + bytes;
3191 	if (assoc->ipsa_hardbyteslt != 0 &&
3192 	    newtotal >= assoc->ipsa_hardbyteslt) {
3193 		if (assoc->ipsa_state < IPSA_STATE_DEAD) {
3194 			/*
3195 			 * Send EXPIRE message to PF_KEY.  May wish to pawn
3196 			 * this off on another non-interrupt thread.  Also
3197 			 * unlink this SA immediately.
3198 			 */
3199 			assoc->ipsa_state = IPSA_STATE_DEAD;
3200 			if (sendmsg)
3201 				sadb_expire_assoc(pfkey_q, assoc);
3202 			/*
3203 			 * Set non-zero expiration time so sadb_age_assoc()
3204 			 * will work when reaping.
3205 			 */
3206 			assoc->ipsa_hardexpiretime = (time_t)1;
3207 		} /* Else someone beat me to it! */
3208 		rc = B_FALSE;
3209 	} else if (assoc->ipsa_softbyteslt != 0 &&
3210 	    (newtotal >= assoc->ipsa_softbyteslt)) {
3211 		if (assoc->ipsa_state < IPSA_STATE_DYING) {
3212 			/*
3213 			 * Send EXPIRE message to PF_KEY.  May wish to pawn
3214 			 * this off on another non-interrupt thread.
3215 			 */
3216 			assoc->ipsa_state = IPSA_STATE_DYING;
3217 			if (sendmsg)
3218 				sadb_expire_assoc(pfkey_q, assoc);
3219 		} /* Else someone beat me to it! */
3220 	}
3221 	if (rc == B_TRUE)
3222 		assoc->ipsa_bytes = newtotal;
3223 	mutex_exit(&assoc->ipsa_lock);
3224 	return (rc);
3225 }
3226 
3227 /*
3228  * Push one or more DL_CO_DELETE messages queued up by
3229  * sadb_torch_assoc down to the underlying driver now that it's a
3230  * convenient time for it (i.e., ipsa bucket locks not held).
3231  */
3232 static void
3233 sadb_drain_torchq(queue_t *q, mblk_t *mp)
3234 {
3235 	while (mp != NULL) {
3236 		mblk_t *next = mp->b_next;
3237 		mp->b_next = NULL;
3238 		if (q != NULL)
3239 			putnext(q, mp);
3240 		else
3241 			freemsg(mp);
3242 		mp = next;
3243 	}
3244 }
3245 
3246 /*
3247  * "Torch" an individual SA.  Returns NULL, so it can be tail-called from
3248  *     sadb_age_assoc().
3249  *
3250  * If SA is hardware-accelerated, and we can't allocate the mblk
3251  * containing the DL_CO_DELETE, just return; it will remain in the
3252  * table and be swept up by sadb_ager() in a subsequent pass.
3253  */
3254 static ipsa_t *
3255 sadb_torch_assoc(isaf_t *head, ipsa_t *sa, boolean_t inbnd, mblk_t **mq)
3256 {
3257 	mblk_t *mp;
3258 
3259 	ASSERT(MUTEX_HELD(&head->isaf_lock));
3260 	ASSERT(MUTEX_HELD(&sa->ipsa_lock));
3261 	ASSERT(sa->ipsa_state == IPSA_STATE_DEAD);
3262 
3263 	/*
3264 	 * Force cached SAs to be revalidated..
3265 	 */
3266 	head->isaf_gen++;
3267 
3268 	if (sa->ipsa_flags & IPSA_F_HW) {
3269 		mp = sadb_fmt_sa_req(DL_CO_DELETE, sa->ipsa_type, sa, inbnd);
3270 		if (mp == NULL) {
3271 			mutex_exit(&sa->ipsa_lock);
3272 			return (NULL);
3273 		}
3274 		mp->b_next = *mq;
3275 		*mq = mp;
3276 	}
3277 	mutex_exit(&sa->ipsa_lock);
3278 	sadb_unlinkassoc(sa);
3279 
3280 	return (NULL);
3281 }
3282 
3283 /*
3284  * Return "assoc" iff haspeer is true and I send an expire.  This allows
3285  * the consumers' aging functions to tidy up an expired SA's peer.
3286  */
3287 static ipsa_t *
3288 sadb_age_assoc(isaf_t *head, queue_t *pfkey_q, ipsa_t *assoc,
3289     time_t current, int reap_delay, boolean_t inbnd, mblk_t **mq)
3290 {
3291 	ipsa_t *retval = NULL;
3292 
3293 	ASSERT(MUTEX_HELD(&head->isaf_lock));
3294 
3295 	mutex_enter(&assoc->ipsa_lock);
3296 
3297 	if ((assoc->ipsa_state == IPSA_STATE_LARVAL) &&
3298 	    (assoc->ipsa_hardexpiretime <= current)) {
3299 		assoc->ipsa_state = IPSA_STATE_DEAD;
3300 		return (sadb_torch_assoc(head, assoc, inbnd, mq));
3301 	}
3302 
3303 	/*
3304 	 * Check lifetimes.  Fortunately, SA setup is done
3305 	 * such that there are only two times to look at,
3306 	 * softexpiretime, and hardexpiretime.
3307 	 *
3308 	 * Check hard first.
3309 	 */
3310 
3311 	if (assoc->ipsa_hardexpiretime != 0 &&
3312 	    assoc->ipsa_hardexpiretime <= current) {
3313 		if (assoc->ipsa_state == IPSA_STATE_DEAD)
3314 			return (sadb_torch_assoc(head, assoc, inbnd, mq));
3315 
3316 		/*
3317 		 * Send SADB_EXPIRE with hard lifetime, delay for unlinking.
3318 		 */
3319 		assoc->ipsa_state = IPSA_STATE_DEAD;
3320 		if (assoc->ipsa_haspeer) {
3321 			/*
3322 			 * If I return assoc, I have to bump up its
3323 			 * reference count to keep with the ipsa_t reference
3324 			 * count semantics.
3325 			 */
3326 			IPSA_REFHOLD(assoc);
3327 			retval = assoc;
3328 		}
3329 		sadb_expire_assoc(pfkey_q, assoc);
3330 		assoc->ipsa_hardexpiretime = current + reap_delay;
3331 	} else if (assoc->ipsa_softexpiretime != 0 &&
3332 	    assoc->ipsa_softexpiretime <= current &&
3333 	    assoc->ipsa_state < IPSA_STATE_DYING) {
3334 		/*
3335 		 * Send EXPIRE message to PF_KEY.  May wish to pawn
3336 		 * this off on another non-interrupt thread.
3337 		 */
3338 		assoc->ipsa_state = IPSA_STATE_DYING;
3339 		if (assoc->ipsa_haspeer) {
3340 			/*
3341 			 * If I return assoc, I have to bump up its
3342 			 * reference count to keep with the ipsa_t reference
3343 			 * count semantics.
3344 			 */
3345 			IPSA_REFHOLD(assoc);
3346 			retval = assoc;
3347 		}
3348 		sadb_expire_assoc(pfkey_q, assoc);
3349 	}
3350 
3351 	mutex_exit(&assoc->ipsa_lock);
3352 	return (retval);
3353 }
3354 
3355 /*
3356  * Called by a consumer protocol to do ther dirty work of reaping dead
3357  * Security Associations.
3358  */
3359 void
3360 sadb_ager(sadb_t *sp, queue_t *pfkey_q, queue_t *ip_q, int reap_delay)
3361 {
3362 	int i;
3363 	isaf_t *bucket;
3364 	ipsa_t *assoc, *spare;
3365 	iacqf_t *acqlist;
3366 	ipsacq_t *acqrec, *spareacq;
3367 	struct templist {
3368 		ipsa_t *ipsa;
3369 		struct templist *next;
3370 	} *haspeerlist = NULL, *newbie;
3371 	time_t current;
3372 	int outhash;
3373 	mblk_t *mq = NULL;
3374 
3375 	/*
3376 	 * Do my dirty work.  This includes aging real entries, aging
3377 	 * larvals, and aging outstanding ACQUIREs.
3378 	 *
3379 	 * I hope I don't tie up resources for too long.
3380 	 */
3381 
3382 	/* Snapshot current time now. */
3383 	(void) drv_getparm(TIME, &current);
3384 
3385 	/* Age acquires. */
3386 
3387 	for (i = 0; i < sp->sdb_hashsize; i++) {
3388 		acqlist = &sp->sdb_acq[i];
3389 		mutex_enter(&acqlist->iacqf_lock);
3390 		for (acqrec = acqlist->iacqf_ipsacq; acqrec != NULL;
3391 		    acqrec = spareacq) {
3392 			spareacq = acqrec->ipsacq_next;
3393 			if (current > acqrec->ipsacq_expire)
3394 				sadb_destroy_acquire(acqrec);
3395 		}
3396 		mutex_exit(&acqlist->iacqf_lock);
3397 	}
3398 
3399 	/* Age inbound associations. */
3400 	for (i = 0; i < sp->sdb_hashsize; i++) {
3401 		bucket = &(sp->sdb_if[i]);
3402 		mutex_enter(&bucket->isaf_lock);
3403 		for (assoc = bucket->isaf_ipsa; assoc != NULL;
3404 		    assoc = spare) {
3405 			spare = assoc->ipsa_next;
3406 			if (sadb_age_assoc(bucket, pfkey_q, assoc, current,
3407 			    reap_delay, B_TRUE, &mq) != NULL) {
3408 				/*
3409 				 * sadb_age_assoc() increments the refcnt,
3410 				 * effectively doing an IPSA_REFHOLD().
3411 				 */
3412 				newbie = kmem_alloc(sizeof (*newbie),
3413 				    KM_NOSLEEP);
3414 				if (newbie == NULL) {
3415 					/*
3416 					 * Don't forget to REFRELE().
3417 					 */
3418 					IPSA_REFRELE(assoc);
3419 					continue;	/* for loop... */
3420 				}
3421 				newbie->next = haspeerlist;
3422 				newbie->ipsa = assoc;
3423 				haspeerlist = newbie;
3424 			}
3425 		}
3426 		mutex_exit(&bucket->isaf_lock);
3427 	}
3428 
3429 	if (mq != NULL) {
3430 		sadb_drain_torchq(ip_q, mq);
3431 		mq = NULL;
3432 	}
3433 	/*
3434 	 * Haspeer cases will contain both IPv4 and IPv6.  This code
3435 	 * is address independent.
3436 	 */
3437 	while (haspeerlist != NULL) {
3438 		/* "spare" contains the SA that has a peer. */
3439 		spare = haspeerlist->ipsa;
3440 		newbie = haspeerlist;
3441 		haspeerlist = newbie->next;
3442 		kmem_free(newbie, sizeof (*newbie));
3443 		/*
3444 		 * Pick peer bucket based on addrfam.
3445 		 */
3446 		if (spare->ipsa_addrfam == AF_INET6) {
3447 			outhash = OUTBOUND_HASH_V6(sp,
3448 			    *((in6_addr_t *)&spare->ipsa_dstaddr));
3449 		} else {
3450 			outhash = OUTBOUND_HASH_V4(sp,
3451 			    *((ipaddr_t *)&spare->ipsa_dstaddr));
3452 		}
3453 		bucket = &(sp->sdb_of[outhash]);
3454 
3455 		mutex_enter(&bucket->isaf_lock);
3456 		assoc = ipsec_getassocbyspi(bucket, spare->ipsa_spi,
3457 		    spare->ipsa_srcaddr, spare->ipsa_dstaddr,
3458 		    spare->ipsa_addrfam);
3459 		mutex_exit(&bucket->isaf_lock);
3460 		if (assoc != NULL) {
3461 			mutex_enter(&assoc->ipsa_lock);
3462 			mutex_enter(&spare->ipsa_lock);
3463 			assoc->ipsa_state = spare->ipsa_state;
3464 			if (assoc->ipsa_state == IPSA_STATE_DEAD)
3465 				assoc->ipsa_hardexpiretime = 1;
3466 			mutex_exit(&spare->ipsa_lock);
3467 			mutex_exit(&assoc->ipsa_lock);
3468 			IPSA_REFRELE(assoc);
3469 		}
3470 		IPSA_REFRELE(spare);
3471 	}
3472 
3473 	/* Age outbound associations. */
3474 	for (i = 0; i < sp->sdb_hashsize; i++) {
3475 		bucket = &(sp->sdb_of[i]);
3476 		mutex_enter(&bucket->isaf_lock);
3477 		for (assoc = bucket->isaf_ipsa; assoc != NULL;
3478 		    assoc = spare) {
3479 			spare = assoc->ipsa_next;
3480 			if (sadb_age_assoc(bucket, pfkey_q, assoc, current,
3481 			    reap_delay, B_FALSE, &mq) != NULL) {
3482 				/*
3483 				 * sadb_age_assoc() increments the refcnt,
3484 				 * effectively doing an IPSA_REFHOLD().
3485 				 */
3486 				newbie = kmem_alloc(sizeof (*newbie),
3487 				    KM_NOSLEEP);
3488 				if (newbie == NULL) {
3489 					/*
3490 					 * Don't forget to REFRELE().
3491 					 */
3492 					IPSA_REFRELE(assoc);
3493 					continue;	/* for loop... */
3494 				}
3495 				newbie->next = haspeerlist;
3496 				newbie->ipsa = assoc;
3497 				haspeerlist = newbie;
3498 			}
3499 		}
3500 		mutex_exit(&bucket->isaf_lock);
3501 	}
3502 	if (mq != NULL) {
3503 		sadb_drain_torchq(ip_q, mq);
3504 		mq = NULL;
3505 	}
3506 	/*
3507 	 * Haspeer cases will contain both IPv4 and IPv6.  This code
3508 	 * is address independent.
3509 	 */
3510 	while (haspeerlist != NULL) {
3511 		/* "spare" contains the SA that has a peer. */
3512 		spare = haspeerlist->ipsa;
3513 		newbie = haspeerlist;
3514 		haspeerlist = newbie->next;
3515 		kmem_free(newbie, sizeof (*newbie));
3516 		/*
3517 		 * Pick peer bucket based on addrfam.
3518 		 */
3519 		bucket = INBOUND_BUCKET(sp, spare->ipsa_spi);
3520 		mutex_enter(&bucket->isaf_lock);
3521 		assoc = ipsec_getassocbyspi(bucket, spare->ipsa_spi,
3522 		    spare->ipsa_srcaddr, spare->ipsa_dstaddr,
3523 		    spare->ipsa_addrfam);
3524 		mutex_exit(&bucket->isaf_lock);
3525 		if (assoc != NULL) {
3526 			mutex_enter(&assoc->ipsa_lock);
3527 			mutex_enter(&spare->ipsa_lock);
3528 			assoc->ipsa_state = spare->ipsa_state;
3529 			if (assoc->ipsa_state == IPSA_STATE_DEAD)
3530 				assoc->ipsa_hardexpiretime = 1;
3531 			mutex_exit(&spare->ipsa_lock);
3532 			mutex_exit(&assoc->ipsa_lock);
3533 			IPSA_REFRELE(assoc);
3534 		}
3535 		IPSA_REFRELE(spare);
3536 	}
3537 	/*
3538 	 * Run a GC pass to clean out dead identities.
3539 	 */
3540 	ipsid_gc();
3541 }
3542 
3543 /*
3544  * Figure out when to reschedule the ager.
3545  */
3546 timeout_id_t
3547 sadb_retimeout(hrtime_t begin, queue_t *pfkey_q, void (*ager)(void *),
3548     uint_t *intp, uint_t intmax, short mid)
3549 {
3550 	hrtime_t end = gethrtime();
3551 	uint_t interval = *intp;
3552 
3553 	/*
3554 	 * See how long this took.  If it took too long, increase the
3555 	 * aging interval.
3556 	 */
3557 	if ((end - begin) > interval * 1000000) {
3558 		if (interval >= intmax) {
3559 			/* XXX Rate limit this?  Or recommend flush? */
3560 			(void) strlog(mid, 0, 0, SL_ERROR | SL_WARN,
3561 			    "Too many SA's to age out in %d msec.\n",
3562 			    intmax);
3563 		} else {
3564 			/* Double by shifting by one bit. */
3565 			interval <<= 1;
3566 			interval = min(interval, intmax);
3567 		}
3568 	} else if ((end - begin) <= interval * 500000 &&
3569 		interval > SADB_AGE_INTERVAL_DEFAULT) {
3570 		/*
3571 		 * If I took less than half of the interval, then I should
3572 		 * ratchet the interval back down.  Never automatically
3573 		 * shift below the default aging interval.
3574 		 *
3575 		 * NOTE:This even overrides manual setting of the age
3576 		 *	interval using NDD.
3577 		 */
3578 		/* Halve by shifting one bit. */
3579 		interval >>= 1;
3580 		interval = max(interval, SADB_AGE_INTERVAL_DEFAULT);
3581 	}
3582 	*intp = interval;
3583 	return (qtimeout(pfkey_q, ager, NULL, interval * drv_usectohz(1000)));
3584 }
3585 
3586 
3587 /*
3588  * Update the lifetime values of an SA.	 This is the path an SADB_UPDATE
3589  * message takes when updating a MATURE or DYING SA.
3590  */
3591 static void
3592 sadb_update_lifetimes(ipsa_t *assoc, sadb_lifetime_t *hard,
3593     sadb_lifetime_t *soft)
3594 {
3595 	mutex_enter(&assoc->ipsa_lock);
3596 
3597 	assoc->ipsa_state = IPSA_STATE_MATURE;
3598 
3599 	/*
3600 	 * XXX RFC 2367 mentions how an SADB_EXT_LIFETIME_CURRENT can be
3601 	 * passed in during an update message.	We currently don't handle
3602 	 * these.
3603 	 */
3604 
3605 	if (hard != NULL) {
3606 		if (hard->sadb_lifetime_bytes != 0)
3607 			assoc->ipsa_hardbyteslt = hard->sadb_lifetime_bytes;
3608 		if (hard->sadb_lifetime_usetime != 0)
3609 			assoc->ipsa_harduselt = hard->sadb_lifetime_usetime;
3610 		if (hard->sadb_lifetime_addtime != 0)
3611 			assoc->ipsa_hardaddlt = hard->sadb_lifetime_addtime;
3612 		if (assoc->ipsa_hardaddlt != 0) {
3613 			assoc->ipsa_hardexpiretime =
3614 			    assoc->ipsa_addtime + assoc->ipsa_hardaddlt;
3615 		}
3616 		if (assoc->ipsa_harduselt != 0) {
3617 			if (assoc->ipsa_hardexpiretime != 0) {
3618 				assoc->ipsa_hardexpiretime =
3619 				    min(assoc->ipsa_hardexpiretime,
3620 					assoc->ipsa_usetime +
3621 					assoc->ipsa_harduselt);
3622 			} else {
3623 				assoc->ipsa_hardexpiretime =
3624 				    assoc->ipsa_usetime + assoc->ipsa_harduselt;
3625 			}
3626 		}
3627 
3628 		if (hard->sadb_lifetime_allocations != 0)
3629 			assoc->ipsa_hardalloc = hard->sadb_lifetime_allocations;
3630 	}
3631 
3632 	if (soft != NULL) {
3633 		if (soft->sadb_lifetime_bytes != 0)
3634 			assoc->ipsa_softbyteslt = soft->sadb_lifetime_bytes;
3635 		if (soft->sadb_lifetime_usetime != 0)
3636 			assoc->ipsa_softuselt = soft->sadb_lifetime_usetime;
3637 		if (soft->sadb_lifetime_addtime != 0)
3638 			assoc->ipsa_softaddlt = soft->sadb_lifetime_addtime;
3639 		if (assoc->ipsa_softaddlt != 0) {
3640 			assoc->ipsa_softexpiretime =
3641 			    assoc->ipsa_addtime + assoc->ipsa_softaddlt;
3642 		}
3643 		if (assoc->ipsa_softuselt != 0) {
3644 			if (assoc->ipsa_softexpiretime != 0) {
3645 				assoc->ipsa_softexpiretime =
3646 				    min(assoc->ipsa_softexpiretime,
3647 					assoc->ipsa_usetime +
3648 					assoc->ipsa_softuselt);
3649 			} else {
3650 				assoc->ipsa_softexpiretime =
3651 				    assoc->ipsa_usetime + assoc->ipsa_softuselt;
3652 			}
3653 		}
3654 
3655 		if (soft->sadb_lifetime_allocations != 0)
3656 			assoc->ipsa_softalloc = soft->sadb_lifetime_allocations;
3657 	}
3658 
3659 	mutex_exit(&assoc->ipsa_lock);
3660 }
3661 
3662 /*
3663  * Common code to update an SA.
3664  */
3665 
3666 int
3667 sadb_update_sa(mblk_t *mp, keysock_in_t *ksi,
3668     sadb_t *sp, int *diagnostic, queue_t *pfkey_q,
3669     int (*add_sa_func)(mblk_t *, keysock_in_t *, int *))
3670 {
3671 	sadb_sa_t *assoc = (sadb_sa_t *)ksi->ks_in_extv[SADB_EXT_SA];
3672 	sadb_address_t *srcext =
3673 	    (sadb_address_t *)ksi->ks_in_extv[SADB_EXT_ADDRESS_SRC];
3674 	sadb_address_t *dstext =
3675 	    (sadb_address_t *)ksi->ks_in_extv[SADB_EXT_ADDRESS_DST];
3676 	sadb_x_kmc_t *kmcext =
3677 	    (sadb_x_kmc_t *)ksi->ks_in_extv[SADB_X_EXT_KM_COOKIE];
3678 	sadb_key_t *akey = (sadb_key_t *)ksi->ks_in_extv[SADB_EXT_KEY_AUTH];
3679 	sadb_key_t *ekey = (sadb_key_t *)ksi->ks_in_extv[SADB_EXT_KEY_ENCRYPT];
3680 	struct sockaddr_in *src, *dst;
3681 	struct sockaddr_in6 *src6, *dst6;
3682 	sadb_lifetime_t *soft =
3683 	    (sadb_lifetime_t *)ksi->ks_in_extv[SADB_EXT_LIFETIME_SOFT];
3684 	sadb_lifetime_t *hard =
3685 	    (sadb_lifetime_t *)ksi->ks_in_extv[SADB_EXT_LIFETIME_HARD];
3686 	isaf_t *inbound, *outbound;
3687 	ipsa_t *outbound_target = NULL, *inbound_target = NULL;
3688 	int error = 0;
3689 	uint32_t *srcaddr, *dstaddr;
3690 	sa_family_t af;
3691 	uint32_t kmp = 0, kmc = 0;
3692 
3693 	/* I need certain extensions present for either UPDATE message. */
3694 	if (srcext == NULL) {
3695 		*diagnostic = SADB_X_DIAGNOSTIC_MISSING_SRC;
3696 		return (EINVAL);
3697 	}
3698 	if (dstext == NULL) {
3699 		*diagnostic = SADB_X_DIAGNOSTIC_MISSING_DST;
3700 		return (EINVAL);
3701 	}
3702 	if (assoc == NULL) {
3703 		*diagnostic = SADB_X_DIAGNOSTIC_MISSING_SA;
3704 		return (EINVAL);
3705 	}
3706 
3707 	if (kmcext != NULL) {
3708 		kmp = kmcext->sadb_x_kmc_proto;
3709 		kmc = kmcext->sadb_x_kmc_cookie;
3710 	}
3711 
3712 	dst = (struct sockaddr_in *)(dstext + 1);
3713 	src = (struct sockaddr_in *)(srcext + 1);
3714 	af = dst->sin_family;
3715 	if (af == AF_INET6) {
3716 		dst6 = (struct sockaddr_in6 *)dst;
3717 		src6 = (struct sockaddr_in6 *)src;
3718 
3719 		srcaddr = (uint32_t *)&src6->sin6_addr;
3720 		dstaddr = (uint32_t *)&dst6->sin6_addr;
3721 		outbound = OUTBOUND_BUCKET_V6(sp, *(uint32_t *)dstaddr);
3722 #if 0
3723 		/* Not used for now... */
3724 		if (proxyext != NULL)
3725 			proxy6 = (struct sockaddr_in6 *)(proxyext + 1);
3726 #endif
3727 	} else {
3728 		srcaddr = (uint32_t *)&src->sin_addr;
3729 		dstaddr = (uint32_t *)&dst->sin_addr;
3730 		outbound = OUTBOUND_BUCKET_V4(sp, *(uint32_t *)dstaddr);
3731 	}
3732 	inbound = INBOUND_BUCKET(sp, assoc->sadb_sa_spi);
3733 
3734 	/* Lock down both buckets. */
3735 	mutex_enter(&outbound->isaf_lock);
3736 	mutex_enter(&inbound->isaf_lock);
3737 
3738 	/* Try outbound first. */
3739 	outbound_target = ipsec_getassocbyspi(outbound, assoc->sadb_sa_spi,
3740 	    srcaddr, dstaddr, af);
3741 	inbound_target = ipsec_getassocbyspi(inbound, assoc->sadb_sa_spi,
3742 	    srcaddr, dstaddr, af);
3743 
3744 	mutex_exit(&inbound->isaf_lock);
3745 	mutex_exit(&outbound->isaf_lock);
3746 
3747 	if (outbound_target == NULL) {
3748 		if (inbound_target == NULL) {
3749 			return (ESRCH);
3750 		} else if (inbound_target->ipsa_state == IPSA_STATE_LARVAL) {
3751 			/*
3752 			 * REFRELE the target and let the add_sa_func()
3753 			 * deal with updating a larval SA.
3754 			 */
3755 			IPSA_REFRELE(inbound_target);
3756 			return (add_sa_func(mp, ksi, diagnostic));
3757 		}
3758 	}
3759 
3760 	/*
3761 	 * Reality checks for updates of active associations.
3762 	 * Sundry first-pass UPDATE-specific reality checks.
3763 	 * Have to do the checks here, because it's after the add_sa code.
3764 	 * XXX STATS : logging/stats here?
3765 	 */
3766 
3767 	if (assoc->sadb_sa_state != SADB_SASTATE_MATURE) {
3768 		*diagnostic = SADB_X_DIAGNOSTIC_BAD_SASTATE;
3769 		error = EINVAL;
3770 		goto bail;
3771 	}
3772 	if (assoc->sadb_sa_flags & ~(SADB_SAFLAGS_NOREPLAY |
3773 		SADB_X_SAFLAGS_NATT_LOC | SADB_X_SAFLAGS_NATT_REM)) {
3774 		*diagnostic = SADB_X_DIAGNOSTIC_BAD_SAFLAGS;
3775 		error = EINVAL;
3776 		goto bail;
3777 	}
3778 	if (ksi->ks_in_extv[SADB_EXT_LIFETIME_CURRENT] != NULL) {
3779 		error = EOPNOTSUPP;
3780 		goto bail;
3781 	}
3782 	if ((*diagnostic = sadb_hardsoftchk(hard, soft)) != 0) {
3783 		error = EINVAL;
3784 		goto bail;
3785 	}
3786 	if (src->sin_family != dst->sin_family) {
3787 		*diagnostic = SADB_X_DIAGNOSTIC_AF_MISMATCH;
3788 		error = EINVAL;
3789 		goto bail;
3790 	}
3791 	if (akey != NULL) {
3792 		*diagnostic = SADB_X_DIAGNOSTIC_AKEY_PRESENT;
3793 		error = EINVAL;
3794 		goto bail;
3795 	}
3796 	if (ekey != NULL) {
3797 		*diagnostic = SADB_X_DIAGNOSTIC_EKEY_PRESENT;
3798 		error = EINVAL;
3799 		goto bail;
3800 	}
3801 
3802 	if (outbound_target != NULL) {
3803 		if (outbound_target->ipsa_state == IPSA_STATE_DEAD) {
3804 			error = ESRCH;	/* DEAD == Not there, in this case. */
3805 			goto bail;
3806 		}
3807 		if ((kmp != 0) &&
3808 		    ((outbound_target->ipsa_kmp != 0) ||
3809 			(outbound_target->ipsa_kmp != kmp))) {
3810 			*diagnostic = SADB_X_DIAGNOSTIC_DUPLICATE_KMP;
3811 			error = EINVAL;
3812 			goto bail;
3813 		}
3814 		if ((kmc != 0) &&
3815 		    ((outbound_target->ipsa_kmc != 0) ||
3816 			(outbound_target->ipsa_kmc != kmc))) {
3817 			*diagnostic = SADB_X_DIAGNOSTIC_DUPLICATE_KMC;
3818 			error = EINVAL;
3819 			goto bail;
3820 		}
3821 	}
3822 
3823 	if (inbound_target != NULL) {
3824 		if (inbound_target->ipsa_state == IPSA_STATE_DEAD) {
3825 			error = ESRCH;	/* DEAD == Not there, in this case. */
3826 			goto bail;
3827 		}
3828 		if ((kmp != 0) &&
3829 		    ((inbound_target->ipsa_kmp != 0) ||
3830 			(inbound_target->ipsa_kmp != kmp))) {
3831 			*diagnostic = SADB_X_DIAGNOSTIC_DUPLICATE_KMP;
3832 			error = EINVAL;
3833 			goto bail;
3834 		}
3835 		if ((kmc != 0) &&
3836 		    ((inbound_target->ipsa_kmc != 0) ||
3837 			(inbound_target->ipsa_kmc != kmc))) {
3838 			*diagnostic = SADB_X_DIAGNOSTIC_DUPLICATE_KMC;
3839 			error = EINVAL;
3840 			goto bail;
3841 		}
3842 	}
3843 
3844 	if (outbound_target != NULL) {
3845 		sadb_set_unique(outbound_target, dstext->sadb_address_proto,
3846 		    src, dst);
3847 		sadb_update_lifetimes(outbound_target, hard, soft);
3848 		if (kmp != 0)
3849 			outbound_target->ipsa_kmp = kmp;
3850 		if (kmc != 0)
3851 			outbound_target->ipsa_kmc = kmc;
3852 	}
3853 
3854 	if (inbound_target != NULL) {
3855 		sadb_set_unique(inbound_target, dstext->sadb_address_proto,
3856 		    src, dst);
3857 		sadb_update_lifetimes(inbound_target, hard, soft);
3858 		if (kmp != 0)
3859 			inbound_target->ipsa_kmp = kmp;
3860 		if (kmc != 0)
3861 			inbound_target->ipsa_kmc = kmc;
3862 	}
3863 
3864 	sadb_pfkey_echo(pfkey_q, mp, (sadb_msg_t *)mp->b_cont->b_rptr,
3865 	    ksi, (outbound_target == NULL) ? inbound_target : outbound_target);
3866 
3867 bail:
3868 	/*
3869 	 * Because of the multi-line macro nature of IPSA_REFRELE, keep
3870 	 * them in { }.
3871 	 */
3872 	if (outbound_target != NULL) {
3873 		IPSA_REFRELE(outbound_target);
3874 	}
3875 	if (inbound_target != NULL) {
3876 		IPSA_REFRELE(inbound_target);
3877 	}
3878 
3879 	return (error);
3880 }
3881 
3882 /*
3883  * The following functions deal with ACQUIRE LISTS.  An ACQUIRE list is
3884  * a list of outstanding SADB_ACQUIRE messages.	 If ipsec_getassocbyconn() fails
3885  * for an outbound datagram, that datagram is queued up on an ACQUIRE record,
3886  * and an SADB_ACQUIRE message is sent up.  Presumably, a user-space key
3887  * management daemon will process the ACQUIRE, use a SADB_GETSPI to reserve
3888  * an SPI value and a larval SA, then SADB_UPDATE the larval SA, and ADD the
3889  * other direction's SA.
3890  */
3891 
3892 /*
3893  * Check the ACQUIRE lists.  If there's an existing ACQUIRE record,
3894  * grab it, lock it, and return it.  Otherwise return NULL.
3895  */
3896 static ipsacq_t *
3897 sadb_checkacquire(iacqf_t *bucket, ipsec_action_t *ap, ipsec_policy_t *pp,
3898     uint32_t *src, uint32_t *dst, uint64_t unique_id)
3899 {
3900 	ipsacq_t *walker;
3901 	sa_family_t fam;
3902 
3903 	/*
3904 	 * Scan list for duplicates.  Check for UNIQUE, src/dest, policy.
3905 	 *
3906 	 * XXX May need search for duplicates based on other things too!
3907 	 */
3908 	for (walker = bucket->iacqf_ipsacq; walker != NULL;
3909 	    walker = walker->ipsacq_next) {
3910 		mutex_enter(&walker->ipsacq_lock);
3911 		fam = walker->ipsacq_addrfam;
3912 		if (IPSA_ARE_ADDR_EQUAL(dst, walker->ipsacq_dstaddr, fam) &&
3913 		    IPSA_ARE_ADDR_EQUAL(src, walker->ipsacq_srcaddr, fam) &&
3914 		    /* XXX PROXY should check for proxy addr here */
3915 		    (ap == walker->ipsacq_act) &&
3916 		    (pp == walker->ipsacq_policy) &&
3917 		    /* XXX do deep compares of ap/pp? */
3918 		    (unique_id == walker->ipsacq_unique_id))
3919 			break;			/* everything matched */
3920 		mutex_exit(&walker->ipsacq_lock);
3921 	}
3922 
3923 	return (walker);
3924 }
3925 
3926 /*
3927  * For this mblk, insert a new acquire record.  Assume bucket contains addrs
3928  * of all of the same length.  Give up (and drop) if memory
3929  * cannot be allocated for a new one; otherwise, invoke callback to
3930  * send the acquire up..
3931  *
3932  * In cases where we need both AH and ESP, add the SA to the ESP ACQUIRE
3933  * list.  The ah_add_sa_finish() routines can look at the packet's ipsec_out_t
3934  * and handle this case specially.
3935  */
3936 void
3937 sadb_acquire(mblk_t *mp, ipsec_out_t *io, boolean_t need_ah, boolean_t need_esp)
3938 {
3939 	sadbp_t *spp;
3940 	sadb_t *sp;
3941 	ipsacq_t *newbie;
3942 	iacqf_t *bucket;
3943 	mblk_t *datamp = mp->b_cont;
3944 	mblk_t *extended;
3945 	ipha_t *ipha = (ipha_t *)datamp->b_rptr;
3946 	ip6_t *ip6h = (ip6_t *)datamp->b_rptr;
3947 	uint32_t *src, *dst;
3948 	ipsec_policy_t *pp = io->ipsec_out_policy;
3949 	ipsec_action_t *ap = io->ipsec_out_act;
3950 	sa_family_t af;
3951 	int hashoffset;
3952 	uint32_t seq;
3953 	uint64_t unique_id = 0;
3954 	ipsec_selector_t sel;
3955 
3956 	ASSERT((pp != NULL) || (ap != NULL));
3957 
3958 	ASSERT(need_ah != NULL || need_esp != NULL);
3959 	/* Assign sadb pointers */
3960 	spp = need_esp ? &esp_sadb : &ah_sadb; /* ESP for AH+ESP */
3961 	sp = io->ipsec_out_v4 ? &spp->s_v4 : &spp->s_v6;
3962 
3963 	if (ap == NULL)
3964 		ap = pp->ipsp_act;
3965 
3966 	ASSERT(ap != NULL);
3967 
3968 	if (ap->ipa_act.ipa_apply.ipp_use_unique)
3969 		unique_id = SA_FORM_UNIQUE_ID(io);
3970 
3971 	/*
3972 	 * Set up an ACQUIRE record.
3973 	 *
3974 	 * Will eventually want to pull the PROXY source address from
3975 	 * either the inner IP header, or from a future extension to the
3976 	 * IPSEC_OUT message.
3977 	 *
3978 	 * Actually, we'll also want to check for duplicates.
3979 	 *
3980 	 * Immediately, make sure the ACQUIRE sequence number doesn't slip
3981 	 * below the lowest point allowed in the kernel.  (In other words,
3982 	 * make sure the high bit on the sequence number is set.)
3983 	 */
3984 
3985 	seq = keysock_next_seq() | IACQF_LOWEST_SEQ;
3986 
3987 	sel.ips_isv4 = io->ipsec_out_v4;
3988 	sel.ips_protocol = io->ipsec_out_proto;
3989 	sel.ips_local_port = io->ipsec_out_src_port;
3990 	sel.ips_remote_port = io->ipsec_out_dst_port;
3991 	sel.ips_icmp_type = io->ipsec_out_icmp_type;
3992 	sel.ips_icmp_code = io->ipsec_out_icmp_code;
3993 	sel.ips_is_icmp_inv_acq = 0;
3994 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
3995 		src = (uint32_t *)&ipha->ipha_src;
3996 		dst = (uint32_t *)&ipha->ipha_dst;
3997 		/* No compiler dain-bramage (4438087) for IPv4 addresses. */
3998 		sel.ips_local_addr_v4 = ipha->ipha_src;
3999 		sel.ips_remote_addr_v4 = ipha->ipha_dst;
4000 		af = AF_INET;
4001 		hashoffset = OUTBOUND_HASH_V4(sp, ipha->ipha_dst);
4002 		ASSERT(io->ipsec_out_v4 == B_TRUE);
4003 	} else {
4004 		ASSERT(IPH_HDR_VERSION(ipha) == IPV6_VERSION);
4005 		src = (uint32_t *)&ip6h->ip6_src;
4006 		dst = (uint32_t *)&ip6h->ip6_dst;
4007 		sel.ips_local_addr_v6 = ip6h->ip6_src;
4008 		sel.ips_remote_addr_v6 = ip6h->ip6_dst;
4009 		af = AF_INET6;
4010 		hashoffset = OUTBOUND_HASH_V6(sp, ip6h->ip6_dst);
4011 		ASSERT(io->ipsec_out_v4 == B_FALSE);
4012 	}
4013 
4014 	/*
4015 	 * Check buckets to see if there is an existing entry.  If so,
4016 	 * grab it.  sadb_checkacquire locks newbie if found.
4017 	 */
4018 	bucket = &(sp->sdb_acq[hashoffset]);
4019 	mutex_enter(&bucket->iacqf_lock);
4020 	newbie = sadb_checkacquire(bucket, ap, pp, src, dst, unique_id);
4021 
4022 	if (newbie == NULL) {
4023 		/*
4024 		 * Otherwise, allocate a new one.
4025 		 */
4026 		newbie = kmem_zalloc(sizeof (*newbie), KM_NOSLEEP);
4027 		if (newbie == NULL) {
4028 			mutex_exit(&bucket->iacqf_lock);
4029 			ip_drop_packet(mp, B_FALSE, NULL, NULL,
4030 			    &ipdrops_sadb_acquire_nomem, &sadb_dropper);
4031 			return;
4032 		}
4033 		newbie->ipsacq_policy = pp;
4034 		if (pp != NULL) {
4035 			IPPOL_REFHOLD(pp);
4036 		}
4037 		IPACT_REFHOLD(ap);
4038 		newbie->ipsacq_act = ap;
4039 		newbie->ipsacq_linklock = &bucket->iacqf_lock;
4040 		newbie->ipsacq_next = bucket->iacqf_ipsacq;
4041 		newbie->ipsacq_ptpn = &bucket->iacqf_ipsacq;
4042 		if (newbie->ipsacq_next != NULL)
4043 			newbie->ipsacq_next->ipsacq_ptpn = &newbie->ipsacq_next;
4044 		bucket->iacqf_ipsacq = newbie;
4045 		mutex_init(&newbie->ipsacq_lock, NULL, MUTEX_DEFAULT, NULL);
4046 		mutex_enter(&newbie->ipsacq_lock);
4047 	}
4048 
4049 	mutex_exit(&bucket->iacqf_lock);
4050 
4051 	/*
4052 	 * This assert looks silly for now, but we may need to enter newbie's
4053 	 * mutex during a search.
4054 	 */
4055 	ASSERT(MUTEX_HELD(&newbie->ipsacq_lock));
4056 
4057 	mp->b_next = NULL;
4058 	/* Queue up packet.  Use b_next. */
4059 	if (newbie->ipsacq_numpackets == 0) {
4060 		/* First one. */
4061 		newbie->ipsacq_mp = mp;
4062 		newbie->ipsacq_numpackets = 1;
4063 		(void) drv_getparm(TIME, &newbie->ipsacq_expire);
4064 		/*
4065 		 * Extended ACQUIRE with both AH+ESP will use ESP's timeout
4066 		 * value.
4067 		 */
4068 		newbie->ipsacq_expire += *spp->s_acquire_timeout;
4069 		newbie->ipsacq_seq = seq;
4070 		newbie->ipsacq_addrfam = af;
4071 
4072 		newbie->ipsacq_srcport = io->ipsec_out_src_port;
4073 		newbie->ipsacq_dstport = io->ipsec_out_dst_port;
4074 		newbie->ipsacq_icmp_type = io->ipsec_out_icmp_type;
4075 		newbie->ipsacq_icmp_code = io->ipsec_out_icmp_code;
4076 		newbie->ipsacq_proto = io->ipsec_out_proto;
4077 		newbie->ipsacq_unique_id = unique_id;
4078 	} else {
4079 		/* Scan to the end of the list & insert. */
4080 		mblk_t *lastone = newbie->ipsacq_mp;
4081 
4082 		while (lastone->b_next != NULL)
4083 			lastone = lastone->b_next;
4084 		lastone->b_next = mp;
4085 		if (newbie->ipsacq_numpackets++ == ipsacq_maxpackets) {
4086 			newbie->ipsacq_numpackets = ipsacq_maxpackets;
4087 			lastone = newbie->ipsacq_mp;
4088 			newbie->ipsacq_mp = lastone->b_next;
4089 			lastone->b_next = NULL;
4090 			ip_drop_packet(lastone, B_FALSE, NULL, NULL,
4091 			    &ipdrops_sadb_acquire_toofull, &sadb_dropper);
4092 		} else {
4093 			IP_ACQUIRE_STAT(qhiwater, newbie->ipsacq_numpackets);
4094 		}
4095 	}
4096 
4097 	/*
4098 	 * Reset addresses.  Set them to the most recently added mblk chain,
4099 	 * so that the address pointers in the acquire record will point
4100 	 * at an mblk still attached to the acquire list.
4101 	 */
4102 
4103 	newbie->ipsacq_srcaddr = src;
4104 	newbie->ipsacq_dstaddr = dst;
4105 
4106 	/*
4107 	 * If the acquire record has more than one queued packet, we've
4108 	 * already sent an ACQUIRE, and don't need to repeat ourself.
4109 	 */
4110 	if (newbie->ipsacq_seq != seq || newbie->ipsacq_numpackets > 1) {
4111 		/* I have an acquire outstanding already! */
4112 		mutex_exit(&newbie->ipsacq_lock);
4113 		return;
4114 	}
4115 
4116 	if (keysock_extended_reg()) {
4117 		/*
4118 		 * Construct an extended ACQUIRE.  There are logging
4119 		 * opportunities here in failure cases.
4120 		 */
4121 
4122 		extended = sadb_keysock_out(0);
4123 		if (extended != NULL) {
4124 			extended->b_cont = sadb_extended_acquire(&sel, pp, ap,
4125 			    seq, 0);
4126 			if (extended->b_cont == NULL) {
4127 				freeb(extended);
4128 				extended = NULL;
4129 			}
4130 		}
4131 	} else
4132 		extended = NULL;
4133 
4134 	/*
4135 	 * Send an ACQUIRE message (and possible an extended ACQUIRE) based on
4136 	 * this new record.  The send-acquire callback assumes that acqrec is
4137 	 * already locked.
4138 	 */
4139 	(*spp->s_acqfn)(newbie, extended);
4140 }
4141 
4142 /*
4143  * Unlink and free an acquire record.
4144  */
4145 void
4146 sadb_destroy_acquire(ipsacq_t *acqrec)
4147 {
4148 	mblk_t *mp;
4149 
4150 	ASSERT(MUTEX_HELD(acqrec->ipsacq_linklock));
4151 
4152 	if (acqrec->ipsacq_policy != NULL) {
4153 		IPPOL_REFRELE(acqrec->ipsacq_policy);
4154 	}
4155 	if (acqrec->ipsacq_act != NULL) {
4156 		IPACT_REFRELE(acqrec->ipsacq_act);
4157 	}
4158 
4159 	/* Unlink */
4160 	*(acqrec->ipsacq_ptpn) = acqrec->ipsacq_next;
4161 	if (acqrec->ipsacq_next != NULL)
4162 		acqrec->ipsacq_next->ipsacq_ptpn = acqrec->ipsacq_ptpn;
4163 
4164 	/*
4165 	 * Free hanging mp's.
4166 	 *
4167 	 * XXX Instead of freemsg(), perhaps use IPSEC_REQ_FAILED.
4168 	 */
4169 
4170 	mutex_enter(&acqrec->ipsacq_lock);
4171 	while (acqrec->ipsacq_mp != NULL) {
4172 		mp = acqrec->ipsacq_mp;
4173 		acqrec->ipsacq_mp = mp->b_next;
4174 		mp->b_next = NULL;
4175 		ip_drop_packet(mp, B_FALSE, NULL, NULL,
4176 		    &ipdrops_sadb_acquire_timeout, &sadb_dropper);
4177 	}
4178 	mutex_exit(&acqrec->ipsacq_lock);
4179 
4180 	/* Free */
4181 	mutex_destroy(&acqrec->ipsacq_lock);
4182 	kmem_free(acqrec, sizeof (*acqrec));
4183 }
4184 
4185 /*
4186  * Destroy an acquire list fanout.
4187  */
4188 static void
4189 sadb_destroy_acqlist(iacqf_t **listp, uint_t numentries, boolean_t forever)
4190 {
4191 	int i;
4192 	iacqf_t *list = *listp;
4193 
4194 	if (list == NULL)
4195 		return;
4196 
4197 	for (i = 0; i < numentries; i++) {
4198 		mutex_enter(&(list[i].iacqf_lock));
4199 		while (list[i].iacqf_ipsacq != NULL)
4200 			sadb_destroy_acquire(list[i].iacqf_ipsacq);
4201 		mutex_exit(&(list[i].iacqf_lock));
4202 		if (forever)
4203 			mutex_destroy(&(list[i].iacqf_lock));
4204 	}
4205 
4206 	if (forever) {
4207 		*listp = NULL;
4208 		kmem_free(list, numentries * sizeof (*list));
4209 	}
4210 }
4211 
4212 static uint8_t *
4213 sadb_new_algdesc(uint8_t *start, uint8_t *limit,
4214     sadb_x_ecomb_t *ecomb, uint8_t satype, uint8_t algtype,
4215     uint8_t alg, uint16_t minbits, uint16_t maxbits)
4216 {
4217 	uint8_t *cur = start;
4218 
4219 	sadb_x_algdesc_t *algdesc = (sadb_x_algdesc_t *)cur;
4220 	cur += sizeof (*algdesc);
4221 	if (cur >= limit)
4222 		return (NULL);
4223 
4224 	ecomb->sadb_x_ecomb_numalgs++;
4225 
4226 	algdesc->sadb_x_algdesc_satype = satype;
4227 	algdesc->sadb_x_algdesc_algtype = algtype;
4228 	algdesc->sadb_x_algdesc_alg = alg;
4229 	algdesc->sadb_x_algdesc_minbits = minbits;
4230 	algdesc->sadb_x_algdesc_maxbits = maxbits;
4231 	algdesc->sadb_x_algdesc_reserved = 0;
4232 	return (cur);
4233 }
4234 
4235 /*
4236  * Convert the given ipsec_action_t into an ecomb starting at *ecomb
4237  * which must fit before *limit
4238  *
4239  * return NULL if we ran out of room or a pointer to the end of the ecomb.
4240  */
4241 static uint8_t *
4242 sadb_action_to_ecomb(uint8_t *start, uint8_t *limit, ipsec_action_t *act)
4243 {
4244 	uint8_t *cur = start;
4245 	sadb_x_ecomb_t *ecomb = (sadb_x_ecomb_t *)cur;
4246 	ipsec_prot_t *ipp;
4247 
4248 	cur += sizeof (*ecomb);
4249 	if (cur >= limit)
4250 		return (NULL);
4251 
4252 	ASSERT(act->ipa_act.ipa_type == IPSEC_ACT_APPLY);
4253 
4254 	ipp = &act->ipa_act.ipa_apply;
4255 
4256 	ecomb->sadb_x_ecomb_numalgs = 0;
4257 	ecomb->sadb_x_ecomb_reserved = 0;
4258 	ecomb->sadb_x_ecomb_reserved2 = 0;
4259 	/*
4260 	 * No limits on allocations, since we really don't support that
4261 	 * concept currently.
4262 	 */
4263 	ecomb->sadb_x_ecomb_soft_allocations = 0;
4264 	ecomb->sadb_x_ecomb_hard_allocations = 0;
4265 
4266 	/*
4267 	 * XXX TBD: Policy or global parameters will eventually be
4268 	 * able to fill in some of these.
4269 	 */
4270 	ecomb->sadb_x_ecomb_flags = 0;
4271 	ecomb->sadb_x_ecomb_soft_bytes = 0;
4272 	ecomb->sadb_x_ecomb_hard_bytes = 0;
4273 	ecomb->sadb_x_ecomb_soft_addtime = 0;
4274 	ecomb->sadb_x_ecomb_hard_addtime = 0;
4275 	ecomb->sadb_x_ecomb_soft_usetime = 0;
4276 	ecomb->sadb_x_ecomb_hard_usetime = 0;
4277 
4278 	if (ipp->ipp_use_ah) {
4279 		cur = sadb_new_algdesc(cur, limit, ecomb,
4280 		    SADB_SATYPE_AH, SADB_X_ALGTYPE_AUTH, ipp->ipp_auth_alg,
4281 		    ipp->ipp_ah_minbits, ipp->ipp_ah_maxbits);
4282 		if (cur == NULL)
4283 			return (NULL);
4284 		ipsecah_fill_defs(ecomb);
4285 	}
4286 
4287 	if (ipp->ipp_use_esp) {
4288 		if (ipp->ipp_use_espa) {
4289 			cur = sadb_new_algdesc(cur, limit, ecomb,
4290 			    SADB_SATYPE_ESP, SADB_X_ALGTYPE_AUTH,
4291 			    ipp->ipp_esp_auth_alg,
4292 			    ipp->ipp_espa_minbits,
4293 			    ipp->ipp_espa_maxbits);
4294 			if (cur == NULL)
4295 				return (NULL);
4296 		}
4297 
4298 		cur = sadb_new_algdesc(cur, limit, ecomb,
4299 		    SADB_SATYPE_ESP, SADB_X_ALGTYPE_CRYPT,
4300 		    ipp->ipp_encr_alg,
4301 		    ipp->ipp_espe_minbits,
4302 		    ipp->ipp_espe_maxbits);
4303 		if (cur == NULL)
4304 			return (NULL);
4305 		/* Fill in lifetimes if and only if AH didn't already... */
4306 		if (!ipp->ipp_use_ah)
4307 			ipsecesp_fill_defs(ecomb);
4308 	}
4309 
4310 	return (cur);
4311 }
4312 
4313 /*
4314  * Construct an extended ACQUIRE message based on a selector and the resulting
4315  * IPsec action.
4316  *
4317  * NOTE: This is used by both inverse ACQUIRE and actual ACQUIRE
4318  * generation. As a consequence, expect this function to evolve
4319  * rapidly.
4320  */
4321 static mblk_t *
4322 sadb_extended_acquire(ipsec_selector_t *sel, ipsec_policy_t *pol,
4323     ipsec_action_t *act, uint32_t seq, uint32_t pid)
4324 {
4325 	mblk_t *mp;
4326 	sadb_msg_t *samsg;
4327 	uint8_t *start, *cur, *end;
4328 	uint32_t *saddrptr, *daddrptr;
4329 	sa_family_t af;
4330 	sadb_prop_t *eprop;
4331 	ipsec_action_t *ap, *an;
4332 	uint8_t proto;
4333 	uint16_t lport, rport;
4334 	uint32_t kmp, kmc;
4335 
4336 	/*
4337 	 * Find the action we want sooner rather than later..
4338 	 */
4339 	an = NULL;
4340 	if (pol == NULL) {
4341 		ap = act;
4342 	} else {
4343 		ap = pol->ipsp_act;
4344 
4345 		if (ap != NULL)
4346 			an = ap->ipa_next;
4347 	}
4348 
4349 	/*
4350 	 * Just take a swag for the allocation for now.	 We can always
4351 	 * alter it later.
4352 	 */
4353 #define	SADB_EXTENDED_ACQUIRE_SIZE	2048
4354 	mp = allocb(SADB_EXTENDED_ACQUIRE_SIZE, BPRI_HI);
4355 	if (mp == NULL)
4356 		return (NULL);
4357 	if (sel->ips_isv4) {
4358 		af = AF_INET;
4359 		saddrptr = (uint32_t *)(&sel->ips_local_addr_v4);
4360 		daddrptr = (uint32_t *)(&sel->ips_remote_addr_v4);
4361 	} else {
4362 		af = AF_INET6;
4363 		saddrptr = (uint32_t *)(&sel->ips_local_addr_v6);
4364 		daddrptr = (uint32_t *)(&sel->ips_remote_addr_v6);
4365 	}
4366 
4367 	start = mp->b_rptr;
4368 	end = start + SADB_EXTENDED_ACQUIRE_SIZE;
4369 
4370 	cur = start;
4371 
4372 	samsg = (sadb_msg_t *)cur;
4373 	cur += sizeof (*samsg);
4374 
4375 	samsg->sadb_msg_version = PF_KEY_V2;
4376 	samsg->sadb_msg_type = SADB_ACQUIRE;
4377 	samsg->sadb_msg_errno = 0;
4378 	samsg->sadb_msg_reserved = 0;
4379 	samsg->sadb_msg_satype = 0;
4380 	samsg->sadb_msg_seq = seq;
4381 	samsg->sadb_msg_pid = pid;
4382 
4383 	proto = sel->ips_protocol;
4384 	lport = sel->ips_local_port;
4385 	rport = sel->ips_remote_port;
4386 
4387 	/*
4388 	 * Unless our policy says "sa unique", drop port/proto
4389 	 * selectors, then add them back if policy rule includes them..
4390 	 */
4391 
4392 	if ((ap != NULL) && (!ap->ipa_want_unique)) {
4393 		proto = 0;
4394 		lport = 0;
4395 		rport = 0;
4396 		if (pol != NULL) {
4397 			ipsec_selkey_t *psel = &pol->ipsp_sel->ipsl_key;
4398 			if (psel->ipsl_valid & IPSL_PROTOCOL)
4399 				proto = psel->ipsl_proto;
4400 			if (psel->ipsl_valid & IPSL_REMOTE_PORT)
4401 				rport = psel->ipsl_rport;
4402 			if (psel->ipsl_valid & IPSL_LOCAL_PORT)
4403 				lport = psel->ipsl_lport;
4404 		}
4405 	}
4406 
4407 	cur = sadb_make_addr_ext(cur, end, SADB_EXT_ADDRESS_SRC, af,
4408 	    saddrptr, lport, proto);
4409 
4410 	if (cur == NULL) {
4411 		freeb(mp);
4412 		return (NULL);
4413 	}
4414 
4415 	cur = sadb_make_addr_ext(cur, end, SADB_EXT_ADDRESS_DST, af,
4416 	    daddrptr, rport, proto);
4417 
4418 	if (cur == NULL) {
4419 		freeb(mp);
4420 		return (NULL);
4421 	}
4422 
4423 	/*
4424 	 * This section will change a lot as policy evolves.
4425 	 * For now, it'll be relatively simple.
4426 	 */
4427 	eprop = (sadb_prop_t *)cur;
4428 	cur += sizeof (*eprop);
4429 	if (cur > end) {
4430 		/* no space left */
4431 		freeb(mp);
4432 		return (NULL);
4433 	}
4434 
4435 	eprop->sadb_prop_exttype = SADB_X_EXT_EPROP;
4436 	eprop->sadb_x_prop_ereserved = 0;
4437 	eprop->sadb_x_prop_numecombs = 0;
4438 	eprop->sadb_prop_replay = 32;	/* default */
4439 
4440 	kmc = kmp = 0;
4441 
4442 	for (; ap != NULL; ap = an) {
4443 		an = (pol != NULL) ? ap->ipa_next : NULL;
4444 
4445 		/*
4446 		 * Skip non-IPsec policies
4447 		 */
4448 		if (ap->ipa_act.ipa_type != IPSEC_ACT_APPLY)
4449 			continue;
4450 
4451 		if (ap->ipa_act.ipa_apply.ipp_km_proto)
4452 			kmp = ap->ipa_act.ipa_apply.ipp_km_proto;
4453 		if (ap->ipa_act.ipa_apply.ipp_km_cookie)
4454 			kmc = ap->ipa_act.ipa_apply.ipp_km_cookie;
4455 		if (ap->ipa_act.ipa_apply.ipp_replay_depth) {
4456 			eprop->sadb_prop_replay =
4457 			    ap->ipa_act.ipa_apply.ipp_replay_depth;
4458 		}
4459 
4460 		cur = sadb_action_to_ecomb(cur, end, ap);
4461 		if (cur == NULL) { /* no space */
4462 			freeb(mp);
4463 			return (NULL);
4464 		}
4465 		eprop->sadb_x_prop_numecombs++;
4466 	}
4467 
4468 	if (eprop->sadb_x_prop_numecombs == 0) {
4469 		/*
4470 		 * This will happen if we fail to find a policy
4471 		 * allowing for IPsec processing.
4472 		 * Construct an error message.
4473 		 */
4474 		samsg->sadb_msg_len = SADB_8TO64(sizeof (*samsg));
4475 		samsg->sadb_msg_errno = ENOENT;
4476 		samsg->sadb_x_msg_diagnostic = 0;
4477 		return (mp);
4478 	}
4479 
4480 	if ((kmp != 0) || (kmc != 0)) {
4481 		cur = sadb_make_kmc_ext(cur, end, kmp, kmc);
4482 		if (cur == NULL) {
4483 			freeb(mp);
4484 			return (NULL);
4485 		}
4486 	}
4487 
4488 	eprop->sadb_prop_len = SADB_8TO64(cur - (uint8_t *)eprop);
4489 	samsg->sadb_msg_len = SADB_8TO64(cur-start);
4490 	mp->b_wptr = cur;
4491 
4492 	return (mp);
4493 }
4494 
4495 /*
4496  * Generic setup of an ACQUIRE message.	 Caller sets satype.
4497  */
4498 uint8_t *
4499 sadb_setup_acquire(uint8_t *start, uint8_t *end, ipsacq_t *acqrec)
4500 {
4501 	sa_family_t af;
4502 	uint8_t *cur = start;
4503 	sadb_msg_t *samsg = (sadb_msg_t *)cur;
4504 	uint16_t sport_typecode;
4505 	uint16_t dport_typecode;
4506 	uint8_t check_proto;
4507 
4508 	cur += sizeof (sadb_msg_t);
4509 	if (cur > end)
4510 		return (NULL);
4511 
4512 	/* use the address length to find the address family */
4513 	af = acqrec->ipsacq_addrfam;
4514 	switch (af) {
4515 	case AF_INET:
4516 		check_proto = IPPROTO_ICMP;
4517 		break;
4518 	case AF_INET6:
4519 		check_proto = IPPROTO_ICMPV6;
4520 		break;
4521 	default:
4522 		/* This should never happen unless we have kernel bugs. */
4523 		cmn_err(CE_WARN,
4524 		    "sadb_setup_acquire:  corrupt ACQUIRE record.\n");
4525 		ASSERT(0);
4526 		return (NULL);
4527 	}
4528 
4529 	samsg->sadb_msg_version = PF_KEY_V2;
4530 	samsg->sadb_msg_type = SADB_ACQUIRE;
4531 	samsg->sadb_msg_errno = 0;
4532 	samsg->sadb_msg_pid = 0;
4533 	samsg->sadb_msg_reserved = 0;
4534 	samsg->sadb_msg_seq = acqrec->ipsacq_seq;
4535 
4536 	ASSERT(MUTEX_HELD(&acqrec->ipsacq_lock));
4537 
4538 	if (acqrec->ipsacq_proto == check_proto) {
4539 		sport_typecode = dport_typecode = 0;
4540 	} else {
4541 		sport_typecode = acqrec->ipsacq_srcport;
4542 		dport_typecode = acqrec->ipsacq_dstport;
4543 	}
4544 
4545 	cur = sadb_make_addr_ext(cur, end, SADB_EXT_ADDRESS_SRC, af,
4546 	    acqrec->ipsacq_srcaddr, sport_typecode, acqrec->ipsacq_proto);
4547 
4548 	cur = sadb_make_addr_ext(cur, end, SADB_EXT_ADDRESS_DST, af,
4549 	    acqrec->ipsacq_dstaddr, dport_typecode, acqrec->ipsacq_proto);
4550 
4551 	if (cur != NULL)
4552 		samsg->sadb_msg_len = SADB_8TO64(cur - start);
4553 
4554 	return (cur);
4555 }
4556 
4557 /*
4558  * Given an SADB_GETSPI message, find an appropriately ranged SA and
4559  * allocate an SA.  If there are message improprieties, return (ipsa_t *)-1.
4560  * If there was a memory allocation error, return NULL.	 (Assume NULL !=
4561  * (ipsa_t *)-1).
4562  *
4563  * master_spi is passed in host order.
4564  */
4565 ipsa_t *
4566 sadb_getspi(keysock_in_t *ksi, uint32_t master_spi, int *diagnostic)
4567 {
4568 	sadb_address_t *src =
4569 	    (sadb_address_t *)ksi->ks_in_extv[SADB_EXT_ADDRESS_SRC],
4570 	    *dst = (sadb_address_t *)ksi->ks_in_extv[SADB_EXT_ADDRESS_DST];
4571 	sadb_spirange_t *range =
4572 	    (sadb_spirange_t *)ksi->ks_in_extv[SADB_EXT_SPIRANGE];
4573 	struct sockaddr_in *ssa, *dsa;
4574 	struct sockaddr_in6 *ssa6, *dsa6;
4575 	uint32_t *srcaddr, *dstaddr;
4576 	sa_family_t af;
4577 	uint32_t add, min, max;
4578 
4579 	if (src == NULL) {
4580 		*diagnostic = SADB_X_DIAGNOSTIC_MISSING_SRC;
4581 		return ((ipsa_t *)-1);
4582 	}
4583 	if (dst == NULL) {
4584 		*diagnostic = SADB_X_DIAGNOSTIC_MISSING_DST;
4585 		return ((ipsa_t *)-1);
4586 	}
4587 	if (range == NULL) {
4588 		*diagnostic = SADB_X_DIAGNOSTIC_MISSING_RANGE;
4589 		return ((ipsa_t *)-1);
4590 	}
4591 
4592 	min = ntohl(range->sadb_spirange_min);
4593 	max = ntohl(range->sadb_spirange_max);
4594 	dsa = (struct sockaddr_in *)(dst + 1);
4595 	dsa6 = (struct sockaddr_in6 *)dsa;
4596 
4597 	ssa = (struct sockaddr_in *)(src + 1);
4598 	ssa6 = (struct sockaddr_in6 *)ssa;
4599 	if (dsa->sin_family != ssa->sin_family) {
4600 		*diagnostic = SADB_X_DIAGNOSTIC_AF_MISMATCH;
4601 		return ((ipsa_t *)-1);
4602 	}
4603 
4604 	srcaddr = ALL_ZEROES_PTR;
4605 	af = dsa->sin_family;
4606 	switch (af) {
4607 	case AF_INET:
4608 		if (src != NULL)
4609 			srcaddr = (uint32_t *)(&ssa->sin_addr);
4610 		dstaddr = (uint32_t *)(&dsa->sin_addr);
4611 		break;
4612 	case AF_INET6:
4613 		if (src != NULL)
4614 			srcaddr = (uint32_t *)(&ssa6->sin6_addr);
4615 		dstaddr = (uint32_t *)(&dsa6->sin6_addr);
4616 		break;
4617 	default:
4618 		*diagnostic = SADB_X_DIAGNOSTIC_BAD_DST_AF;
4619 		return ((ipsa_t *)-1);
4620 	}
4621 
4622 	if (master_spi < min || master_spi > max) {
4623 		/* Return a random value in the range. */
4624 		(void) random_get_pseudo_bytes((uint8_t *)&add, sizeof (add));
4625 		master_spi = min + (add % (max - min + 1));
4626 	}
4627 
4628 	/*
4629 	 * Since master_spi is passed in host order, we need to htonl() it
4630 	 * for the purposes of creating a new SA.
4631 	 */
4632 	return (sadb_makelarvalassoc(htonl(master_spi), srcaddr, dstaddr, af));
4633 }
4634 
4635 /*
4636  *
4637  * Locate an ACQUIRE and nuke it.  If I have an samsg that's larger than the
4638  * base header, just ignore it.	 Otherwise, lock down the whole ACQUIRE list
4639  * and scan for the sequence number in question.  I may wish to accept an
4640  * address pair with it, for easier searching.
4641  *
4642  * Caller frees the message, so we don't have to here.
4643  *
4644  * NOTE:	The ip_q parameter may be used in the future for ACQUIRE
4645  *		failures.
4646  */
4647 /* ARGSUSED */
4648 void
4649 sadb_in_acquire(sadb_msg_t *samsg, sadbp_t *sp, queue_t *ip_q)
4650 {
4651 	int i;
4652 	ipsacq_t *acqrec;
4653 	iacqf_t *bucket;
4654 
4655 	/*
4656 	 * I only accept the base header for this!
4657 	 * Though to be honest, requiring the dst address would help
4658 	 * immensely.
4659 	 *
4660 	 * XXX	There are already cases where I can get the dst address.
4661 	 */
4662 	if (samsg->sadb_msg_len > SADB_8TO64(sizeof (*samsg)))
4663 		return;
4664 
4665 	/*
4666 	 * Using the samsg->sadb_msg_seq, find the ACQUIRE record, delete it,
4667 	 * (and in the future send a message to IP with the appropriate error
4668 	 * number).
4669 	 *
4670 	 * Q: Do I want to reject if pid != 0?
4671 	 */
4672 
4673 	for (i = 0; i < sp->s_v4.sdb_hashsize; i++) {
4674 		bucket = &sp->s_v4.sdb_acq[i];
4675 		mutex_enter(&bucket->iacqf_lock);
4676 		for (acqrec = bucket->iacqf_ipsacq; acqrec != NULL;
4677 		    acqrec = acqrec->ipsacq_next) {
4678 			if (samsg->sadb_msg_seq == acqrec->ipsacq_seq)
4679 				break;	/* for acqrec... loop. */
4680 		}
4681 		if (acqrec != NULL)
4682 			break;	/* for i = 0... loop. */
4683 
4684 		mutex_exit(&bucket->iacqf_lock);
4685 	}
4686 
4687 	if (acqrec == NULL) {
4688 		for (i = 0; i < sp->s_v6.sdb_hashsize; i++) {
4689 			bucket = &sp->s_v6.sdb_acq[i];
4690 			mutex_enter(&bucket->iacqf_lock);
4691 			for (acqrec = bucket->iacqf_ipsacq; acqrec != NULL;
4692 			    acqrec = acqrec->ipsacq_next) {
4693 				if (samsg->sadb_msg_seq == acqrec->ipsacq_seq)
4694 					break;	/* for acqrec... loop. */
4695 			}
4696 			if (acqrec != NULL)
4697 				break;	/* for i = 0... loop. */
4698 
4699 			mutex_exit(&bucket->iacqf_lock);
4700 		}
4701 	}
4702 
4703 
4704 	if (acqrec == NULL)
4705 		return;
4706 
4707 	/*
4708 	 * What do I do with the errno and IP?	I may need mp's services a
4709 	 * little more.	 See sadb_destroy_acquire() for future directions
4710 	 * beyond free the mblk chain on the acquire record.
4711 	 */
4712 
4713 	ASSERT(&bucket->iacqf_lock == acqrec->ipsacq_linklock);
4714 	sadb_destroy_acquire(acqrec);
4715 	/* Have to exit mutex here, because of breaking out of for loop. */
4716 	mutex_exit(&bucket->iacqf_lock);
4717 }
4718 
4719 /*
4720  * The following functions work with the replay windows of an SA.  They assume
4721  * the ipsa->ipsa_replay_arr is an array of uint64_t, and that the bit vector
4722  * represents the highest sequence number packet received, and back
4723  * (ipsa->ipsa_replay_wsize) packets.
4724  */
4725 
4726 /*
4727  * Is the replay bit set?
4728  */
4729 static boolean_t
4730 ipsa_is_replay_set(ipsa_t *ipsa, uint32_t offset)
4731 {
4732 	uint64_t bit = (uint64_t)1 << (uint64_t)(offset & 63);
4733 
4734 	return ((bit & ipsa->ipsa_replay_arr[offset >> 6]) ? B_TRUE : B_FALSE);
4735 }
4736 
4737 /*
4738  * Shift the bits of the replay window over.
4739  */
4740 static void
4741 ipsa_shift_replay(ipsa_t *ipsa, uint32_t shift)
4742 {
4743 	int i;
4744 	int jump = ((shift - 1) >> 6) + 1;
4745 
4746 	if (shift == 0)
4747 		return;
4748 
4749 	for (i = (ipsa->ipsa_replay_wsize - 1) >> 6; i >= 0; i--) {
4750 		if (i + jump <= (ipsa->ipsa_replay_wsize - 1) >> 6) {
4751 			ipsa->ipsa_replay_arr[i + jump] |=
4752 			    ipsa->ipsa_replay_arr[i] >> (64 - (shift & 63));
4753 		}
4754 		ipsa->ipsa_replay_arr[i] <<= shift;
4755 	}
4756 }
4757 
4758 /*
4759  * Set a bit in the bit vector.
4760  */
4761 static void
4762 ipsa_set_replay(ipsa_t *ipsa, uint32_t offset)
4763 {
4764 	uint64_t bit = (uint64_t)1 << (uint64_t)(offset & 63);
4765 
4766 	ipsa->ipsa_replay_arr[offset >> 6] |= bit;
4767 }
4768 
4769 #define	SADB_MAX_REPLAY_VALUE 0xffffffff
4770 
4771 /*
4772  * Assume caller has NOT done ntohl() already on seq.  Check to see
4773  * if replay sequence number "seq" has been seen already.
4774  */
4775 boolean_t
4776 sadb_replay_check(ipsa_t *ipsa, uint32_t seq)
4777 {
4778 	boolean_t rc;
4779 	uint32_t diff;
4780 
4781 	if (ipsa->ipsa_replay_wsize == 0)
4782 		return (B_TRUE);
4783 
4784 	/*
4785 	 * NOTE:  I've already checked for 0 on the wire in sadb_replay_peek().
4786 	 */
4787 
4788 	/* Convert sequence number into host order before holding the mutex. */
4789 	seq = ntohl(seq);
4790 
4791 	mutex_enter(&ipsa->ipsa_lock);
4792 
4793 	/* Initialize inbound SA's ipsa_replay field to last one received. */
4794 	if (ipsa->ipsa_replay == 0)
4795 		ipsa->ipsa_replay = 1;
4796 
4797 	if (seq > ipsa->ipsa_replay) {
4798 		/*
4799 		 * I have received a new "highest value received".  Shift
4800 		 * the replay window over.
4801 		 */
4802 		diff = seq - ipsa->ipsa_replay;
4803 		if (diff < ipsa->ipsa_replay_wsize) {
4804 			/* In replay window, shift bits over. */
4805 			ipsa_shift_replay(ipsa, diff);
4806 		} else {
4807 			/* WAY FAR AHEAD, clear bits and start again. */
4808 			bzero(ipsa->ipsa_replay_arr,
4809 			    sizeof (ipsa->ipsa_replay_arr));
4810 		}
4811 		ipsa_set_replay(ipsa, 0);
4812 		ipsa->ipsa_replay = seq;
4813 		rc = B_TRUE;
4814 		goto done;
4815 	}
4816 	diff = ipsa->ipsa_replay - seq;
4817 	if (diff >= ipsa->ipsa_replay_wsize || ipsa_is_replay_set(ipsa, diff)) {
4818 		rc = B_FALSE;
4819 		goto done;
4820 	}
4821 	/* Set this packet as seen. */
4822 	ipsa_set_replay(ipsa, diff);
4823 
4824 	rc = B_TRUE;
4825 done:
4826 	mutex_exit(&ipsa->ipsa_lock);
4827 	return (rc);
4828 }
4829 
4830 /*
4831  * "Peek" and see if we should even bother going through the effort of
4832  * running an authentication check on the sequence number passed in.
4833  * this takes into account packets that are below the replay window,
4834  * and collisions with already replayed packets.  Return B_TRUE if it
4835  * is okay to proceed, B_FALSE if this packet should be dropped immeidately.
4836  * Assume same byte-ordering as sadb_replay_check.
4837  */
4838 boolean_t
4839 sadb_replay_peek(ipsa_t *ipsa, uint32_t seq)
4840 {
4841 	boolean_t rc = B_FALSE;
4842 	uint32_t diff;
4843 
4844 	if (ipsa->ipsa_replay_wsize == 0)
4845 		return (B_TRUE);
4846 
4847 	/*
4848 	 * 0 is 0, regardless of byte order... :)
4849 	 *
4850 	 * If I get 0 on the wire (and there is a replay window) then the
4851 	 * sender most likely wrapped.	This ipsa may need to be marked or
4852 	 * something.
4853 	 */
4854 	if (seq == 0)
4855 		return (B_FALSE);
4856 
4857 	seq = ntohl(seq);
4858 	mutex_enter(&ipsa->ipsa_lock);
4859 	if (seq < ipsa->ipsa_replay - ipsa->ipsa_replay_wsize &&
4860 	    ipsa->ipsa_replay >= ipsa->ipsa_replay_wsize)
4861 		goto done;
4862 
4863 	/*
4864 	 * If I've hit 0xffffffff, then quite honestly, I don't need to
4865 	 * bother with formalities.  I'm not accepting any more packets
4866 	 * on this SA.
4867 	 */
4868 	if (ipsa->ipsa_replay == SADB_MAX_REPLAY_VALUE) {
4869 		/*
4870 		 * Since we're already holding the lock, update the
4871 		 * expire time ala. sadb_replay_delete() and return.
4872 		 */
4873 		ipsa->ipsa_hardexpiretime = (time_t)1;
4874 		goto done;
4875 	}
4876 
4877 	if (seq <= ipsa->ipsa_replay) {
4878 		/*
4879 		 * This seq is in the replay window.  I'm not below it,
4880 		 * because I already checked for that above!
4881 		 */
4882 		diff = ipsa->ipsa_replay - seq;
4883 		if (ipsa_is_replay_set(ipsa, diff))
4884 			goto done;
4885 	}
4886 	/* Else return B_TRUE, I'm going to advance the window. */
4887 
4888 	rc = B_TRUE;
4889 done:
4890 	mutex_exit(&ipsa->ipsa_lock);
4891 	return (rc);
4892 }
4893 
4894 /*
4895  * Delete a single SA.
4896  *
4897  * For now, use the quick-and-dirty trick of making the association's
4898  * hard-expire lifetime (time_t)1, ensuring deletion by the *_ager().
4899  */
4900 void
4901 sadb_replay_delete(ipsa_t *assoc)
4902 {
4903 	mutex_enter(&assoc->ipsa_lock);
4904 	assoc->ipsa_hardexpiretime = (time_t)1;
4905 	mutex_exit(&assoc->ipsa_lock);
4906 }
4907 
4908 /*
4909  * Given a queue that presumably points to IP, send a T_BIND_REQ for _proto_
4910  * down.  The caller will handle the T_BIND_ACK locally.
4911  */
4912 boolean_t
4913 sadb_t_bind_req(queue_t *q, int proto)
4914 {
4915 	struct T_bind_req *tbr;
4916 	mblk_t *mp;
4917 
4918 	mp = allocb(sizeof (struct T_bind_req) + 1, BPRI_HI);
4919 	if (mp == NULL) {
4920 		/* cmn_err(CE_WARN, */
4921 		/* "sadb_t_bind_req(%d): couldn't allocate mblk\n", proto); */
4922 		return (B_FALSE);
4923 	}
4924 	mp->b_datap->db_type = M_PCPROTO;
4925 	tbr = (struct T_bind_req *)mp->b_rptr;
4926 	mp->b_wptr += sizeof (struct T_bind_req);
4927 	tbr->PRIM_type = T_BIND_REQ;
4928 	tbr->ADDR_length = 0;
4929 	tbr->ADDR_offset = 0;
4930 	tbr->CONIND_number = 0;
4931 	*mp->b_wptr = (uint8_t)proto;
4932 	mp->b_wptr++;
4933 
4934 	putnext(q, mp);
4935 	return (B_TRUE);
4936 }
4937 
4938 /*
4939  * Special front-end to ipsec_rl_strlog() dealing with SA failure.
4940  * this is designed to take only a format string with "* %x * %s *", so
4941  * that "spi" is printed first, then "addr" is converted using inet_pton().
4942  *
4943  * This is abstracted out to save the stack space for only when inet_pton()
4944  * is called.  Make sure "spi" is in network order; it usually is when this
4945  * would get called.
4946  */
4947 void
4948 ipsec_assocfailure(short mid, short sid, char level, ushort_t sl, char *fmt,
4949     uint32_t spi, void *addr, int af)
4950 {
4951 	char buf[INET6_ADDRSTRLEN];
4952 
4953 	ASSERT(af == AF_INET6 || af == AF_INET);
4954 
4955 	ipsec_rl_strlog(mid, sid, level, sl, fmt, ntohl(spi),
4956 	    inet_ntop(af, addr, buf, sizeof (buf)));
4957 }
4958 
4959 /*
4960  * Fills in a reference to the policy, if any, from the conn, in *ppp
4961  * Releases a reference to the passed conn_t.
4962  */
4963 
4964 /* ARGSUSED */
4965 static void
4966 ipsec_conn_pol(ipsec_selector_t *sel, conn_t *connp, ipsec_policy_t **ppp,
4967     ipsec_action_t **app)
4968 {
4969 	ipsec_policy_t	*pp;
4970 	ipsec_latch_t	*ipl = connp->conn_latch;
4971 
4972 	if ((ipl != NULL) && (ipl->ipl_out_policy != NULL)) {
4973 		pp = ipl->ipl_out_policy;
4974 		IPPOL_REFHOLD(pp);
4975 	} else {
4976 		pp = ipsec_find_policy(IPSEC_TYPE_OUTBOUND, connp, NULL, sel);
4977 	}
4978 	*ppp = pp;
4979 	CONN_DEC_REF(connp);
4980 }
4981 
4982 /*
4983  * The following functions scan through active conn_t structures
4984  * and return a reference to the best-matching policy it can find.
4985  * Caller must release the reference.
4986  */
4987 static void
4988 ipsec_udp_pol(ipsec_selector_t *sel, ipsec_policy_t **ppp, ipsec_action_t **app)
4989 {
4990 	connf_t *connfp;
4991 	conn_t *connp = NULL;
4992 	ipsec_selector_t portonly;
4993 
4994 	bzero((void*)&portonly, sizeof (portonly));
4995 
4996 	if (sel->ips_local_port == 0)
4997 		return;
4998 
4999 	connfp = &ipcl_udp_fanout[IPCL_UDP_HASH(sel->ips_local_port)];
5000 	mutex_enter(&connfp->connf_lock);
5001 
5002 	if (sel->ips_isv4) {
5003 		connp = connfp->connf_head;
5004 		while (connp != NULL) {
5005 			if (IPCL_UDP_MATCH(connp, sel->ips_local_port,
5006 			    sel->ips_local_addr_v4, sel->ips_remote_port,
5007 			    sel->ips_remote_addr_v4))
5008 				break;
5009 			connp = connp->conn_next;
5010 		}
5011 
5012 		if (connp == NULL) {
5013 			/* Try port-only match in IPv6. */
5014 			portonly.ips_local_port = sel->ips_local_port;
5015 			sel = &portonly;
5016 		}
5017 	}
5018 
5019 	if (connp == NULL) {
5020 		connp = connfp->connf_head;
5021 		while (connp != NULL) {
5022 			if (IPCL_UDP_MATCH_V6(connp, sel->ips_local_port,
5023 			    sel->ips_local_addr_v6, sel->ips_remote_port,
5024 			    sel->ips_remote_addr_v6))
5025 				break;
5026 			connp = connp->conn_next;
5027 		}
5028 
5029 		if (connp == NULL) {
5030 			mutex_exit(&connfp->connf_lock);
5031 			return;
5032 		}
5033 	}
5034 
5035 	CONN_INC_REF(connp);
5036 	mutex_exit(&connfp->connf_lock);
5037 
5038 	ipsec_conn_pol(sel, connp, ppp, app);
5039 }
5040 
5041 static conn_t *
5042 ipsec_find_listen_conn(uint16_t *pptr, ipsec_selector_t *sel)
5043 {
5044 	connf_t *connfp;
5045 	conn_t *connp = NULL;
5046 	const in6_addr_t *v6addrmatch = &sel->ips_local_addr_v6;
5047 
5048 	if (sel->ips_local_port == 0)
5049 		return (NULL);
5050 
5051 	connfp = &ipcl_bind_fanout[IPCL_BIND_HASH(sel->ips_local_port)];
5052 	mutex_enter(&connfp->connf_lock);
5053 
5054 	if (sel->ips_isv4) {
5055 		connp = connfp->connf_head;
5056 		while (connp != NULL) {
5057 			if (IPCL_BIND_MATCH(connp, IPPROTO_TCP,
5058 			    sel->ips_local_addr_v4, pptr[1]))
5059 				break;
5060 			connp = connp->conn_next;
5061 		}
5062 
5063 		if (connp == NULL) {
5064 			/* Match to all-zeroes. */
5065 			v6addrmatch = &ipv6_all_zeros;
5066 		}
5067 	}
5068 
5069 	if (connp == NULL) {
5070 		connp = connfp->connf_head;
5071 		while (connp != NULL) {
5072 			if (IPCL_BIND_MATCH_V6(connp, IPPROTO_TCP,
5073 			    *v6addrmatch, pptr[1]))
5074 				break;
5075 			connp = connp->conn_next;
5076 		}
5077 
5078 		if (connp == NULL) {
5079 			mutex_exit(&connfp->connf_lock);
5080 			return (NULL);
5081 		}
5082 	}
5083 
5084 	CONN_INC_REF(connp);
5085 	mutex_exit(&connfp->connf_lock);
5086 	return (connp);
5087 }
5088 
5089 static void
5090 ipsec_tcp_pol(ipsec_selector_t *sel, ipsec_policy_t **ppp, ipsec_action_t **app)
5091 {
5092 	connf_t 	*connfp;
5093 	conn_t		*connp;
5094 	uint32_t	ports;
5095 	uint16_t	*pptr = (uint16_t *)&ports;
5096 
5097 	/*
5098 	 * Find TCP state in the following order:
5099 	 * 1.) Connected conns.
5100 	 * 2.) Listeners.
5101 	 *
5102 	 * Even though #2 will be the common case for inbound traffic, only
5103 	 * following this order insures correctness.
5104 	 */
5105 
5106 	if (sel->ips_local_port == 0)
5107 		return;
5108 
5109 	/*
5110 	 * 0 should be fport, 1 should be lport.  SRC is the local one here.
5111 	 * See ipsec_construct_inverse_acquire() for details.
5112 	 */
5113 	pptr[0] = sel->ips_remote_port;
5114 	pptr[1] = sel->ips_local_port;
5115 
5116 	connfp = &ipcl_conn_fanout[IPCL_CONN_HASH(sel->ips_remote_addr_v4,
5117 	    ports)];
5118 	mutex_enter(&connfp->connf_lock);
5119 	connp = connfp->connf_head;
5120 
5121 	if (sel->ips_isv4) {
5122 		while (connp != NULL) {
5123 			if (IPCL_CONN_MATCH(connp, IPPROTO_TCP,
5124 			    sel->ips_remote_addr_v4, sel->ips_local_addr_v4,
5125 			    ports))
5126 				break;
5127 			connp = connp->conn_next;
5128 		}
5129 	} else {
5130 		while (connp != NULL) {
5131 			if (IPCL_CONN_MATCH_V6(connp, IPPROTO_TCP,
5132 			    sel->ips_remote_addr_v6, sel->ips_local_addr_v6,
5133 			    ports))
5134 				break;
5135 			connp = connp->conn_next;
5136 		}
5137 	}
5138 
5139 	if (connp != NULL) {
5140 		CONN_INC_REF(connp);
5141 		mutex_exit(&connfp->connf_lock);
5142 	} else {
5143 		mutex_exit(&connfp->connf_lock);
5144 
5145 		/* Try the listen hash. */
5146 		if ((connp = ipsec_find_listen_conn(pptr, sel)) == NULL)
5147 			return;
5148 	}
5149 
5150 	ipsec_conn_pol(sel, connp, ppp, app);
5151 }
5152 
5153 static void
5154 ipsec_sctp_pol(ipsec_selector_t *sel, ipsec_policy_t **ppp,
5155     ipsec_action_t **app)
5156 {
5157 	conn_t		*connp;
5158 	uint32_t	ports;
5159 	uint16_t	*pptr = (uint16_t *)&ports;
5160 
5161 	/*
5162 	 * Find SCP state in the following order:
5163 	 * 1.) Connected conns.
5164 	 * 2.) Listeners.
5165 	 *
5166 	 * Even though #2 will be the common case for inbound traffic, only
5167 	 * following this order insures correctness.
5168 	 */
5169 
5170 	if (sel->ips_local_port == 0)
5171 		return;
5172 
5173 	/*
5174 	 * 0 should be fport, 1 should be lport.  SRC is the local one here.
5175 	 * See ipsec_construct_inverse_acquire() for details.
5176 	 */
5177 	pptr[0] = sel->ips_remote_port;
5178 	pptr[1] = sel->ips_local_port;
5179 
5180 	if (sel->ips_isv4) {
5181 		in6_addr_t	src, dst;
5182 
5183 		IN6_IPADDR_TO_V4MAPPED(sel->ips_remote_addr_v4, &dst);
5184 		IN6_IPADDR_TO_V4MAPPED(sel->ips_local_addr_v4, &src);
5185 		connp = sctp_find_conn(&dst, &src, ports, 0, ALL_ZONES);
5186 	} else {
5187 		connp = sctp_find_conn(&sel->ips_remote_addr_v6,
5188 		    &sel->ips_local_addr_v6, ports, 0, ALL_ZONES);
5189 	}
5190 	if (connp == NULL)
5191 		return;
5192 	ipsec_conn_pol(sel, connp, ppp, app);
5193 }
5194 
5195 static void
5196 ipsec_oth_pol(ipsec_selector_t *sel,
5197     ipsec_policy_t **ppp, ipsec_action_t **app)
5198 {
5199 	boolean_t	isv4 = sel->ips_isv4;
5200 	connf_t		*connfp;
5201 	conn_t		*connp;
5202 
5203 	if (isv4) {
5204 		connfp = &ipcl_proto_fanout[sel->ips_protocol];
5205 	} else {
5206 		connfp = &ipcl_proto_fanout_v6[sel->ips_protocol];
5207 	}
5208 
5209 	mutex_enter(&connfp->connf_lock);
5210 	for (connp = connfp->connf_head; connp != NULL;
5211 	    connp = connp->conn_next) {
5212 		if (!((isv4 && !((connp->conn_src == 0 ||
5213 		    connp->conn_src == sel->ips_local_addr_v4) &&
5214 		    (connp->conn_rem == 0 ||
5215 		    connp->conn_rem == sel->ips_remote_addr_v4))) ||
5216 		    (!isv4 && !((IN6_IS_ADDR_UNSPECIFIED(&connp->conn_srcv6) ||
5217 		    IN6_ARE_ADDR_EQUAL(&connp->conn_srcv6,
5218 		    &sel->ips_local_addr_v6)) &&
5219 		    (IN6_IS_ADDR_UNSPECIFIED(&connp->conn_remv6) ||
5220 		    IN6_ARE_ADDR_EQUAL(&connp->conn_remv6,
5221 			&sel->ips_remote_addr_v6)))))) {
5222 			break;
5223 		}
5224 	}
5225 	if (connp == NULL) {
5226 		mutex_exit(&connfp->connf_lock);
5227 		return;
5228 	}
5229 
5230 	CONN_INC_REF(connp);
5231 	mutex_exit(&connfp->connf_lock);
5232 
5233 	ipsec_conn_pol(sel, connp, ppp, app);
5234 }
5235 
5236 /*
5237  * Construct an inverse ACQUIRE reply based on:
5238  *
5239  * 1.) Current global policy.
5240  * 2.) An conn_t match depending on what all was passed in the extv[].
5241  * ...
5242  * N.) Other stuff TBD (e.g. identities)
5243  *
5244  * If there is an error, set sadb_msg_errno and sadb_x_msg_diagnostic
5245  * in this function so the caller can extract them where appropriately.
5246  *
5247  * The SRC address is the local one - just like an outbound ACQUIRE message.
5248  */
5249 mblk_t *
5250 ipsec_construct_inverse_acquire(sadb_msg_t *samsg, sadb_ext_t *extv[])
5251 {
5252 	int err;
5253 	int diagnostic;
5254 	sadb_address_t *srcext = (sadb_address_t *)extv[SADB_EXT_ADDRESS_SRC],
5255 	    *dstext = (sadb_address_t *)extv[SADB_EXT_ADDRESS_DST];
5256 	struct sockaddr_in *src, *dst;
5257 	struct sockaddr_in6 *src6, *dst6;
5258 	ipsec_policy_t *pp;
5259 	ipsec_action_t *ap;
5260 	ipsec_selector_t sel;
5261 	mblk_t *retmp;
5262 
5263 	bzero(&sel, sizeof (sel));
5264 	sel.ips_protocol = srcext->sadb_address_proto;
5265 	dst = (struct sockaddr_in *)(dstext + 1);
5266 	if (dst->sin_family == AF_INET6) {
5267 		dst6 = (struct sockaddr_in6 *)dst;
5268 		src6 = (struct sockaddr_in6 *)(srcext + 1);
5269 		if (src6->sin6_family != AF_INET6) {
5270 			diagnostic = SADB_X_DIAGNOSTIC_AF_MISMATCH;
5271 			err = EINVAL;
5272 			goto bail;
5273 		}
5274 		sel.ips_remote_addr_v6 = dst6->sin6_addr;
5275 		sel.ips_local_addr_v6 = src6->sin6_addr;
5276 		if (sel.ips_protocol == IPPROTO_ICMPV6) {
5277 			sel.ips_is_icmp_inv_acq = 1;
5278 		} else {
5279 			sel.ips_remote_port = dst6->sin6_port;
5280 			sel.ips_local_port = src6->sin6_port;
5281 		}
5282 		sel.ips_isv4 = B_FALSE;
5283 	} else {
5284 		src = (struct sockaddr_in *)(srcext + 1);
5285 		if (src->sin_family != AF_INET) {
5286 			diagnostic = SADB_X_DIAGNOSTIC_AF_MISMATCH;
5287 			err = EINVAL;
5288 			goto bail;
5289 		}
5290 		sel.ips_remote_addr_v4 = dst->sin_addr.s_addr;
5291 		sel.ips_local_addr_v4 = src->sin_addr.s_addr;
5292 		if (sel.ips_protocol == IPPROTO_ICMP) {
5293 			sel.ips_is_icmp_inv_acq = 1;
5294 		} else {
5295 			sel.ips_remote_port = dst->sin_port;
5296 			sel.ips_local_port = src->sin_port;
5297 		}
5298 		sel.ips_isv4 = B_TRUE;
5299 	}
5300 
5301 	/*
5302 	 * Okay, we have the addresses and other selector information.
5303 	 * Let's first find a conn...
5304 	 */
5305 	pp = NULL; ap = NULL;
5306 	switch (sel.ips_protocol) {
5307 	case IPPROTO_TCP:
5308 		ipsec_tcp_pol(&sel, &pp, &ap);
5309 		break;
5310 	case IPPROTO_UDP:
5311 		ipsec_udp_pol(&sel, &pp, &ap);
5312 		break;
5313 	case IPPROTO_SCTP:
5314 		ipsec_sctp_pol(&sel, &pp, &ap);
5315 		break;
5316 	default:
5317 		ipsec_oth_pol(&sel, &pp, &ap);
5318 		break;
5319 	}
5320 
5321 	/*
5322 	 * If we didn't find a matching conn_t, take a look in the global
5323 	 * policy.
5324 	 */
5325 	if ((pp == NULL) && (ap == NULL)) {
5326 		pp = ipsec_find_policy(IPSEC_TYPE_OUTBOUND, NULL, NULL, &sel);
5327 		if (pp == NULL) {
5328 			/* There's no global policy. */
5329 			err = ENOENT;
5330 			diagnostic = 0;
5331 			goto bail;
5332 		}
5333 	}
5334 
5335 	/*
5336 	 * Now that we have a policy entry/widget, construct an ACQUIRE
5337 	 * message based on that, fix fields where appropriate,
5338 	 * and return the message.
5339 	 */
5340 	retmp = sadb_extended_acquire(&sel, pp, ap, samsg->sadb_msg_seq,
5341 	    samsg->sadb_msg_pid);
5342 	if (pp != NULL) {
5343 		IPPOL_REFRELE(pp);
5344 	}
5345 	if (ap != NULL) {
5346 		IPACT_REFRELE(ap);
5347 	}
5348 	if (retmp != NULL) {
5349 		return (retmp);
5350 	} else {
5351 		err = ENOMEM;
5352 		diagnostic = 0;
5353 	bail:
5354 		samsg->sadb_msg_errno = (uint8_t)err;
5355 		samsg->sadb_x_msg_diagnostic = (uint16_t)diagnostic;
5356 		return (NULL);
5357 	}
5358 }
5359 
5360 /*
5361  * ipsa_lpkt is a one-element queue, only manipulated by casptr within
5362  * the next two functions.
5363  *
5364  * These functions loop calling casptr() until the swap "happens",
5365  * turning a compare-and-swap op into an atomic swap operation.
5366  */
5367 
5368 /*
5369  * sadb_set_lpkt: Atomically swap in a value to ipsa->ipsa_lpkt and
5370  * freemsg the previous value.  free clue: freemsg(NULL) is safe.
5371  */
5372 
5373 void
5374 sadb_set_lpkt(ipsa_t *ipsa, mblk_t *npkt)
5375 {
5376 	mblk_t *opkt;
5377 
5378 	membar_producer();
5379 	do
5380 		opkt = ipsa->ipsa_lpkt;
5381 	while (casptr(&ipsa->ipsa_lpkt, opkt, npkt) != opkt);
5382 
5383 	ip_drop_packet(opkt, B_TRUE, NULL, NULL, &ipdrops_sadb_inlarval_replace,
5384 	    &sadb_dropper);
5385 }
5386 
5387 /*
5388  * sadb_clear_lpkt: Atomically clear ipsa->ipsa_lpkt and return the
5389  * previous value.
5390  */
5391 
5392 mblk_t *
5393 sadb_clear_lpkt(ipsa_t *ipsa)
5394 {
5395 	mblk_t *opkt;
5396 
5397 	do
5398 		opkt = ipsa->ipsa_lpkt;
5399 	while (casptr(&ipsa->ipsa_lpkt, opkt, NULL) != opkt);
5400 
5401 	return (opkt);
5402 }
5403 
5404 /*
5405  * Walker callback used by sadb_alg_update() to free/create crypto
5406  * context template when a crypto software provider is removed or
5407  * added.
5408  */
5409 
5410 struct sadb_update_alg_state {
5411 	ipsec_algtype_t alg_type;
5412 	uint8_t alg_id;
5413 	boolean_t is_added;
5414 };
5415 
5416 static void
5417 sadb_alg_update_cb(isaf_t *head, ipsa_t *entry, void *cookie)
5418 {
5419 	struct sadb_update_alg_state *update_state =
5420 	    (struct sadb_update_alg_state *)cookie;
5421 	crypto_ctx_template_t *ctx_tmpl = NULL;
5422 
5423 	ASSERT(MUTEX_HELD(&head->isaf_lock));
5424 
5425 	if (entry->ipsa_state == IPSA_STATE_LARVAL)
5426 		return;
5427 
5428 	mutex_enter(&entry->ipsa_lock);
5429 
5430 	switch (update_state->alg_type) {
5431 	case IPSEC_ALG_AUTH:
5432 		if (entry->ipsa_auth_alg == update_state->alg_id)
5433 			ctx_tmpl = &entry->ipsa_authtmpl;
5434 		break;
5435 	case IPSEC_ALG_ENCR:
5436 		if (entry->ipsa_encr_alg == update_state->alg_id)
5437 			ctx_tmpl = &entry->ipsa_encrtmpl;
5438 		break;
5439 	default:
5440 		ctx_tmpl = NULL;
5441 	}
5442 
5443 	if (ctx_tmpl == NULL) {
5444 		mutex_exit(&entry->ipsa_lock);
5445 		return;
5446 	}
5447 
5448 	/*
5449 	 * The context template of the SA may be affected by the change
5450 	 * of crypto provider.
5451 	 */
5452 	if (update_state->is_added) {
5453 		/* create the context template if not already done */
5454 		if (*ctx_tmpl == NULL) {
5455 			(void) ipsec_create_ctx_tmpl(entry,
5456 			    update_state->alg_type);
5457 		}
5458 	} else {
5459 		/*
5460 		 * The crypto provider was removed. If the context template
5461 		 * exists but it is no longer valid, free it.
5462 		 */
5463 		if (*ctx_tmpl != NULL)
5464 			ipsec_destroy_ctx_tmpl(entry, update_state->alg_type);
5465 	}
5466 
5467 	mutex_exit(&entry->ipsa_lock);
5468 }
5469 
5470 /*
5471  * Invoked by IP when an software crypto provider has been updated.
5472  * The type and id of the corresponding algorithm is passed as argument.
5473  * is_added is B_TRUE if the provider was added, B_FALSE if it was
5474  * removed. The function updates the SADB and free/creates the
5475  * context templates associated with SAs if needed.
5476  */
5477 
5478 #define	SADB_ALG_UPDATE_WALK(sadb, table) \
5479     sadb_walker((sadb).table, (sadb).sdb_hashsize, sadb_alg_update_cb, \
5480 	&update_state)
5481 
5482 void
5483 sadb_alg_update(ipsec_algtype_t alg_type, uint8_t alg_id, boolean_t is_added)
5484 {
5485 	struct sadb_update_alg_state update_state;
5486 
5487 	update_state.alg_type = alg_type;
5488 	update_state.alg_id = alg_id;
5489 	update_state.is_added = is_added;
5490 
5491 	if (alg_type == IPSEC_ALG_AUTH) {
5492 		/* walk the AH tables only for auth. algorithm changes */
5493 		SADB_ALG_UPDATE_WALK(ah_sadb.s_v4, sdb_of);
5494 		SADB_ALG_UPDATE_WALK(ah_sadb.s_v4, sdb_if);
5495 		SADB_ALG_UPDATE_WALK(ah_sadb.s_v6, sdb_of);
5496 		SADB_ALG_UPDATE_WALK(ah_sadb.s_v6, sdb_if);
5497 	}
5498 
5499 	/* walk the ESP tables */
5500 	SADB_ALG_UPDATE_WALK(esp_sadb.s_v4, sdb_of);
5501 	SADB_ALG_UPDATE_WALK(esp_sadb.s_v4, sdb_if);
5502 	SADB_ALG_UPDATE_WALK(esp_sadb.s_v6, sdb_of);
5503 	SADB_ALG_UPDATE_WALK(esp_sadb.s_v6, sdb_if);
5504 }
5505 
5506 /*
5507  * Creates a context template for the specified SA. This function
5508  * is called when an SA is created and when a context template needs
5509  * to be created due to a change of software provider.
5510  */
5511 int
5512 ipsec_create_ctx_tmpl(ipsa_t *sa, ipsec_algtype_t alg_type)
5513 {
5514 	ipsec_alginfo_t *alg;
5515 	crypto_mechanism_t mech;
5516 	crypto_key_t *key;
5517 	crypto_ctx_template_t *sa_tmpl;
5518 	int rv;
5519 
5520 	ASSERT(MUTEX_HELD(&alg_lock));
5521 	ASSERT(MUTEX_HELD(&sa->ipsa_lock));
5522 
5523 	/* get pointers to the algorithm info, context template, and key */
5524 	switch (alg_type) {
5525 	case IPSEC_ALG_AUTH:
5526 		key = &sa->ipsa_kcfauthkey;
5527 		sa_tmpl = &sa->ipsa_authtmpl;
5528 		alg = ipsec_alglists[alg_type][sa->ipsa_auth_alg];
5529 		break;
5530 	case IPSEC_ALG_ENCR:
5531 		key = &sa->ipsa_kcfencrkey;
5532 		sa_tmpl = &sa->ipsa_encrtmpl;
5533 		alg = ipsec_alglists[alg_type][sa->ipsa_encr_alg];
5534 		break;
5535 	default:
5536 		alg = NULL;
5537 	}
5538 
5539 	if (alg == NULL || !ALG_VALID(alg))
5540 		return (EINVAL);
5541 
5542 	/* initialize the mech info structure for the framework */
5543 	ASSERT(alg->alg_mech_type != CRYPTO_MECHANISM_INVALID);
5544 	mech.cm_type = alg->alg_mech_type;
5545 	mech.cm_param = NULL;
5546 	mech.cm_param_len = 0;
5547 
5548 	/* create a new context template */
5549 	rv = crypto_create_ctx_template(&mech, key, sa_tmpl, KM_NOSLEEP);
5550 
5551 	/*
5552 	 * CRYPTO_MECH_NOT_SUPPORTED can be returned if only hardware
5553 	 * providers are available for that mechanism. In that case
5554 	 * we don't fail, and will generate the context template from
5555 	 * the framework callback when a software provider for that
5556 	 * mechanism registers.
5557 	 *
5558 	 * The context template is assigned the special value
5559 	 * IPSEC_CTX_TMPL_ALLOC if the allocation failed due to a
5560 	 * lack of memory. No attempt will be made to use
5561 	 * the context template if it is set to this value.
5562 	 */
5563 	if (rv == CRYPTO_HOST_MEMORY) {
5564 		*sa_tmpl = IPSEC_CTX_TMPL_ALLOC;
5565 	} else if (rv != CRYPTO_SUCCESS) {
5566 		*sa_tmpl = NULL;
5567 		if (rv != CRYPTO_MECH_NOT_SUPPORTED)
5568 			return (EINVAL);
5569 	}
5570 
5571 	return (0);
5572 }
5573 
5574 /*
5575  * Destroy the context template of the specified algorithm type
5576  * of the specified SA. Must be called while holding the SA lock.
5577  */
5578 void
5579 ipsec_destroy_ctx_tmpl(ipsa_t *sa, ipsec_algtype_t alg_type)
5580 {
5581 	ASSERT(MUTEX_HELD(&sa->ipsa_lock));
5582 
5583 	if (alg_type == IPSEC_ALG_AUTH) {
5584 		if (sa->ipsa_authtmpl == IPSEC_CTX_TMPL_ALLOC)
5585 			sa->ipsa_authtmpl = NULL;
5586 		else if (sa->ipsa_authtmpl != NULL) {
5587 			crypto_destroy_ctx_template(sa->ipsa_authtmpl);
5588 			sa->ipsa_authtmpl = NULL;
5589 		}
5590 	} else {
5591 		ASSERT(alg_type == IPSEC_ALG_ENCR);
5592 		if (sa->ipsa_encrtmpl == IPSEC_CTX_TMPL_ALLOC)
5593 			sa->ipsa_encrtmpl = NULL;
5594 		else if (sa->ipsa_encrtmpl != NULL) {
5595 			crypto_destroy_ctx_template(sa->ipsa_encrtmpl);
5596 			sa->ipsa_encrtmpl = NULL;
5597 		}
5598 	}
5599 }
5600 
5601 /*
5602  * Use the kernel crypto framework to check the validity of a key received
5603  * via keysock. Returns 0 if the key is OK, -1 otherwise.
5604  */
5605 int
5606 ipsec_check_key(crypto_mech_type_t mech_type, sadb_key_t *sadb_key,
5607     boolean_t is_auth, int *diag)
5608 {
5609 	crypto_mechanism_t mech;
5610 	crypto_key_t crypto_key;
5611 	int crypto_rc;
5612 
5613 	mech.cm_type = mech_type;
5614 	mech.cm_param = NULL;
5615 	mech.cm_param_len = 0;
5616 
5617 	crypto_key.ck_format = CRYPTO_KEY_RAW;
5618 	crypto_key.ck_data = sadb_key + 1;
5619 	crypto_key.ck_length = sadb_key->sadb_key_bits;
5620 
5621 	crypto_rc = crypto_key_check(&mech, &crypto_key);
5622 
5623 	switch (crypto_rc) {
5624 	case CRYPTO_SUCCESS:
5625 		return (0);
5626 	case CRYPTO_MECHANISM_INVALID:
5627 	case CRYPTO_MECH_NOT_SUPPORTED:
5628 		*diag = is_auth ? SADB_X_DIAGNOSTIC_BAD_AALG :
5629 		    SADB_X_DIAGNOSTIC_BAD_EALG;
5630 		break;
5631 	case CRYPTO_KEY_SIZE_RANGE:
5632 		*diag = is_auth ? SADB_X_DIAGNOSTIC_BAD_AKEYBITS :
5633 		    SADB_X_DIAGNOSTIC_BAD_EKEYBITS;
5634 		break;
5635 	case CRYPTO_WEAK_KEY:
5636 		*diag = is_auth ? SADB_X_DIAGNOSTIC_WEAK_AKEY :
5637 		    SADB_X_DIAGNOSTIC_WEAK_EKEY;
5638 		break;
5639 	}
5640 
5641 	return (-1);
5642 }
5643 
5644 /* ARGSUSED */
5645 static void
5646 sadb_clear_timeouts_walker(isaf_t *head, ipsa_t *ipsa, void *q)
5647 {
5648 	if (!(ipsa->ipsa_flags & IPSA_F_NATT))
5649 		return;
5650 
5651 	mutex_enter(&ipsa->ipsa_lock);
5652 	if (ipsa->ipsa_natt_q != q) {
5653 		mutex_exit(&ipsa->ipsa_lock);
5654 		return;
5655 	}
5656 
5657 	(void) quntimeout(ipsa->ipsa_natt_q, ipsa->ipsa_natt_ka_timer);
5658 
5659 	ipsa->ipsa_natt_ka_timer = 0;
5660 	ipsa->ipsa_natt_q = NULL;
5661 	mutex_exit(&ipsa->ipsa_lock);
5662 }
5663 
5664 void
5665 sadb_clear_timeouts(queue_t *q)
5666 {
5667 	sadb_t *sp = &esp_sadb.s_v4;
5668 
5669 	sadb_walker(sp->sdb_if, sp->sdb_hashsize,
5670 	    sadb_clear_timeouts_walker, q);
5671 }
5672