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