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