xref: /illumos-gate/usr/src/uts/common/inet/ip/spd.c (revision 956e8222f10bf55e45b41d8b56084f72ebc113c9)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License, Version 1.0 only
6  * (the "License").  You may not use this file except in compliance
7  * with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or http://www.opensolaris.org/os/licensing.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 /*
23  * Copyright 2005 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 /*
30  * IPsec Security Policy Database.
31  *
32  * This module maintains the SPD and provides routines used by ip and ip6
33  * to apply IPsec policy to inbound and outbound datagrams.
34  *
35  * XXX TODO LIST
36  * Inbound policy:
37  * Put policy failure logging back in here (as policy action flag bit)
38  */
39 
40 #include <sys/types.h>
41 #include <sys/stream.h>
42 #include <sys/stropts.h>
43 #include <sys/sysmacros.h>
44 #include <sys/strsubr.h>
45 #include <sys/strlog.h>
46 #include <sys/cmn_err.h>
47 #include <sys/zone.h>
48 
49 #include <sys/systm.h>
50 #include <sys/param.h>
51 #include <sys/kmem.h>
52 
53 #include <sys/crypto/api.h>
54 
55 #include <inet/common.h>
56 #include <inet/mi.h>
57 
58 #include <netinet/ip6.h>
59 #include <netinet/icmp6.h>
60 #include <netinet/udp.h>
61 
62 #include <inet/ip.h>
63 #include <inet/ip6.h>
64 
65 #include <net/pfkeyv2.h>
66 #include <net/pfpolicy.h>
67 #include <inet/ipsec_info.h>
68 #include <inet/sadb.h>
69 #include <inet/ipsec_impl.h>
70 #include <inet/ipsecah.h>
71 #include <inet/ipsecesp.h>
72 #include <inet/ipdrop.h>
73 #include <inet/ipclassifier.h>
74 
75 static void ipsec_update_present_flags();
76 static ipsec_act_t *ipsec_act_wildcard_expand(ipsec_act_t *, uint_t *);
77 static void ipsec_out_free(void *);
78 static void ipsec_in_free(void *);
79 static boolean_t ipsec_init_inbound_sel(ipsec_selector_t *, mblk_t *,
80     ipha_t *, ip6_t *);
81 static mblk_t *ipsec_attach_global_policy(mblk_t *, conn_t *,
82     ipsec_selector_t *);
83 static mblk_t *ipsec_apply_global_policy(mblk_t *, conn_t *,
84     ipsec_selector_t *);
85 static mblk_t *ipsec_check_ipsecin_policy(queue_t *, mblk_t *,
86     ipsec_policy_t *, ipha_t *, ip6_t *);
87 static void ipsec_in_release_refs(ipsec_in_t *);
88 static void ipsec_out_release_refs(ipsec_out_t *);
89 static void ipsec_action_reclaim(void *);
90 static void ipsid_init(void);
91 static void ipsid_fini(void);
92 static boolean_t ipsec_check_ipsecin_action(struct ipsec_in_s *, mblk_t *,
93     struct ipsec_action_s *, ipha_t *ipha, ip6_t *ip6h, const char **,
94     kstat_named_t **);
95 static int32_t ipsec_act_ovhd(const ipsec_act_t *act);
96 static void ipsec_unregister_prov_update(void);
97 static boolean_t ipsec_compare_action(ipsec_policy_t *, ipsec_policy_t *);
98 static uint32_t selector_hash(ipsec_selector_t *);
99 
100 /*
101  * Policy rule index generator.  We assume this won't wrap in the
102  * lifetime of a system.  If we make 2^20 policy changes per second,
103  * this will last 2^44 seconds, or roughly 500,000 years, so we don't
104  * have to worry about reusing policy index values.
105  *
106  * Protected by ipsec_conf_lock.
107  */
108 uint64_t	ipsec_next_policy_index = 1;
109 
110 /*
111  * Active & Inactive system policy roots
112  */
113 static ipsec_policy_head_t system_policy;
114 static ipsec_policy_head_t inactive_policy;
115 
116 /* Packet dropper for generic SPD drops. */
117 static ipdropper_t spd_dropper;
118 
119 /*
120  * For now, use a trivially sized hash table for actions.
121  * In the future we can add the structure canonicalization necessary
122  * to get the hash function to behave correctly..
123  */
124 #define	IPSEC_ACTION_HASH_SIZE 1
125 
126 /*
127  * Selector hash table is statically sized at module load time.
128  * we default to 251 buckets, which is the largest prime number under 255
129  */
130 
131 #define	IPSEC_SPDHASH_DEFAULT 251
132 uint32_t ipsec_spd_hashsize = 0;
133 
134 #define	IPSEC_SEL_NOHASH ((uint32_t)(~0))
135 
136 static HASH_HEAD(ipsec_action_s) ipsec_action_hash[IPSEC_ACTION_HASH_SIZE];
137 static HASH_HEAD(ipsec_sel) *ipsec_sel_hash;
138 
139 static kmem_cache_t *ipsec_action_cache;
140 static kmem_cache_t *ipsec_sel_cache;
141 static kmem_cache_t *ipsec_pol_cache;
142 static kmem_cache_t *ipsec_info_cache;
143 
144 boolean_t ipsec_inbound_v4_policy_present = B_FALSE;
145 boolean_t ipsec_outbound_v4_policy_present = B_FALSE;
146 boolean_t ipsec_inbound_v6_policy_present = B_FALSE;
147 boolean_t ipsec_outbound_v6_policy_present = B_FALSE;
148 
149 /*
150  * Because policy needs to know what algorithms are supported, keep the
151  * lists of algorithms here.
152  */
153 
154 kmutex_t alg_lock;
155 uint8_t ipsec_nalgs[IPSEC_NALGTYPES];
156 ipsec_alginfo_t *ipsec_alglists[IPSEC_NALGTYPES][IPSEC_MAX_ALGS];
157 uint8_t ipsec_sortlist[IPSEC_NALGTYPES][IPSEC_MAX_ALGS];
158 ipsec_algs_exec_mode_t ipsec_algs_exec_mode[IPSEC_NALGTYPES];
159 static crypto_notify_handle_t prov_update_handle = NULL;
160 
161 #define	ALGBITS_ROUND_DOWN(x, align)	(((x)/(align))*(align))
162 #define	ALGBITS_ROUND_UP(x, align)	ALGBITS_ROUND_DOWN((x)+(align)-1, align)
163 
164 /*
165  * Inbound traffic should have matching identities for both SA's.
166  */
167 
168 #define	SA_IDS_MATCH(sa1, sa2) 						\
169 	(((sa1) == NULL) || ((sa2) == NULL) ||				\
170 	(((sa1)->ipsa_src_cid == (sa2)->ipsa_src_cid) &&		\
171 	    (((sa1)->ipsa_dst_cid == (sa2)->ipsa_dst_cid))))
172 
173 #define	IPPOL_UNCHAIN(php, ip) 						\
174 	HASHLIST_UNCHAIN((ip), ipsp_hash);				\
175 	avl_remove(&(php)->iph_rulebyid, (ip));				\
176 	IPPOL_REFRELE(ip);
177 
178 /*
179  * Policy failure messages.
180  */
181 static char *ipsec_policy_failure_msgs[] = {
182 
183 	/* IPSEC_POLICY_NOT_NEEDED */
184 	"%s: Dropping the datagram because the incoming packet "
185 	"is %s, but the recipient expects clear; Source %s, "
186 	"Destination %s.\n",
187 
188 	/* IPSEC_POLICY_MISMATCH */
189 	"%s: Policy Failure for the incoming packet (%s); Source %s, "
190 	"Destination %s.\n",
191 
192 	/* IPSEC_POLICY_AUTH_NOT_NEEDED	*/
193 	"%s: Authentication present while not expected in the "
194 	"incoming %s packet; Source %s, Destination %s.\n",
195 
196 	/* IPSEC_POLICY_ENCR_NOT_NEEDED */
197 	"%s: Encryption present while not expected in the "
198 	"incoming %s packet; Source %s, Destination %s.\n",
199 
200 	/* IPSEC_POLICY_SE_NOT_NEEDED */
201 	"%s: Self-Encapsulation present while not expected in the "
202 	"incoming %s packet; Source %s, Destination %s.\n",
203 };
204 /*
205  * Have a counter for every possible policy message in the previous array.
206  */
207 static uint32_t ipsec_policy_failure_count[IPSEC_POLICY_MAX];
208 /* Time since last ipsec policy failure that printed a message. */
209 hrtime_t ipsec_policy_failure_last = 0;
210 
211 /*
212  * General overviews:
213  *
214  * Locking:
215  *
216  *	All of the system policy structures are protected by a single
217  *	rwlock, ipsec_conf_lock.  These structures are threaded in a
218  *	fairly complex fashion and are not expected to change on a
219  *	regular basis, so this should not cause scaling/contention
220  *	problems.  As a result, policy checks should (hopefully) be MT-hot.
221  *
222  * Allocation policy:
223  *
224  *	We use custom kmem cache types for the various
225  *	bits & pieces of the policy data structures.  All allocations
226  *	use KM_NOSLEEP instead of KM_SLEEP for policy allocation.  The
227  *	policy table is of potentially unbounded size, so we don't
228  *	want to provide a way to hog all system memory with policy
229  *	entries..
230  */
231 
232 
233 /*
234  * AVL tree comparison function.
235  * the in-kernel avl assumes unique keys for all objects.
236  * Since sometimes policy will duplicate rules, we may insert
237  * multiple rules with the same rule id, so we need a tie-breaker.
238  */
239 static int
240 ipsec_policy_cmpbyid(const void *a, const void *b)
241 {
242 	const ipsec_policy_t *ipa, *ipb;
243 	uint64_t idxa, idxb;
244 
245 	ipa = (const ipsec_policy_t *)a;
246 	ipb = (const ipsec_policy_t *)b;
247 	idxa = ipa->ipsp_index;
248 	idxb = ipb->ipsp_index;
249 
250 	if (idxa < idxb)
251 		return (-1);
252 	if (idxa > idxb)
253 		return (1);
254 	/*
255 	 * Tie-breaker #1: All installed policy rules have a non-NULL
256 	 * ipsl_sel (selector set), so an entry with a NULL ipsp_sel is not
257 	 * actually in-tree but rather a template node being used in
258 	 * an avl_find query; see ipsec_policy_delete().  This gives us
259 	 * a placeholder in the ordering just before the the first entry with
260 	 * a key >= the one we're looking for, so we can walk forward from
261 	 * that point to get the remaining entries with the same id.
262 	 */
263 	if ((ipa->ipsp_sel == NULL) && (ipb->ipsp_sel != NULL))
264 		return (-1);
265 	if ((ipb->ipsp_sel == NULL) && (ipa->ipsp_sel != NULL))
266 		return (1);
267 	/*
268 	 * At most one of the arguments to the comparison should have a
269 	 * NULL selector pointer; if not, the tree is broken.
270 	 */
271 	ASSERT(ipa->ipsp_sel != NULL);
272 	ASSERT(ipb->ipsp_sel != NULL);
273 	/*
274 	 * Tie-breaker #2: use the virtual address of the policy node
275 	 * to arbitrarily break ties.  Since we use the new tree node in
276 	 * the avl_find() in ipsec_insert_always, the new node will be
277 	 * inserted into the tree in the right place in the sequence.
278 	 */
279 	if (ipa < ipb)
280 		return (-1);
281 	if (ipa > ipb)
282 		return (1);
283 	return (0);
284 }
285 
286 static void
287 ipsec_polhead_free_table(ipsec_policy_head_t *iph)
288 {
289 	int dir, nchains;
290 
291 	nchains = ipsec_spd_hashsize;
292 
293 	for (dir = 0; dir < IPSEC_NTYPES; dir++) {
294 		ipsec_policy_root_t *ipr = &iph->iph_root[dir];
295 
296 		if (ipr->ipr_hash == NULL)
297 			continue;
298 
299 		kmem_free(ipr->ipr_hash, nchains *
300 		    sizeof (ipsec_policy_hash_t));
301 	}
302 }
303 
304 static void
305 ipsec_polhead_destroy(ipsec_policy_head_t *iph)
306 {
307 	int dir;
308 
309 	avl_destroy(&iph->iph_rulebyid);
310 	rw_destroy(&iph->iph_lock);
311 
312 	for (dir = 0; dir < IPSEC_NTYPES; dir++) {
313 		ipsec_policy_root_t *ipr = &iph->iph_root[dir];
314 		int nchains = ipr->ipr_nchains;
315 		int chain;
316 
317 		for (chain = 0; chain < nchains; chain++)
318 			mutex_destroy(&(ipr->ipr_hash[chain].hash_lock));
319 
320 	}
321 	ipsec_polhead_free_table(iph);
322 }
323 
324 /*
325  * Module unload hook.
326  */
327 void
328 ipsec_policy_destroy(void)
329 {
330 	int i;
331 
332 	ip_drop_unregister(&spd_dropper);
333 	ip_drop_destroy();
334 
335 	ipsec_polhead_destroy(&system_policy);
336 	ipsec_polhead_destroy(&inactive_policy);
337 
338 	for (i = 0; i < IPSEC_ACTION_HASH_SIZE; i++)
339 		mutex_destroy(&(ipsec_action_hash[i].hash_lock));
340 
341 	for (i = 0; i < ipsec_spd_hashsize; i++)
342 		mutex_destroy(&(ipsec_sel_hash[i].hash_lock));
343 
344 	ipsec_unregister_prov_update();
345 
346 	mutex_destroy(&alg_lock);
347 
348 	kmem_cache_destroy(ipsec_action_cache);
349 	kmem_cache_destroy(ipsec_sel_cache);
350 	kmem_cache_destroy(ipsec_pol_cache);
351 	kmem_cache_destroy(ipsec_info_cache);
352 	ipsid_gc();
353 	ipsid_fini();
354 }
355 
356 
357 /*
358  * Called when table allocation fails to free the table.
359  */
360 static int
361 ipsec_alloc_tables_failed()
362 {
363 	if (ipsec_sel_hash != NULL) {
364 		kmem_free(ipsec_sel_hash, ipsec_spd_hashsize *
365 		    sizeof (*ipsec_sel_hash));
366 		ipsec_sel_hash = NULL;
367 	}
368 	ipsec_polhead_free_table(&system_policy);
369 	ipsec_polhead_free_table(&inactive_policy);
370 
371 	return (ENOMEM);
372 }
373 
374 /*
375  * Attempt to allocate the tables in a single policy head.
376  * Return nonzero on failure after cleaning up any work in progress.
377  */
378 static int
379 ipsec_alloc_table(ipsec_policy_head_t *iph, int kmflag)
380 {
381 	int dir, nchains;
382 
383 	nchains = ipsec_spd_hashsize;
384 
385 	for (dir = 0; dir < IPSEC_NTYPES; dir++) {
386 		ipsec_policy_root_t *ipr = &iph->iph_root[dir];
387 
388 		ipr->ipr_hash = kmem_zalloc(nchains *
389 		    sizeof (ipsec_policy_hash_t), kmflag);
390 		if (ipr->ipr_hash == NULL)
391 			return (ipsec_alloc_tables_failed());
392 	}
393 	return (0);
394 }
395 
396 /*
397  * Attempt to allocate the various tables.  Return nonzero on failure
398  * after cleaning up any work in progress.
399  */
400 static int
401 ipsec_alloc_tables(int kmflag)
402 {
403 	int error;
404 
405 	error = ipsec_alloc_table(&system_policy, kmflag);
406 	if (error != 0)
407 		return (error);
408 
409 	error = ipsec_alloc_table(&inactive_policy, kmflag);
410 	if (error != 0)
411 		return (error);
412 
413 	ipsec_sel_hash = kmem_zalloc(ipsec_spd_hashsize *
414 	    sizeof (*ipsec_sel_hash), kmflag);
415 
416 	if (ipsec_sel_hash == NULL)
417 		return (ipsec_alloc_tables_failed());
418 
419 	return (0);
420 }
421 
422 /*
423  * After table allocation, initialize a policy head.
424  */
425 static void
426 ipsec_polhead_init(ipsec_policy_head_t *iph)
427 {
428 	int dir, chain, nchains;
429 
430 	nchains = ipsec_spd_hashsize;
431 
432 	rw_init(&iph->iph_lock, NULL, RW_DEFAULT, NULL);
433 	avl_create(&iph->iph_rulebyid, ipsec_policy_cmpbyid,
434 	    sizeof (ipsec_policy_t), offsetof(ipsec_policy_t, ipsp_byid));
435 
436 	for (dir = 0; dir < IPSEC_NTYPES; dir++) {
437 		ipsec_policy_root_t *ipr = &iph->iph_root[dir];
438 		ipr->ipr_nchains = nchains;
439 
440 		for (chain = 0; chain < nchains; chain++) {
441 			mutex_init(&(ipr->ipr_hash[chain].hash_lock),
442 			    NULL, MUTEX_DEFAULT, NULL);
443 		}
444 	}
445 }
446 
447 /*
448  * Module load hook.
449  */
450 void
451 ipsec_policy_init()
452 {
453 	int i;
454 
455 	/*
456 	 * Make two attempts to allocate policy hash tables; try it at
457 	 * the "preferred" size (may be set in /etc/system) first,
458 	 * then fall back to the default size.
459 	 */
460 	if (ipsec_spd_hashsize == 0)
461 		ipsec_spd_hashsize = IPSEC_SPDHASH_DEFAULT;
462 
463 	if (ipsec_alloc_tables(KM_NOSLEEP) != 0) {
464 		cmn_err(CE_WARN,
465 		    "Unable to allocate %d entry IPsec policy hash table",
466 		    ipsec_spd_hashsize);
467 		ipsec_spd_hashsize = IPSEC_SPDHASH_DEFAULT;
468 		cmn_err(CE_WARN, "Falling back to %d entries",
469 		    ipsec_spd_hashsize);
470 		(void) ipsec_alloc_tables(KM_SLEEP);
471 	}
472 
473 	ipsid_init();
474 	ipsec_polhead_init(&system_policy);
475 	ipsec_polhead_init(&inactive_policy);
476 
477 	for (i = 0; i < IPSEC_ACTION_HASH_SIZE; i++)
478 		mutex_init(&(ipsec_action_hash[i].hash_lock),
479 		    NULL, MUTEX_DEFAULT, NULL);
480 
481 	for (i = 0; i < ipsec_spd_hashsize; i++)
482 		mutex_init(&(ipsec_sel_hash[i].hash_lock),
483 		    NULL, MUTEX_DEFAULT, NULL);
484 
485 	mutex_init(&alg_lock, NULL, MUTEX_DEFAULT, NULL);
486 
487 	for (i = 0; i < IPSEC_NALGTYPES; i++)
488 		ipsec_nalgs[i] = 0;
489 
490 	ipsec_action_cache = kmem_cache_create("ipsec_actions",
491 	    sizeof (ipsec_action_t), _POINTER_ALIGNMENT, NULL, NULL,
492 	    ipsec_action_reclaim, NULL, NULL, 0);
493 	ipsec_sel_cache = kmem_cache_create("ipsec_selectors",
494 	    sizeof (ipsec_sel_t), _POINTER_ALIGNMENT, NULL, NULL,
495 	    NULL, NULL, NULL, 0);
496 	ipsec_pol_cache = kmem_cache_create("ipsec_policy",
497 	    sizeof (ipsec_policy_t), _POINTER_ALIGNMENT, NULL, NULL,
498 	    NULL, NULL, NULL, 0);
499 	ipsec_info_cache = kmem_cache_create("ipsec_info",
500 	    sizeof (ipsec_info_t), _POINTER_ALIGNMENT, NULL, NULL,
501 	    NULL, NULL, NULL, 0);
502 
503 	ip_drop_init();
504 	ip_drop_register(&spd_dropper, "IPsec SPD");
505 }
506 
507 /*
508  * Sort algorithm lists.
509  *
510  * I may need to split this based on
511  * authentication/encryption, and I may wish to have an administrator
512  * configure this list.  Hold on to some NDD variables...
513  *
514  * XXX For now, sort on minimum key size (GAG!).  While minimum key size is
515  * not the ideal metric, it's the only quantifiable measure available.
516  * We need a better metric for sorting algorithms by preference.
517  */
518 static void
519 alg_insert_sortlist(enum ipsec_algtype at, uint8_t algid)
520 {
521 	ipsec_alginfo_t *ai = ipsec_alglists[at][algid];
522 	uint8_t holder, swap;
523 	uint_t i;
524 	uint_t count = ipsec_nalgs[at];
525 	ASSERT(ai != NULL);
526 	ASSERT(algid == ai->alg_id);
527 
528 	ASSERT(MUTEX_HELD(&alg_lock));
529 
530 	holder = algid;
531 
532 	for (i = 0; i < count - 1; i++) {
533 		ipsec_alginfo_t *alt;
534 
535 		alt = ipsec_alglists[at][ipsec_sortlist[at][i]];
536 		/*
537 		 * If you want to give precedence to newly added algs,
538 		 * add the = in the > comparison.
539 		 */
540 		if ((holder != algid) || (ai->alg_minbits > alt->alg_minbits)) {
541 			/* Swap sortlist[i] and holder. */
542 			swap = ipsec_sortlist[at][i];
543 			ipsec_sortlist[at][i] = holder;
544 			holder = swap;
545 			ai = alt;
546 		} /* Else just continue. */
547 	}
548 
549 	/* Store holder in last slot. */
550 	ipsec_sortlist[at][i] = holder;
551 }
552 
553 /*
554  * Remove an algorithm from a sorted algorithm list.
555  * This should be considerably easier, even with complex sorting.
556  */
557 static void
558 alg_remove_sortlist(enum ipsec_algtype at, uint8_t algid)
559 {
560 	boolean_t copyback = B_FALSE;
561 	int i;
562 	int newcount = ipsec_nalgs[at];
563 
564 	ASSERT(MUTEX_HELD(&alg_lock));
565 
566 	for (i = 0; i <= newcount; i++) {
567 		if (copyback)
568 			ipsec_sortlist[at][i-1] = ipsec_sortlist[at][i];
569 		else if (ipsec_sortlist[at][i] == algid)
570 			copyback = B_TRUE;
571 	}
572 }
573 
574 /*
575  * Add the specified algorithm to the algorithm tables.
576  * Must be called while holding the algorithm table writer lock.
577  */
578 void
579 ipsec_alg_reg(ipsec_algtype_t algtype, ipsec_alginfo_t *alg)
580 {
581 	ASSERT(MUTEX_HELD(&alg_lock));
582 
583 	ASSERT(ipsec_alglists[algtype][alg->alg_id] == NULL);
584 	ipsec_alg_fix_min_max(alg, algtype);
585 	ipsec_alglists[algtype][alg->alg_id] = alg;
586 
587 	ipsec_nalgs[algtype]++;
588 	alg_insert_sortlist(algtype, alg->alg_id);
589 }
590 
591 /*
592  * Remove the specified algorithm from the algorithm tables.
593  * Must be called while holding the algorithm table writer lock.
594  */
595 void
596 ipsec_alg_unreg(ipsec_algtype_t algtype, uint8_t algid)
597 {
598 	ASSERT(MUTEX_HELD(&alg_lock));
599 
600 	ASSERT(ipsec_alglists[algtype][algid] != NULL);
601 	ipsec_alg_free(ipsec_alglists[algtype][algid]);
602 	ipsec_alglists[algtype][algid] = NULL;
603 
604 	ipsec_nalgs[algtype]--;
605 	alg_remove_sortlist(algtype, algid);
606 }
607 
608 /*
609  * Hooks for spdsock to get a grip on system policy.
610  */
611 
612 ipsec_policy_head_t *
613 ipsec_system_policy(void)
614 {
615 	ipsec_policy_head_t *h = &system_policy;
616 	IPPH_REFHOLD(h);
617 	return (h);
618 }
619 
620 ipsec_policy_head_t *
621 ipsec_inactive_policy(void)
622 {
623 	ipsec_policy_head_t *h = &inactive_policy;
624 	IPPH_REFHOLD(h);
625 	return (h);
626 }
627 
628 /*
629  * Lock inactive policy, then active policy, then exchange policy root
630  * pointers.
631  */
632 void
633 ipsec_swap_policy(void)
634 {
635 	int af, dir;
636 	avl_tree_t r1, r2;
637 
638 	rw_enter(&inactive_policy.iph_lock, RW_WRITER);
639 	rw_enter(&system_policy.iph_lock, RW_WRITER);
640 
641 	r1 = system_policy.iph_rulebyid;
642 	r2 = inactive_policy.iph_rulebyid;
643 	system_policy.iph_rulebyid = r2;
644 	inactive_policy.iph_rulebyid = r1;
645 
646 	for (dir = 0; dir < IPSEC_NTYPES; dir++) {
647 		ipsec_policy_hash_t *h1, *h2;
648 
649 		h1 = system_policy.iph_root[dir].ipr_hash;
650 		h2 = inactive_policy.iph_root[dir].ipr_hash;
651 		system_policy.iph_root[dir].ipr_hash = h2;
652 		inactive_policy.iph_root[dir].ipr_hash = h1;
653 
654 		for (af = 0; af < IPSEC_NAF; af++) {
655 			ipsec_policy_t *t1, *t2;
656 
657 			t1 = system_policy.iph_root[dir].ipr_nonhash[af];
658 			t2 = inactive_policy.iph_root[dir].ipr_nonhash[af];
659 			system_policy.iph_root[dir].ipr_nonhash[af] = t2;
660 			inactive_policy.iph_root[dir].ipr_nonhash[af] = t1;
661 			if (t1 != NULL) {
662 				t1->ipsp_hash.hash_pp =
663 				    &(inactive_policy.iph_root[dir].
664 				    ipr_nonhash[af]);
665 			}
666 			if (t2 != NULL) {
667 				t2->ipsp_hash.hash_pp =
668 				    &(system_policy.iph_root[dir].
669 				    ipr_nonhash[af]);
670 			}
671 
672 		}
673 	}
674 	system_policy.iph_gen++;
675 	inactive_policy.iph_gen++;
676 	ipsec_update_present_flags();
677 	rw_exit(&system_policy.iph_lock);
678 	rw_exit(&inactive_policy.iph_lock);
679 }
680 
681 /*
682  * Clone one policy rule..
683  */
684 static ipsec_policy_t *
685 ipsec_copy_policy(const ipsec_policy_t *src)
686 {
687 	ipsec_policy_t *dst = kmem_cache_alloc(ipsec_pol_cache, KM_NOSLEEP);
688 
689 	if (dst == NULL)
690 		return (NULL);
691 
692 	/*
693 	 * Adjust refcounts of cloned state.
694 	 */
695 	IPACT_REFHOLD(src->ipsp_act);
696 	src->ipsp_sel->ipsl_refs++;
697 
698 	HASH_NULL(dst, ipsp_hash);
699 	dst->ipsp_refs = 1;
700 	dst->ipsp_sel = src->ipsp_sel;
701 	dst->ipsp_act = src->ipsp_act;
702 	dst->ipsp_prio = src->ipsp_prio;
703 	dst->ipsp_index = src->ipsp_index;
704 
705 	return (dst);
706 }
707 
708 void
709 ipsec_insert_always(avl_tree_t *tree, void *new_node)
710 {
711 	void *node;
712 	avl_index_t where;
713 
714 	node = avl_find(tree, new_node, &where);
715 	ASSERT(node == NULL);
716 	avl_insert(tree, new_node, where);
717 }
718 
719 
720 static int
721 ipsec_copy_chain(ipsec_policy_head_t *dph, ipsec_policy_t *src,
722     ipsec_policy_t **dstp)
723 {
724 	for (; src != NULL; src = src->ipsp_hash.hash_next) {
725 		ipsec_policy_t *dst = ipsec_copy_policy(src);
726 		if (dst == NULL)
727 			return (ENOMEM);
728 
729 		HASHLIST_INSERT(dst, ipsp_hash, *dstp);
730 		ipsec_insert_always(&dph->iph_rulebyid, dst);
731 	}
732 	return (0);
733 }
734 
735 
736 
737 /*
738  * Make one policy head look exactly like another.
739  *
740  * As with ipsec_swap_policy, we lock the destination policy head first, then
741  * the source policy head. Note that we only need to read-lock the source
742  * policy head as we are not changing it.
743  */
744 static int
745 ipsec_copy_polhead(ipsec_policy_head_t *sph, ipsec_policy_head_t *dph)
746 {
747 	int af, dir, chain, nchains;
748 
749 	rw_enter(&dph->iph_lock, RW_WRITER);
750 
751 	ipsec_polhead_flush(dph);
752 
753 	rw_enter(&sph->iph_lock, RW_READER);
754 
755 	for (dir = 0; dir < IPSEC_NTYPES; dir++) {
756 		ipsec_policy_root_t *dpr = &dph->iph_root[dir];
757 		ipsec_policy_root_t *spr = &sph->iph_root[dir];
758 		nchains = dpr->ipr_nchains;
759 
760 		ASSERT(dpr->ipr_nchains == spr->ipr_nchains);
761 
762 		for (af = 0; af < IPSEC_NAF; af++) {
763 			if (ipsec_copy_chain(dph, spr->ipr_nonhash[af],
764 			    &dpr->ipr_nonhash[af]))
765 				goto abort_copy;
766 		}
767 
768 		for (chain = 0; chain < nchains; chain++) {
769 			if (ipsec_copy_chain(dph,
770 			    spr->ipr_hash[chain].hash_head,
771 			    &dpr->ipr_hash[chain].hash_head))
772 				goto abort_copy;
773 		}
774 	}
775 
776 	dph->iph_gen++;
777 
778 	rw_exit(&sph->iph_lock);
779 	rw_exit(&dph->iph_lock);
780 	return (0);
781 
782 abort_copy:
783 	ipsec_polhead_flush(dph);
784 	rw_exit(&sph->iph_lock);
785 	rw_exit(&dph->iph_lock);
786 	return (ENOMEM);
787 }
788 
789 /*
790  * Clone currently active policy to the inactive policy list.
791  */
792 int
793 ipsec_clone_system_policy(void)
794 {
795 	return (ipsec_copy_polhead(&system_policy, &inactive_policy));
796 }
797 
798 
799 /*
800  * Extract the string from ipsec_policy_failure_msgs[type] and
801  * log it.
802  *
803  * This function needs to be kept in synch with ipsec_rl_strlog() in
804  * sadb.c.
805  * XXX this function should be combined with the ipsec_rl_strlog() function.
806  */
807 void
808 ipsec_log_policy_failure(queue_t *q, int type, char *func_name, ipha_t *ipha,
809     ip6_t *ip6h, boolean_t secure)
810 {
811 	char	sbuf[INET6_ADDRSTRLEN];
812 	char	dbuf[INET6_ADDRSTRLEN];
813 	char	*s;
814 	char	*d;
815 	hrtime_t current = gethrtime();
816 
817 	ASSERT((ipha == NULL && ip6h != NULL) ||
818 	    (ip6h == NULL && ipha != NULL));
819 
820 	if (ipha != NULL) {
821 		s = inet_ntop(AF_INET, &ipha->ipha_src, sbuf, sizeof (sbuf));
822 		d = inet_ntop(AF_INET, &ipha->ipha_dst, dbuf, sizeof (dbuf));
823 	} else {
824 		s = inet_ntop(AF_INET6, &ip6h->ip6_src, sbuf, sizeof (sbuf));
825 		d = inet_ntop(AF_INET6, &ip6h->ip6_dst, dbuf, sizeof (dbuf));
826 
827 	}
828 
829 	/* Always bump the policy failure counter. */
830 	ipsec_policy_failure_count[type]++;
831 
832 	/* Convert interval (in msec) to hrtime (in nsec), which means * 10^6 */
833 	if (ipsec_policy_failure_last +
834 	    ((hrtime_t)ipsec_policy_log_interval * (hrtime_t)1000000) <=
835 	    current) {
836 		/*
837 		 * Throttle the logging such that I only log one message
838 		 * every 'ipsec_policy_log_interval' amount of time.
839 		 */
840 		(void) mi_strlog(q, 0, SL_ERROR|SL_WARN|SL_CONSOLE,
841 		    ipsec_policy_failure_msgs[type],
842 		    func_name,
843 		    (secure ? "secure" : "not secure"), s, d);
844 		ipsec_policy_failure_last = current;
845 	}
846 }
847 
848 void
849 ipsec_config_flush()
850 {
851 	rw_enter(&system_policy.iph_lock, RW_WRITER);
852 	ipsec_polhead_flush(&system_policy);
853 	ipsec_next_policy_index = 1;
854 	rw_exit(&system_policy.iph_lock);
855 	ipsec_action_reclaim(0);
856 }
857 
858 /*
859  * Clip a policy's min/max keybits vs. the capabilities of the
860  * algorithm.
861  */
862 static void
863 act_alg_adjust(uint_t algtype, uint_t algid,
864     uint16_t *minbits, uint16_t *maxbits)
865 {
866 	ipsec_alginfo_t *algp = ipsec_alglists[algtype][algid];
867 	if (algp != NULL) {
868 		/*
869 		 * If passed-in minbits is zero, we assume the caller trusts
870 		 * us with setting the minimum key size.  We pick the
871 		 * algorithms DEFAULT key size for the minimum in this case.
872 		 */
873 		if (*minbits == 0) {
874 			*minbits = algp->alg_default_bits;
875 			ASSERT(*minbits >= algp->alg_minbits);
876 		} else {
877 			*minbits = MAX(*minbits, algp->alg_minbits);
878 		}
879 		if (*maxbits == 0)
880 			*maxbits = algp->alg_maxbits;
881 		else
882 			*maxbits = MIN(*maxbits, algp->alg_maxbits);
883 		ASSERT(*minbits <= *maxbits);
884 	} else {
885 		*minbits = 0;
886 		*maxbits = 0;
887 	}
888 }
889 
890 /*
891  * Check an action's requested algorithms against the algorithms currently
892  * loaded in the system.
893  */
894 boolean_t
895 ipsec_check_action(ipsec_act_t *act, int *diag)
896 {
897 	ipsec_prot_t *ipp;
898 
899 	ipp = &act->ipa_apply;
900 
901 	if (ipp->ipp_use_ah &&
902 	    ipsec_alglists[IPSEC_ALG_AUTH][ipp->ipp_auth_alg] == NULL) {
903 		*diag = SPD_DIAGNOSTIC_UNSUPP_AH_ALG;
904 		return (B_FALSE);
905 	}
906 	if (ipp->ipp_use_espa &&
907 	    ipsec_alglists[IPSEC_ALG_AUTH][ipp->ipp_esp_auth_alg] == NULL) {
908 		*diag = SPD_DIAGNOSTIC_UNSUPP_ESP_AUTH_ALG;
909 		return (B_FALSE);
910 	}
911 	if (ipp->ipp_use_esp &&
912 	    ipsec_alglists[IPSEC_ALG_ENCR][ipp->ipp_encr_alg] == NULL) {
913 		*diag = SPD_DIAGNOSTIC_UNSUPP_ESP_ENCR_ALG;
914 		return (B_FALSE);
915 	}
916 
917 	act_alg_adjust(IPSEC_ALG_AUTH, ipp->ipp_auth_alg,
918 	    &ipp->ipp_ah_minbits, &ipp->ipp_ah_maxbits);
919 	act_alg_adjust(IPSEC_ALG_AUTH, ipp->ipp_esp_auth_alg,
920 	    &ipp->ipp_espa_minbits, &ipp->ipp_espa_maxbits);
921 	act_alg_adjust(IPSEC_ALG_ENCR, ipp->ipp_encr_alg,
922 	    &ipp->ipp_espe_minbits, &ipp->ipp_espe_maxbits);
923 
924 	if (ipp->ipp_ah_minbits > ipp->ipp_ah_maxbits) {
925 		*diag = SPD_DIAGNOSTIC_UNSUPP_AH_KEYSIZE;
926 		return (B_FALSE);
927 	}
928 	if (ipp->ipp_espa_minbits > ipp->ipp_espa_maxbits) {
929 		*diag = SPD_DIAGNOSTIC_UNSUPP_ESP_AUTH_KEYSIZE;
930 		return (B_FALSE);
931 	}
932 	if (ipp->ipp_espe_minbits > ipp->ipp_espe_maxbits) {
933 		*diag = SPD_DIAGNOSTIC_UNSUPP_ESP_ENCR_KEYSIZE;
934 		return (B_FALSE);
935 	}
936 	/* TODO: sanity check lifetimes */
937 	return (B_TRUE);
938 }
939 
940 /*
941  * Set up a single action during wildcard expansion..
942  */
943 static void
944 ipsec_setup_act(ipsec_act_t *outact, ipsec_act_t *act,
945     uint_t auth_alg, uint_t encr_alg, uint_t eauth_alg)
946 {
947 	ipsec_prot_t *ipp;
948 
949 	*outact = *act;
950 	ipp = &outact->ipa_apply;
951 	ipp->ipp_auth_alg = (uint8_t)auth_alg;
952 	ipp->ipp_encr_alg = (uint8_t)encr_alg;
953 	ipp->ipp_esp_auth_alg = (uint8_t)eauth_alg;
954 
955 	act_alg_adjust(IPSEC_ALG_AUTH, auth_alg,
956 	    &ipp->ipp_ah_minbits, &ipp->ipp_ah_maxbits);
957 	act_alg_adjust(IPSEC_ALG_AUTH, eauth_alg,
958 	    &ipp->ipp_espa_minbits, &ipp->ipp_espa_maxbits);
959 	act_alg_adjust(IPSEC_ALG_ENCR, encr_alg,
960 	    &ipp->ipp_espe_minbits, &ipp->ipp_espe_maxbits);
961 }
962 
963 /*
964  * combinatoric expansion time: expand a wildcarded action into an
965  * array of wildcarded actions; we return the exploded action list,
966  * and return a count in *nact (output only).
967  */
968 static ipsec_act_t *
969 ipsec_act_wildcard_expand(ipsec_act_t *act, uint_t *nact)
970 {
971 	boolean_t use_ah, use_esp, use_espa;
972 	boolean_t wild_auth, wild_encr, wild_eauth;
973 	uint_t	auth_alg, auth_idx, auth_min, auth_max;
974 	uint_t	eauth_alg, eauth_idx, eauth_min, eauth_max;
975 	uint_t  encr_alg, encr_idx, encr_min, encr_max;
976 	uint_t	action_count, ai;
977 	ipsec_act_t *outact;
978 
979 	if (act->ipa_type != IPSEC_ACT_APPLY) {
980 		outact = kmem_alloc(sizeof (*act), KM_NOSLEEP);
981 		*nact = 1;
982 		if (outact != NULL)
983 			bcopy(act, outact, sizeof (*act));
984 		return (outact);
985 	}
986 	/*
987 	 * compute the combinatoric explosion..
988 	 *
989 	 * we assume a request for encr if esp_req is PREF_REQUIRED
990 	 * we assume a request for ah auth if ah_req is PREF_REQUIRED.
991 	 * we assume a request for esp auth if !ah and esp_req is PREF_REQUIRED
992 	 */
993 
994 	use_ah = act->ipa_apply.ipp_use_ah;
995 	use_esp = act->ipa_apply.ipp_use_esp;
996 	use_espa = act->ipa_apply.ipp_use_espa;
997 	auth_alg = act->ipa_apply.ipp_auth_alg;
998 	eauth_alg = act->ipa_apply.ipp_esp_auth_alg;
999 	encr_alg = act->ipa_apply.ipp_encr_alg;
1000 
1001 	wild_auth = use_ah && (auth_alg == 0);
1002 	wild_eauth = use_espa && (eauth_alg == 0);
1003 	wild_encr = use_esp && (encr_alg == 0);
1004 
1005 	action_count = 1;
1006 	auth_min = auth_max = auth_alg;
1007 	eauth_min = eauth_max = eauth_alg;
1008 	encr_min = encr_max = encr_alg;
1009 
1010 	/*
1011 	 * set up for explosion.. for each dimension, expand output
1012 	 * size by the explosion factor.
1013 	 *
1014 	 * Don't include the "any" algorithms, if defined, as no
1015 	 * kernel policies should be set for these algorithms.
1016 	 */
1017 
1018 #define	SET_EXP_MINMAX(type, wild, alg, min, max) if (wild) {	\
1019 		int nalgs = ipsec_nalgs[type];			\
1020 		if (ipsec_alglists[type][alg] != NULL)		\
1021 			nalgs--;				\
1022 		action_count *= nalgs;				\
1023 		min = 0;					\
1024 		max = ipsec_nalgs[type] - 1;			\
1025 	}
1026 
1027 	SET_EXP_MINMAX(IPSEC_ALG_AUTH, wild_auth, SADB_AALG_NONE,
1028 	    auth_min, auth_max);
1029 	SET_EXP_MINMAX(IPSEC_ALG_AUTH, wild_eauth, SADB_AALG_NONE,
1030 	    eauth_min, eauth_max);
1031 	SET_EXP_MINMAX(IPSEC_ALG_ENCR, wild_encr, SADB_EALG_NONE,
1032 	    encr_min, encr_max);
1033 
1034 #undef	SET_EXP_MINMAX
1035 
1036 	/*
1037 	 * ok, allocate the whole mess..
1038 	 */
1039 
1040 	outact = kmem_alloc(sizeof (*outact) * action_count, KM_NOSLEEP);
1041 	if (outact == NULL)
1042 		return (NULL);
1043 
1044 	/*
1045 	 * Now compute all combinations.  Note that non-wildcarded
1046 	 * dimensions just get a single value from auth_min, while
1047 	 * wildcarded dimensions indirect through the sortlist.
1048 	 *
1049 	 * We do encryption outermost since, at this time, there's
1050 	 * greater difference in security and performance between
1051 	 * encryption algorithms vs. authentication algorithms.
1052 	 */
1053 
1054 	ai = 0;
1055 
1056 #define	WHICH_ALG(type, wild, idx) ((wild)?(ipsec_sortlist[type][idx]):(idx))
1057 
1058 	for (encr_idx = encr_min; encr_idx <= encr_max; encr_idx++) {
1059 		encr_alg = WHICH_ALG(IPSEC_ALG_ENCR, wild_encr, encr_idx);
1060 		if (wild_encr && encr_alg == SADB_EALG_NONE)
1061 			continue;
1062 		for (auth_idx = auth_min; auth_idx <= auth_max; auth_idx++) {
1063 			auth_alg = WHICH_ALG(IPSEC_ALG_AUTH, wild_auth,
1064 			    auth_idx);
1065 			if (wild_auth && auth_alg == SADB_AALG_NONE)
1066 				continue;
1067 			for (eauth_idx = eauth_min; eauth_idx <= eauth_max;
1068 			    eauth_idx++) {
1069 				eauth_alg = WHICH_ALG(IPSEC_ALG_AUTH,
1070 				    wild_eauth, eauth_idx);
1071 				if (wild_eauth && eauth_alg == SADB_AALG_NONE)
1072 					continue;
1073 
1074 				ipsec_setup_act(&outact[ai], act,
1075 				    auth_alg, encr_alg, eauth_alg);
1076 				ai++;
1077 			}
1078 		}
1079 	}
1080 
1081 #undef WHICH_ALG
1082 
1083 	ASSERT(ai == action_count);
1084 	*nact = action_count;
1085 	return (outact);
1086 }
1087 
1088 /*
1089  * Extract the parts of an ipsec_prot_t from an old-style ipsec_req_t.
1090  */
1091 static void
1092 ipsec_prot_from_req(ipsec_req_t *req, ipsec_prot_t *ipp)
1093 {
1094 	bzero(ipp, sizeof (*ipp));
1095 	/*
1096 	 * ipp_use_* are bitfields.  Look at "!!" in the following as a
1097 	 * "boolean canonicalization" operator.
1098 	 */
1099 	ipp->ipp_use_ah = !!(req->ipsr_ah_req & IPSEC_PREF_REQUIRED);
1100 	ipp->ipp_use_esp = !!(req->ipsr_esp_req & IPSEC_PREF_REQUIRED);
1101 	ipp->ipp_use_espa = !!(req->ipsr_esp_auth_alg) || !ipp->ipp_use_ah;
1102 	ipp->ipp_use_se = !!(req->ipsr_self_encap_req & IPSEC_PREF_REQUIRED);
1103 	ipp->ipp_use_unique = !!((req->ipsr_ah_req|req->ipsr_esp_req) &
1104 	    IPSEC_PREF_UNIQUE);
1105 	ipp->ipp_encr_alg = req->ipsr_esp_alg;
1106 	ipp->ipp_auth_alg = req->ipsr_auth_alg;
1107 	ipp->ipp_esp_auth_alg = req->ipsr_esp_auth_alg;
1108 }
1109 
1110 /*
1111  * Extract a new-style action from a request.
1112  */
1113 void
1114 ipsec_actvec_from_req(ipsec_req_t *req, ipsec_act_t **actp, uint_t *nactp)
1115 {
1116 	struct ipsec_act act;
1117 	bzero(&act, sizeof (act));
1118 	if ((req->ipsr_ah_req & IPSEC_PREF_NEVER) &&
1119 	    (req->ipsr_esp_req & IPSEC_PREF_NEVER)) {
1120 		act.ipa_type = IPSEC_ACT_BYPASS;
1121 	} else {
1122 		act.ipa_type = IPSEC_ACT_APPLY;
1123 		ipsec_prot_from_req(req, &act.ipa_apply);
1124 	}
1125 	*actp = ipsec_act_wildcard_expand(&act, nactp);
1126 }
1127 
1128 /*
1129  * Convert a new-style "prot" back to an ipsec_req_t (more backwards compat).
1130  * We assume caller has already zero'ed *req for us.
1131  */
1132 static int
1133 ipsec_req_from_prot(ipsec_prot_t *ipp, ipsec_req_t *req)
1134 {
1135 	req->ipsr_esp_alg = ipp->ipp_encr_alg;
1136 	req->ipsr_auth_alg = ipp->ipp_auth_alg;
1137 	req->ipsr_esp_auth_alg = ipp->ipp_esp_auth_alg;
1138 
1139 	if (ipp->ipp_use_unique) {
1140 		req->ipsr_ah_req |= IPSEC_PREF_UNIQUE;
1141 		req->ipsr_esp_req |= IPSEC_PREF_UNIQUE;
1142 	}
1143 	if (ipp->ipp_use_se)
1144 		req->ipsr_self_encap_req |= IPSEC_PREF_REQUIRED;
1145 	if (ipp->ipp_use_ah)
1146 		req->ipsr_ah_req |= IPSEC_PREF_REQUIRED;
1147 	if (ipp->ipp_use_esp)
1148 		req->ipsr_esp_req |= IPSEC_PREF_REQUIRED;
1149 	return (sizeof (*req));
1150 }
1151 
1152 /*
1153  * Convert a new-style action back to an ipsec_req_t (more backwards compat).
1154  * We assume caller has already zero'ed *req for us.
1155  */
1156 static int
1157 ipsec_req_from_act(ipsec_action_t *ap, ipsec_req_t *req)
1158 {
1159 	switch (ap->ipa_act.ipa_type) {
1160 	case IPSEC_ACT_BYPASS:
1161 		req->ipsr_ah_req = IPSEC_PREF_NEVER;
1162 		req->ipsr_esp_req = IPSEC_PREF_NEVER;
1163 		return (sizeof (*req));
1164 	case IPSEC_ACT_APPLY:
1165 		return (ipsec_req_from_prot(&ap->ipa_act.ipa_apply, req));
1166 	}
1167 	return (sizeof (*req));
1168 }
1169 
1170 /*
1171  * Convert a new-style action back to an ipsec_req_t (more backwards compat).
1172  * We assume caller has already zero'ed *req for us.
1173  */
1174 static int
1175 ipsec_req_from_head(ipsec_policy_head_t *ph, ipsec_req_t *req, int af)
1176 {
1177 	ipsec_policy_t *p;
1178 
1179 	/*
1180 	 * FULL-PERSOCK: consult hash table, too?
1181 	 */
1182 	for (p = ph->iph_root[IPSEC_INBOUND].ipr_nonhash[af];
1183 	    p != NULL;
1184 	    p = p->ipsp_hash.hash_next) {
1185 		if ((p->ipsp_sel->ipsl_key.ipsl_valid&IPSL_WILDCARD) == 0)
1186 			return (ipsec_req_from_act(p->ipsp_act, req));
1187 	}
1188 	return (sizeof (*req));
1189 }
1190 
1191 /*
1192  * Based on per-socket or latched policy, convert to an appropriate
1193  * IP_SEC_OPT ipsec_req_t for the socket option; return size so we can
1194  * be tail-called from ip.
1195  */
1196 int
1197 ipsec_req_from_conn(conn_t *connp, ipsec_req_t *req, int af)
1198 {
1199 	ipsec_latch_t *ipl;
1200 	int rv = sizeof (ipsec_req_t);
1201 
1202 	bzero(req, sizeof (*req));
1203 
1204 	mutex_enter(&connp->conn_lock);
1205 	ipl = connp->conn_latch;
1206 
1207 	/*
1208 	 * Find appropriate policy.  First choice is latched action;
1209 	 * failing that, see latched policy; failing that,
1210 	 * look at configured policy.
1211 	 */
1212 	if (ipl != NULL) {
1213 		if (ipl->ipl_in_action != NULL) {
1214 			rv = ipsec_req_from_act(ipl->ipl_in_action, req);
1215 			goto done;
1216 		}
1217 		if (ipl->ipl_in_policy != NULL) {
1218 			rv = ipsec_req_from_act(ipl->ipl_in_policy->ipsp_act,
1219 			    req);
1220 			goto done;
1221 		}
1222 	}
1223 	if (connp->conn_policy != NULL)
1224 		rv = ipsec_req_from_head(connp->conn_policy, req, af);
1225 done:
1226 	mutex_exit(&connp->conn_lock);
1227 	return (rv);
1228 }
1229 
1230 void
1231 ipsec_actvec_free(ipsec_act_t *act, uint_t nact)
1232 {
1233 	kmem_free(act, nact * sizeof (*act));
1234 }
1235 
1236 /*
1237  * When outbound policy is not cached, look it up the hard way and attach
1238  * an ipsec_out_t to the packet..
1239  */
1240 static mblk_t *
1241 ipsec_attach_global_policy(mblk_t *mp, conn_t *connp, ipsec_selector_t *sel)
1242 {
1243 	ipsec_policy_t *p;
1244 
1245 	p = ipsec_find_policy(IPSEC_TYPE_OUTBOUND, connp, NULL, sel);
1246 
1247 	if (p == NULL)
1248 		return (NULL);
1249 	return (ipsec_attach_ipsec_out(mp, connp, p, sel->ips_protocol));
1250 }
1251 
1252 /*
1253  * We have an ipsec_out already, but don't have cached policy; fill it in
1254  * with the right actions.
1255  */
1256 static mblk_t *
1257 ipsec_apply_global_policy(mblk_t *ipsec_mp, conn_t *connp,
1258     ipsec_selector_t *sel)
1259 {
1260 	ipsec_out_t *io;
1261 	ipsec_policy_t *p;
1262 
1263 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL);
1264 	ASSERT(ipsec_mp->b_cont->b_datap->db_type == M_DATA);
1265 
1266 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
1267 
1268 	if (io->ipsec_out_policy == NULL) {
1269 		p = ipsec_find_policy(IPSEC_TYPE_OUTBOUND, connp, io, sel);
1270 		io->ipsec_out_policy = p;
1271 	}
1272 	return (ipsec_mp);
1273 }
1274 
1275 
1276 /* ARGSUSED */
1277 /*
1278  * Consumes a reference to ipsp.
1279  */
1280 static mblk_t *
1281 ipsec_check_loopback_policy(queue_t *q, mblk_t *first_mp,
1282     boolean_t mctl_present, ipsec_policy_t *ipsp)
1283 {
1284 	mblk_t *ipsec_mp;
1285 	ipsec_in_t *ii;
1286 
1287 	if (!mctl_present)
1288 		return (first_mp);
1289 
1290 	ipsec_mp = first_mp;
1291 
1292 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
1293 	ASSERT(ii->ipsec_in_loopback);
1294 	IPPOL_REFRELE(ipsp);
1295 
1296 	/*
1297 	 * We should do an actual policy check here.  Revisit this
1298 	 * when we revisit the IPsec API.
1299 	 */
1300 
1301 	return (first_mp);
1302 }
1303 
1304 static boolean_t
1305 ipsec_check_ipsecin_action(ipsec_in_t *ii, mblk_t *mp, ipsec_action_t *ap,
1306     ipha_t *ipha, ip6_t *ip6h, const char **reason, kstat_named_t **counter)
1307 {
1308 	boolean_t ret = B_TRUE;
1309 	ipsec_prot_t *ipp;
1310 	ipsa_t *ah_assoc;
1311 	ipsa_t *esp_assoc;
1312 	boolean_t decaps;
1313 
1314 	ASSERT((ipha == NULL && ip6h != NULL) ||
1315 	    (ip6h == NULL && ipha != NULL));
1316 
1317 	if (ii->ipsec_in_loopback) {
1318 		/*
1319 		 * Besides accepting pointer-equivalent actions, we also
1320 		 * accept any ICMP errors we generated for ourselves,
1321 		 * regardless of policy.  If we do not wish to make this
1322 		 * assumption in the future, check here, and where
1323 		 * icmp_loopback is initialized in ip.c and ip6.c.  (Look for
1324 		 * ipsec_out_icmp_loopback.)
1325 		 */
1326 		if (ap == ii->ipsec_in_action || ii->ipsec_in_icmp_loopback)
1327 			return (B_TRUE);
1328 
1329 		/* Deep compare necessary here?? */
1330 		*counter = &ipdrops_spd_loopback_mismatch;
1331 		*reason = "loopback policy mismatch";
1332 		return (B_FALSE);
1333 	}
1334 	ASSERT(!ii->ipsec_in_icmp_loopback);
1335 
1336 	ah_assoc = ii->ipsec_in_ah_sa;
1337 	esp_assoc = ii->ipsec_in_esp_sa;
1338 
1339 	decaps = ii->ipsec_in_decaps;
1340 
1341 	switch (ap->ipa_act.ipa_type) {
1342 	case IPSEC_ACT_DISCARD:
1343 	case IPSEC_ACT_REJECT:
1344 		/* Should "fail hard" */
1345 		*counter = &ipdrops_spd_explicit;
1346 		*reason = "blocked by policy";
1347 		return (B_FALSE);
1348 
1349 	case IPSEC_ACT_BYPASS:
1350 	case IPSEC_ACT_CLEAR:
1351 		*counter = &ipdrops_spd_got_secure;
1352 		*reason = "expected clear, got protected";
1353 		return (B_FALSE);
1354 
1355 	case IPSEC_ACT_APPLY:
1356 		ipp = &ap->ipa_act.ipa_apply;
1357 		/*
1358 		 * As of now we do the simple checks of whether
1359 		 * the datagram has gone through the required IPSEC
1360 		 * protocol constraints or not. We might have more
1361 		 * in the future like sensitive levels, key bits, etc.
1362 		 * If it fails the constraints, check whether we would
1363 		 * have accepted this if it had come in clear.
1364 		 */
1365 		if (ipp->ipp_use_ah) {
1366 			if (ah_assoc == NULL) {
1367 				ret = ipsec_inbound_accept_clear(mp, ipha,
1368 				    ip6h);
1369 				*counter = &ipdrops_spd_got_clear;
1370 				*reason = "unprotected not accepted";
1371 				break;
1372 			}
1373 			ASSERT(ah_assoc != NULL);
1374 			ASSERT(ipp->ipp_auth_alg != 0);
1375 
1376 			if (ah_assoc->ipsa_auth_alg !=
1377 			    ipp->ipp_auth_alg) {
1378 				*counter = &ipdrops_spd_bad_ahalg;
1379 				*reason = "unacceptable ah alg";
1380 				ret = B_FALSE;
1381 				break;
1382 			}
1383 		} else if (ah_assoc != NULL) {
1384 			/*
1385 			 * Don't allow this. Check IPSEC NOTE above
1386 			 * ip_fanout_proto().
1387 			 */
1388 			*counter = &ipdrops_spd_got_ah;
1389 			*reason = "unexpected AH";
1390 			ret = B_FALSE;
1391 			break;
1392 		}
1393 		if (ipp->ipp_use_esp) {
1394 			if (esp_assoc == NULL) {
1395 				ret = ipsec_inbound_accept_clear(mp, ipha,
1396 				    ip6h);
1397 				*counter = &ipdrops_spd_got_clear;
1398 				*reason = "unprotected not accepted";
1399 				break;
1400 			}
1401 			ASSERT(esp_assoc != NULL);
1402 			ASSERT(ipp->ipp_encr_alg != 0);
1403 
1404 			if (esp_assoc->ipsa_encr_alg !=
1405 			    ipp->ipp_encr_alg) {
1406 				*counter = &ipdrops_spd_bad_espealg;
1407 				*reason = "unacceptable esp alg";
1408 				ret = B_FALSE;
1409 				break;
1410 			}
1411 			/*
1412 			 * If the client does not need authentication,
1413 			 * we don't verify the alogrithm.
1414 			 */
1415 			if (ipp->ipp_use_espa) {
1416 				if (esp_assoc->ipsa_auth_alg !=
1417 				    ipp->ipp_esp_auth_alg) {
1418 					*counter = &ipdrops_spd_bad_espaalg;
1419 					*reason = "unacceptable esp auth alg";
1420 					ret = B_FALSE;
1421 					break;
1422 				}
1423 			}
1424 		} else if (esp_assoc != NULL) {
1425 				/*
1426 				 * Don't allow this. Check IPSEC NOTE above
1427 				 * ip_fanout_proto().
1428 				 */
1429 			*counter = &ipdrops_spd_got_esp;
1430 			*reason = "unexpected ESP";
1431 			ret = B_FALSE;
1432 			break;
1433 		}
1434 		if (ipp->ipp_use_se) {
1435 			if (!decaps) {
1436 				ret = ipsec_inbound_accept_clear(mp, ipha,
1437 				    ip6h);
1438 				if (!ret) {
1439 					/* XXX mutant? */
1440 					*counter = &ipdrops_spd_bad_selfencap;
1441 					*reason = "self encap not found";
1442 					break;
1443 				}
1444 			}
1445 		} else if (decaps) {
1446 			/*
1447 			 * XXX If the packet comes in tunneled and the
1448 			 * recipient does not expect it to be tunneled, it
1449 			 * is okay. But we drop to be consistent with the
1450 			 * other cases.
1451 			 */
1452 			*counter = &ipdrops_spd_got_selfencap;
1453 			*reason = "unexpected self encap";
1454 			ret = B_FALSE;
1455 			break;
1456 		}
1457 		if (ii->ipsec_in_action != NULL) {
1458 			/*
1459 			 * This can happen if we do a double policy-check on
1460 			 * a packet
1461 			 * XXX XXX should fix this case!
1462 			 */
1463 			IPACT_REFRELE(ii->ipsec_in_action);
1464 		}
1465 		ASSERT(ii->ipsec_in_action == NULL);
1466 		IPACT_REFHOLD(ap);
1467 		ii->ipsec_in_action = ap;
1468 		break;	/* from switch */
1469 	}
1470 	return (ret);
1471 }
1472 
1473 static boolean_t
1474 spd_match_inbound_ids(ipsec_latch_t *ipl, ipsa_t *sa)
1475 {
1476 	ASSERT(ipl->ipl_ids_latched == B_TRUE);
1477 	return ipsid_equal(ipl->ipl_remote_cid, sa->ipsa_src_cid) &&
1478 	    ipsid_equal(ipl->ipl_local_cid, sa->ipsa_dst_cid);
1479 }
1480 
1481 /*
1482  * Called to check policy on a latched connection, both from this file
1483  * and from tcp.c
1484  */
1485 boolean_t
1486 ipsec_check_ipsecin_latch(ipsec_in_t *ii, mblk_t *mp, ipsec_latch_t *ipl,
1487     ipha_t *ipha, ip6_t *ip6h, const char **reason, kstat_named_t **counter)
1488 {
1489 	ASSERT(ipl->ipl_ids_latched == B_TRUE);
1490 
1491 	if ((ii->ipsec_in_ah_sa != NULL) &&
1492 	    (!spd_match_inbound_ids(ipl, ii->ipsec_in_ah_sa))) {
1493 		*counter = &ipdrops_spd_ah_badid;
1494 		*reason = "AH identity mismatch";
1495 		return (B_FALSE);
1496 	}
1497 
1498 	if ((ii->ipsec_in_esp_sa != NULL) &&
1499 	    (!spd_match_inbound_ids(ipl, ii->ipsec_in_esp_sa))) {
1500 		*counter = &ipdrops_spd_esp_badid;
1501 		*reason = "ESP identity mismatch";
1502 		return (B_FALSE);
1503 	}
1504 
1505 	return (ipsec_check_ipsecin_action(ii, mp, ipl->ipl_in_action,
1506 	    ipha, ip6h, reason, counter));
1507 }
1508 
1509 /*
1510  * Check to see whether this secured datagram meets the policy
1511  * constraints specified in ipsp.
1512  *
1513  * Called from ipsec_check_global_policy, and ipsec_check_inbound_policy.
1514  *
1515  * Consumes a reference to ipsp.
1516  */
1517 static mblk_t *
1518 ipsec_check_ipsecin_policy(queue_t *q, mblk_t *first_mp, ipsec_policy_t *ipsp,
1519     ipha_t *ipha, ip6_t *ip6h)
1520 {
1521 	ipsec_in_t *ii;
1522 	ipsec_action_t *ap;
1523 	const char *reason = "no policy actions found";
1524 	mblk_t *data_mp, *ipsec_mp;
1525 	kstat_named_t *counter = &ipdrops_spd_got_secure;
1526 
1527 	data_mp = first_mp->b_cont;
1528 	ipsec_mp = first_mp;
1529 
1530 	ASSERT(ipsp != NULL);
1531 
1532 	ASSERT((ipha == NULL && ip6h != NULL) ||
1533 	    (ip6h == NULL && ipha != NULL));
1534 
1535 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
1536 
1537 	if (ii->ipsec_in_loopback)
1538 		return (ipsec_check_loopback_policy(q, first_mp, B_TRUE, ipsp));
1539 
1540 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
1541 	if (ii->ipsec_in_action != NULL) {
1542 		/*
1543 		 * this can happen if we do a double policy-check on a packet
1544 		 * Would be nice to be able to delete this test..
1545 		 */
1546 		IPACT_REFRELE(ii->ipsec_in_action);
1547 	}
1548 	ASSERT(ii->ipsec_in_action == NULL);
1549 
1550 	if (!SA_IDS_MATCH(ii->ipsec_in_ah_sa, ii->ipsec_in_esp_sa)) {
1551 		reason = "inbound AH and ESP identities differ";
1552 		counter = &ipdrops_spd_ahesp_diffid;
1553 		goto drop;
1554 	}
1555 
1556 	/*
1557 	 * Ok, now loop through the possible actions and see if any
1558 	 * of them work for us.
1559 	 */
1560 
1561 	for (ap = ipsp->ipsp_act; ap != NULL; ap = ap->ipa_next) {
1562 		if (ipsec_check_ipsecin_action(ii, data_mp, ap,
1563 		    ipha, ip6h, &reason, &counter)) {
1564 			BUMP_MIB(&ip_mib, ipsecInSucceeded);
1565 			IPPOL_REFRELE(ipsp);
1566 			return (first_mp);
1567 		}
1568 	}
1569 drop:
1570 	(void) mi_strlog(q, 0, SL_ERROR|SL_WARN|SL_CONSOLE,
1571 	    "ipsec inbound policy mismatch: %s, packet dropped\n",
1572 	    reason);
1573 	IPPOL_REFRELE(ipsp);
1574 	ASSERT(ii->ipsec_in_action == NULL);
1575 	BUMP_MIB(&ip_mib, ipsecInFailed);
1576 	ip_drop_packet(first_mp, B_TRUE, NULL, NULL, counter, &spd_dropper);
1577 	return (NULL);
1578 }
1579 
1580 /*
1581  * sleazy prefix-length-based compare.
1582  * another inlining candidate..
1583  */
1584 static boolean_t
1585 ip_addr_match(uint8_t *addr1, int pfxlen, in6_addr_t *addr2p)
1586 {
1587 	int offset = pfxlen>>3;
1588 	int bitsleft = pfxlen & 7;
1589 	uint8_t *addr2 = (uint8_t *)addr2p;
1590 
1591 	/*
1592 	 * and there was much evil..
1593 	 * XXX should inline-expand the bcmp here and do this 32 bits
1594 	 * or 64 bits at a time..
1595 	 */
1596 	return ((bcmp(addr1, addr2, offset) == 0) &&
1597 	    ((bitsleft == 0) ||
1598 		(((addr1[offset] ^ addr2[offset]) &
1599 		    (0xff<<(8-bitsleft))) == 0)));
1600 }
1601 
1602 static ipsec_policy_t *
1603 ipsec_find_policy_chain(ipsec_policy_t *best, ipsec_policy_t *chain,
1604     ipsec_selector_t *sel, boolean_t is_icmp_inv_acq)
1605 {
1606 	ipsec_selkey_t *isel;
1607 	ipsec_policy_t *p;
1608 	int bpri = best ? best->ipsp_prio : 0;
1609 
1610 	for (p = chain; p != NULL; p = p->ipsp_hash.hash_next) {
1611 		uint32_t valid;
1612 
1613 		if (p->ipsp_prio <= bpri)
1614 			continue;
1615 		isel = &p->ipsp_sel->ipsl_key;
1616 		valid = isel->ipsl_valid;
1617 
1618 		if ((valid & IPSL_PROTOCOL) &&
1619 		    (isel->ipsl_proto != sel->ips_protocol))
1620 			continue;
1621 
1622 		if ((valid & IPSL_REMOTE_ADDR) &&
1623 		    !ip_addr_match((uint8_t *)&isel->ipsl_remote,
1624 			isel->ipsl_remote_pfxlen,
1625 			&sel->ips_remote_addr_v6))
1626 			continue;
1627 
1628 		if ((valid & IPSL_LOCAL_ADDR) &&
1629 		    !ip_addr_match((uint8_t *)&isel->ipsl_local,
1630 			isel->ipsl_local_pfxlen,
1631 			&sel->ips_local_addr_v6))
1632 			continue;
1633 
1634 		if ((valid & IPSL_REMOTE_PORT) &&
1635 		    isel->ipsl_rport != sel->ips_remote_port)
1636 			continue;
1637 
1638 		if ((valid & IPSL_LOCAL_PORT) &&
1639 		    isel->ipsl_lport != sel->ips_local_port)
1640 			continue;
1641 
1642 		if (!is_icmp_inv_acq) {
1643 			if ((valid & IPSL_ICMP_TYPE) &&
1644 			    (isel->ipsl_icmp_type > sel->ips_icmp_type ||
1645 			    isel->ipsl_icmp_type_end < sel->ips_icmp_type)) {
1646 				continue;
1647 			}
1648 
1649 			if ((valid & IPSL_ICMP_CODE) &&
1650 			    (isel->ipsl_icmp_code > sel->ips_icmp_code ||
1651 			    isel->ipsl_icmp_code_end <
1652 			    sel->ips_icmp_code)) {
1653 				continue;
1654 			}
1655 		} else {
1656 			/*
1657 			 * special case for icmp inverse acquire
1658 			 * we only want policies that aren't drop/pass
1659 			 */
1660 			if (p->ipsp_act->ipa_act.ipa_type != IPSEC_ACT_APPLY)
1661 				continue;
1662 		}
1663 
1664 		/* we matched all the packet-port-field selectors! */
1665 		best = p;
1666 		bpri = p->ipsp_prio;
1667 	}
1668 
1669 	return (best);
1670 }
1671 
1672 /*
1673  * Try to find and return the best policy entry under a given policy
1674  * root for a given set of selectors; the first parameter "best" is
1675  * the current best policy so far.  If "best" is non-null, we have a
1676  * reference to it.  We return a reference to a policy; if that policy
1677  * is not the original "best", we need to release that reference
1678  * before returning.
1679  */
1680 static ipsec_policy_t *
1681 ipsec_find_policy_head(ipsec_policy_t *best,
1682     ipsec_policy_head_t *head, int direction, ipsec_selector_t *sel,
1683     int selhash)
1684 {
1685 	ipsec_policy_t *curbest;
1686 	ipsec_policy_root_t *root;
1687 	uint8_t is_icmp_inv_acq = sel->ips_is_icmp_inv_acq;
1688 	int af = sel->ips_isv4 ? IPSEC_AF_V4 : IPSEC_AF_V6;
1689 
1690 	curbest = best;
1691 	root = &head->iph_root[direction];
1692 
1693 #ifdef DEBUG
1694 	if (is_icmp_inv_acq) {
1695 		if (sel->ips_isv4) {
1696 			if (sel->ips_protocol != IPPROTO_ICMP) {
1697 			    cmn_err(CE_WARN, "ipsec_find_policy_head:"
1698 			    " expecting icmp, got %d", sel->ips_protocol);
1699 			}
1700 		} else {
1701 			if (sel->ips_protocol != IPPROTO_ICMPV6) {
1702 				cmn_err(CE_WARN, "ipsec_find_policy_head:"
1703 				" expecting icmpv6, got %d", sel->ips_protocol);
1704 			}
1705 		}
1706 	}
1707 #endif
1708 
1709 	rw_enter(&head->iph_lock, RW_READER);
1710 
1711 	if (root->ipr_nchains > 0) {
1712 		curbest = ipsec_find_policy_chain(curbest,
1713 		    root->ipr_hash[selhash].hash_head, sel, is_icmp_inv_acq);
1714 	}
1715 	curbest = ipsec_find_policy_chain(curbest, root->ipr_nonhash[af], sel,
1716 	    is_icmp_inv_acq);
1717 
1718 	/*
1719 	 * Adjust reference counts if we found anything new.
1720 	 */
1721 	if (curbest != best) {
1722 		ASSERT(curbest != NULL);
1723 		IPPOL_REFHOLD(curbest);
1724 
1725 		if (best != NULL) {
1726 			IPPOL_REFRELE(best);
1727 		}
1728 	}
1729 
1730 	rw_exit(&head->iph_lock);
1731 
1732 	return (curbest);
1733 }
1734 
1735 /*
1736  * Find the best system policy (either global or per-interface) which
1737  * applies to the given selector; look in all the relevant policy roots
1738  * to figure out which policy wins.
1739  *
1740  * Returns a reference to a policy; caller must release this
1741  * reference when done.
1742  */
1743 ipsec_policy_t *
1744 ipsec_find_policy(int direction, conn_t *connp, ipsec_out_t *io,
1745     ipsec_selector_t *sel)
1746 {
1747 	ipsec_policy_t *p;
1748 	int selhash = selector_hash(sel);
1749 
1750 	p = ipsec_find_policy_head(NULL, &system_policy, direction, sel,
1751 	    selhash);
1752 	if ((connp != NULL) && (connp->conn_policy != NULL)) {
1753 		p = ipsec_find_policy_head(p, connp->conn_policy,
1754 		    direction, sel, selhash);
1755 	} else if ((io != NULL) && (io->ipsec_out_polhead != NULL)) {
1756 		p = ipsec_find_policy_head(p, io->ipsec_out_polhead,
1757 		    direction, sel, selhash);
1758 	}
1759 
1760 	return (p);
1761 }
1762 
1763 /*
1764  * Check with global policy and see whether this inbound
1765  * packet meets the policy constraints.
1766  *
1767  * Locate appropriate policy from global policy, supplemented by the
1768  * conn's configured and/or cached policy if the conn is supplied.
1769  *
1770  * Dispatch to ipsec_check_ipsecin_policy if we have policy and an
1771  * encrypted packet to see if they match.
1772  *
1773  * Otherwise, see if the policy allows cleartext; if not, drop it on the
1774  * floor.
1775  */
1776 mblk_t *
1777 ipsec_check_global_policy(mblk_t *first_mp, conn_t *connp,
1778     ipha_t *ipha, ip6_t *ip6h, boolean_t mctl_present)
1779 {
1780 	ipsec_policy_t *p;
1781 	ipsec_selector_t sel;
1782 	queue_t *q = NULL;
1783 	mblk_t *data_mp, *ipsec_mp;
1784 	boolean_t policy_present;
1785 	kstat_named_t *counter;
1786 
1787 	data_mp = mctl_present ? first_mp->b_cont : first_mp;
1788 	ipsec_mp = mctl_present ? first_mp : NULL;
1789 
1790 	sel.ips_is_icmp_inv_acq = 0;
1791 
1792 	ASSERT((ipha == NULL && ip6h != NULL) ||
1793 	    (ip6h == NULL && ipha != NULL));
1794 
1795 	if (ipha != NULL)
1796 		policy_present = ipsec_inbound_v4_policy_present;
1797 	else
1798 		policy_present = ipsec_inbound_v6_policy_present;
1799 
1800 	if (!policy_present && connp == NULL) {
1801 		/*
1802 		 * No global policy and no per-socket policy;
1803 		 * just pass it back (but we shouldn't get here in that case)
1804 		 */
1805 		return (first_mp);
1806 	}
1807 
1808 	if (connp != NULL)
1809 		q = CONNP_TO_WQ(connp);
1810 
1811 	if (ipsec_mp != NULL) {
1812 		ASSERT(ipsec_mp->b_datap->db_type == M_CTL);
1813 		ASSERT(((ipsec_in_t *)ipsec_mp->b_rptr)->ipsec_in_type ==
1814 		    IPSEC_IN);
1815 	}
1816 
1817 	/*
1818 	 * If we have cached policy, use it.
1819 	 * Otherwise consult system policy.
1820 	 */
1821 	if ((connp != NULL) && (connp->conn_latch != NULL)) {
1822 		p = connp->conn_latch->ipl_in_policy;
1823 		if (p != NULL) {
1824 			IPPOL_REFHOLD(p);
1825 		}
1826 	} else {
1827 		/* Initialize the ports in the selector */
1828 		if (!ipsec_init_inbound_sel(&sel, data_mp, ipha, ip6h)) {
1829 			/*
1830 			 * Technically not a policy mismatch, but it is
1831 			 * an internal failure.
1832 			 */
1833 			ipsec_log_policy_failure(q, IPSEC_POLICY_MISMATCH,
1834 			    "ipsec_init_inbound_sel", ipha, ip6h, B_FALSE);
1835 			counter = &ipdrops_spd_nomem;
1836 			goto fail;
1837 		}
1838 
1839 		/*
1840 		 * Find the policy which best applies.
1841 		 *
1842 		 * If we find global policy, we should look at both
1843 		 * local policy and global policy and see which is
1844 		 * stronger and match accordingly.
1845 		 *
1846 		 * If we don't find a global policy, check with
1847 		 * local policy alone.
1848 		 */
1849 
1850 		p = ipsec_find_policy(IPSEC_TYPE_INBOUND, connp, NULL, &sel);
1851 	}
1852 
1853 	if (p == NULL) {
1854 		if (ipsec_mp == NULL) {
1855 			/*
1856 			 * We have no policy; default to succeeding.
1857 			 * XXX paranoid system design doesn't do this.
1858 			 */
1859 			BUMP_MIB(&ip_mib, ipsecInSucceeded);
1860 			return (first_mp);
1861 		} else {
1862 			counter = &ipdrops_spd_got_secure;
1863 			ipsec_log_policy_failure(q, IPSEC_POLICY_NOT_NEEDED,
1864 			    "ipsec_check_global_policy", ipha, ip6h, B_TRUE);
1865 			goto fail;
1866 		}
1867 	}
1868 	if (ipsec_mp != NULL)
1869 		return (ipsec_check_ipsecin_policy(q, ipsec_mp, p, ipha, ip6h));
1870 	if (p->ipsp_act->ipa_allow_clear) {
1871 		BUMP_MIB(&ip_mib, ipsecInSucceeded);
1872 		IPPOL_REFRELE(p);
1873 		return (first_mp);
1874 	}
1875 	IPPOL_REFRELE(p);
1876 	/*
1877 	 * If we reach here, we will drop the packet because it failed the
1878 	 * global policy check because the packet was cleartext, and it
1879 	 * should not have been.
1880 	 */
1881 	ipsec_log_policy_failure(q, IPSEC_POLICY_MISMATCH,
1882 	    "ipsec_check_global_policy", ipha, ip6h, B_FALSE);
1883 	counter = &ipdrops_spd_got_clear;
1884 
1885 fail:
1886 	ip_drop_packet(first_mp, B_TRUE, NULL, NULL, counter, &spd_dropper);
1887 	BUMP_MIB(&ip_mib, ipsecInFailed);
1888 	return (NULL);
1889 }
1890 
1891 /*
1892  * We check whether an inbound datagram is a valid one
1893  * to accept in clear. If it is secure, it is the job
1894  * of IPSEC to log information appropriately if it
1895  * suspects that it may not be the real one.
1896  *
1897  * It is called only while fanning out to the ULP
1898  * where ULP accepts only secure data and the incoming
1899  * is clear. Usually we never accept clear datagrams in
1900  * such cases. ICMP is the only exception.
1901  *
1902  * NOTE : We don't call this function if the client (ULP)
1903  * is willing to accept things in clear.
1904  */
1905 boolean_t
1906 ipsec_inbound_accept_clear(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h)
1907 {
1908 	ushort_t iph_hdr_length;
1909 	icmph_t *icmph;
1910 	icmp6_t *icmp6;
1911 	uint8_t *nexthdrp;
1912 
1913 	ASSERT((ipha != NULL && ip6h == NULL) ||
1914 	    (ipha == NULL && ip6h != NULL));
1915 
1916 	if (ip6h != NULL) {
1917 		iph_hdr_length = ip_hdr_length_v6(mp, ip6h);
1918 		if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length,
1919 		    &nexthdrp)) {
1920 			return (B_FALSE);
1921 		}
1922 		if (*nexthdrp != IPPROTO_ICMPV6)
1923 			return (B_FALSE);
1924 		icmp6 = (icmp6_t *)(&mp->b_rptr[iph_hdr_length]);
1925 		/* Match IPv6 ICMP policy as closely as IPv4 as possible. */
1926 		switch (icmp6->icmp6_type) {
1927 		case ICMP6_PARAM_PROB:
1928 			/* Corresponds to port/proto unreach in IPv4. */
1929 		case ICMP6_ECHO_REQUEST:
1930 			/* Just like IPv4. */
1931 			return (B_FALSE);
1932 
1933 		case MLD_LISTENER_QUERY:
1934 		case MLD_LISTENER_REPORT:
1935 		case MLD_LISTENER_REDUCTION:
1936 			/*
1937 			 * XXX Seperate NDD in IPv4 what about here?
1938 			 * Plus, mcast is important to ND.
1939 			 */
1940 		case ICMP6_DST_UNREACH:
1941 			/* Corresponds to HOST/NET unreachable in IPv4. */
1942 		case ICMP6_PACKET_TOO_BIG:
1943 		case ICMP6_ECHO_REPLY:
1944 			/* These are trusted in IPv4. */
1945 		case ND_ROUTER_SOLICIT:
1946 		case ND_ROUTER_ADVERT:
1947 		case ND_NEIGHBOR_SOLICIT:
1948 		case ND_NEIGHBOR_ADVERT:
1949 		case ND_REDIRECT:
1950 			/* Trust ND messages for now. */
1951 		case ICMP6_TIME_EXCEEDED:
1952 		default:
1953 			return (B_TRUE);
1954 		}
1955 	} else {
1956 		/*
1957 		 * If it is not ICMP, fail this request.
1958 		 */
1959 		if (ipha->ipha_protocol != IPPROTO_ICMP)
1960 			return (B_FALSE);
1961 		iph_hdr_length = IPH_HDR_LENGTH(ipha);
1962 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1963 		/*
1964 		 * It is an insecure icmp message. Check to see whether we are
1965 		 * willing to accept this one.
1966 		 */
1967 
1968 		switch (icmph->icmph_type) {
1969 		case ICMP_ECHO_REPLY:
1970 		case ICMP_TIME_STAMP_REPLY:
1971 		case ICMP_INFO_REPLY:
1972 		case ICMP_ROUTER_ADVERTISEMENT:
1973 			/*
1974 			 * We should not encourage clear replies if this
1975 			 * client expects secure. If somebody is replying
1976 			 * in clear some mailicious user watching both the
1977 			 * request and reply, can do chosen-plain-text attacks.
1978 			 * With global policy we might be just expecting secure
1979 			 * but sending out clear. We don't know what the right
1980 			 * thing is. We can't do much here as we can't control
1981 			 * the sender here. Till we are sure of what to do,
1982 			 * accept them.
1983 			 */
1984 			return (B_TRUE);
1985 		case ICMP_ECHO_REQUEST:
1986 		case ICMP_TIME_STAMP_REQUEST:
1987 		case ICMP_INFO_REQUEST:
1988 		case ICMP_ADDRESS_MASK_REQUEST:
1989 		case ICMP_ROUTER_SOLICITATION:
1990 		case ICMP_ADDRESS_MASK_REPLY:
1991 			/*
1992 			 * Don't accept this as somebody could be sending
1993 			 * us plain text to get encrypted data. If we reply,
1994 			 * it will lead to chosen plain text attack.
1995 			 */
1996 			return (B_FALSE);
1997 		case ICMP_DEST_UNREACHABLE:
1998 			switch (icmph->icmph_code) {
1999 			case ICMP_FRAGMENTATION_NEEDED:
2000 				/*
2001 				 * Be in sync with icmp_inbound, where we have
2002 				 * already set ire_max_frag.
2003 				 */
2004 				return (B_TRUE);
2005 			case ICMP_HOST_UNREACHABLE:
2006 			case ICMP_NET_UNREACHABLE:
2007 				/*
2008 				 * By accepting, we could reset a connection.
2009 				 * How do we solve the problem of some
2010 				 * intermediate router sending in-secure ICMP
2011 				 * messages ?
2012 				 */
2013 				return (B_TRUE);
2014 			case ICMP_PORT_UNREACHABLE:
2015 			case ICMP_PROTOCOL_UNREACHABLE:
2016 			default :
2017 				return (B_FALSE);
2018 			}
2019 		case ICMP_SOURCE_QUENCH:
2020 			/*
2021 			 * If this is an attack, TCP will slow start
2022 			 * because of this. Is it very harmful ?
2023 			 */
2024 			return (B_TRUE);
2025 		case ICMP_PARAM_PROBLEM:
2026 			return (B_FALSE);
2027 		case ICMP_TIME_EXCEEDED:
2028 			return (B_TRUE);
2029 		case ICMP_REDIRECT:
2030 			return (B_FALSE);
2031 		default :
2032 			return (B_FALSE);
2033 		}
2034 	}
2035 }
2036 
2037 void
2038 ipsec_latch_ids(ipsec_latch_t *ipl, ipsid_t *local, ipsid_t *remote)
2039 {
2040 	mutex_enter(&ipl->ipl_lock);
2041 
2042 	if (ipl->ipl_ids_latched) {
2043 		/* I lost, someone else got here before me */
2044 		mutex_exit(&ipl->ipl_lock);
2045 		return;
2046 	}
2047 
2048 	if (local != NULL)
2049 		IPSID_REFHOLD(local);
2050 	if (remote != NULL)
2051 		IPSID_REFHOLD(remote);
2052 
2053 	ipl->ipl_local_cid = local;
2054 	ipl->ipl_remote_cid = remote;
2055 	ipl->ipl_ids_latched = B_TRUE;
2056 	mutex_exit(&ipl->ipl_lock);
2057 }
2058 
2059 void
2060 ipsec_latch_inbound(ipsec_latch_t *ipl, ipsec_in_t *ii)
2061 {
2062 	ipsa_t *sa;
2063 
2064 	if (!ipl->ipl_ids_latched) {
2065 		ipsid_t *local = NULL;
2066 		ipsid_t *remote = NULL;
2067 
2068 		if (!ii->ipsec_in_loopback) {
2069 			if (ii->ipsec_in_esp_sa != NULL)
2070 				sa = ii->ipsec_in_esp_sa;
2071 			else
2072 				sa = ii->ipsec_in_ah_sa;
2073 			ASSERT(sa != NULL);
2074 			local = sa->ipsa_dst_cid;
2075 			remote = sa->ipsa_src_cid;
2076 		}
2077 		ipsec_latch_ids(ipl, local, remote);
2078 	}
2079 	ipl->ipl_in_action = ii->ipsec_in_action;
2080 	IPACT_REFHOLD(ipl->ipl_in_action);
2081 }
2082 
2083 /*
2084  * Check whether the policy constraints are met either for an
2085  * inbound datagram; called from IP in numerous places.
2086  *
2087  * Note that this is not a chokepoint for inbound policy checks;
2088  * see also ipsec_check_ipsecin_latch()
2089  */
2090 mblk_t *
2091 ipsec_check_inbound_policy(mblk_t *first_mp, conn_t *connp,
2092     ipha_t *ipha, ip6_t *ip6h, boolean_t mctl_present)
2093 {
2094 	ipsec_in_t *ii;
2095 	boolean_t ret;
2096 	mblk_t *mp = mctl_present ? first_mp->b_cont : first_mp;
2097 	mblk_t *ipsec_mp = mctl_present ? first_mp : NULL;
2098 	ipsec_latch_t *ipl;
2099 
2100 	ASSERT(connp != NULL);
2101 	ipl = connp->conn_latch;
2102 
2103 	if (ipsec_mp == NULL) {
2104 		/*
2105 		 * This is the case where the incoming datagram is
2106 		 * cleartext and we need to see whether this client
2107 		 * would like to receive such untrustworthy things from
2108 		 * the wire.
2109 		 */
2110 		ASSERT(mp != NULL);
2111 
2112 		if (ipl != NULL) {
2113 			/*
2114 			 * Policy is cached in the conn.
2115 			 */
2116 			if ((ipl->ipl_in_policy != NULL) &&
2117 			    (!ipl->ipl_in_policy->ipsp_act->ipa_allow_clear)) {
2118 				ret = ipsec_inbound_accept_clear(mp,
2119 				    ipha, ip6h);
2120 				if (ret) {
2121 					BUMP_MIB(&ip_mib, ipsecInSucceeded);
2122 					return (first_mp);
2123 				} else {
2124 					ip_drop_packet(first_mp, B_TRUE, NULL,
2125 					    NULL, &ipdrops_spd_got_clear,
2126 					    &spd_dropper);
2127 					ipsec_log_policy_failure(
2128 					    CONNP_TO_WQ(connp),
2129 					    IPSEC_POLICY_MISMATCH,
2130 					    "ipsec_check_inbound_policy", ipha,
2131 					    ip6h, B_FALSE);
2132 					BUMP_MIB(&ip_mib, ipsecInFailed);
2133 					return (NULL);
2134 				}
2135 			} else {
2136 				BUMP_MIB(&ip_mib, ipsecInSucceeded);
2137 				return (first_mp);
2138 			}
2139 		} else {
2140 			/*
2141 			 * As this is a non-hardbound connection we need
2142 			 * to look at both per-socket policy and global
2143 			 * policy. As this is cleartext, mark the mp as
2144 			 * M_DATA in case if it is an ICMP error being
2145 			 * reported before calling ipsec_check_global_policy
2146 			 * so that it does not mistake it for IPSEC_IN.
2147 			 */
2148 			uchar_t db_type = mp->b_datap->db_type;
2149 			mp->b_datap->db_type = M_DATA;
2150 			first_mp = ipsec_check_global_policy(first_mp, connp,
2151 			    ipha, ip6h, mctl_present);
2152 			if (first_mp != NULL)
2153 				mp->b_datap->db_type = db_type;
2154 			return (first_mp);
2155 		}
2156 	}
2157 	/*
2158 	 * If it is inbound check whether the attached message
2159 	 * is secure or not. We have a special case for ICMP,
2160 	 * where we have a IPSEC_IN message and the attached
2161 	 * message is not secure. See icmp_inbound_error_fanout
2162 	 * for details.
2163 	 */
2164 	ASSERT(ipsec_mp != NULL);
2165 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL);
2166 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
2167 
2168 	/*
2169 	 * mp->b_cont could be either a M_CTL message
2170 	 * for icmp errors being sent up or a M_DATA message.
2171 	 */
2172 	ASSERT(mp->b_datap->db_type == M_CTL ||
2173 	    mp->b_datap->db_type == M_DATA);
2174 
2175 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
2176 
2177 	if (ipl == NULL) {
2178 		/*
2179 		 * We don't have policies cached in the conn's
2180 		 * for this stream. So, look at the global
2181 		 * policy. It will check against conn or global
2182 		 * depending on whichever is stronger.
2183 		 */
2184 		return (ipsec_check_global_policy(first_mp, connp,
2185 		    ipha, ip6h, mctl_present));
2186 	} else if (ipl->ipl_in_action != NULL) {
2187 		/* Policy is cached & latched; fast(er) path */
2188 		const char *reason;
2189 		kstat_named_t *counter;
2190 		if (ipsec_check_ipsecin_latch(ii, mp, ipl,
2191 		    ipha, ip6h, &reason, &counter)) {
2192 			BUMP_MIB(&ip_mib, ipsecInSucceeded);
2193 			return (first_mp);
2194 		}
2195 		(void) mi_strlog(CONNP_TO_WQ(connp), 0,
2196 		    SL_ERROR|SL_WARN|SL_CONSOLE,
2197 		    "ipsec inbound policy mismatch: %s, packet dropped\n",
2198 		    reason);
2199 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL, counter,
2200 		    &spd_dropper);
2201 		BUMP_MIB(&ip_mib, ipsecInFailed);
2202 		return (NULL);
2203 	} else if (ipl->ipl_in_policy == NULL)
2204 		return (first_mp);
2205 
2206 	IPPOL_REFHOLD(ipl->ipl_in_policy);
2207 	first_mp = ipsec_check_ipsecin_policy(CONNP_TO_WQ(connp), first_mp,
2208 	    ipl->ipl_in_policy, ipha, ip6h);
2209 	/*
2210 	 * NOTE: ipsecIn{Failed,Succeeeded} bumped by
2211 	 * ipsec_check_ipsecin_policy().
2212 	 */
2213 	if (first_mp != NULL)
2214 		ipsec_latch_inbound(ipl, ii);
2215 	return (first_mp);
2216 }
2217 
2218 boolean_t
2219 ipsec_init_inbound_sel(ipsec_selector_t *sel, mblk_t *mp,
2220     ipha_t *ipha, ip6_t *ip6h)
2221 {
2222 	uint16_t *ports;
2223 	ushort_t hdr_len;
2224 	mblk_t *spare_mp = NULL;
2225 	uint8_t *nexthdrp;
2226 	uint8_t nexthdr;
2227 	uint8_t *typecode;
2228 	uint8_t check_proto;
2229 
2230 	ASSERT((ipha == NULL && ip6h != NULL) ||
2231 	    (ipha != NULL && ip6h == NULL));
2232 
2233 	if (ip6h != NULL) {
2234 		check_proto = IPPROTO_ICMPV6;
2235 		sel->ips_isv4 = B_FALSE;
2236 		sel->ips_local_addr_v6 = ip6h->ip6_dst;
2237 		sel->ips_remote_addr_v6 = ip6h->ip6_src;
2238 
2239 		nexthdr = ip6h->ip6_nxt;
2240 		switch (nexthdr) {
2241 		case IPPROTO_HOPOPTS:
2242 		case IPPROTO_ROUTING:
2243 		case IPPROTO_DSTOPTS:
2244 			/*
2245 			 * Use ip_hdr_length_nexthdr_v6().  And have a spare
2246 			 * mblk that's contiguous to feed it
2247 			 */
2248 			if ((spare_mp = msgpullup(mp, -1)) == NULL)
2249 				return (B_FALSE);
2250 			if (!ip_hdr_length_nexthdr_v6(spare_mp,
2251 			    (ip6_t *)spare_mp->b_rptr, &hdr_len, &nexthdrp)) {
2252 				/* Malformed packet - XXX ip_drop_packet()? */
2253 				freemsg(spare_mp);
2254 				return (B_FALSE);
2255 			}
2256 			nexthdr = *nexthdrp;
2257 			/* We can just extract based on hdr_len now. */
2258 			break;
2259 		default:
2260 			hdr_len = IPV6_HDR_LEN;
2261 			break;
2262 		}
2263 	} else {
2264 		check_proto = IPPROTO_ICMP;
2265 		sel->ips_isv4 = B_TRUE;
2266 		sel->ips_local_addr_v4 = ipha->ipha_dst;
2267 		sel->ips_remote_addr_v4 = ipha->ipha_src;
2268 		nexthdr = ipha->ipha_protocol;
2269 		hdr_len = IPH_HDR_LENGTH(ipha);
2270 	}
2271 	sel->ips_protocol = nexthdr;
2272 
2273 	if (nexthdr != IPPROTO_TCP && nexthdr != IPPROTO_UDP &&
2274 	    nexthdr != IPPROTO_SCTP && nexthdr != check_proto) {
2275 		sel->ips_remote_port = sel->ips_local_port = 0;
2276 		freemsg(spare_mp);	/* Always works, even if NULL. */
2277 		return (B_TRUE);
2278 	}
2279 
2280 	if (&mp->b_rptr[hdr_len] + 4 > mp->b_wptr) {
2281 		/* If we didn't pullup a copy already, do so now. */
2282 		/*
2283 		 * XXX performance, will upper-layers frequently split TCP/UDP
2284 		 * apart from IP or options?  If so, perhaps we should revisit
2285 		 * the spare_mp strategy.
2286 		 */
2287 		if (spare_mp == NULL &&
2288 		    (spare_mp = msgpullup(mp, -1)) == NULL) {
2289 			return (B_FALSE);
2290 		}
2291 		ports = (uint16_t *)&spare_mp->b_rptr[hdr_len];
2292 	} else {
2293 		ports = (uint16_t *)&mp->b_rptr[hdr_len];
2294 	}
2295 
2296 	if (nexthdr == check_proto) {
2297 		typecode = (uint8_t *)ports;
2298 		sel->ips_icmp_type = *typecode++;
2299 		sel->ips_icmp_code = *typecode;
2300 		sel->ips_remote_port = sel->ips_local_port = 0;
2301 		freemsg(spare_mp);	/* Always works, even if NULL */
2302 		return (B_TRUE);
2303 	}
2304 
2305 	sel->ips_remote_port = *ports++;
2306 	sel->ips_local_port = *ports;
2307 	freemsg(spare_mp);	/* Always works, even if NULL */
2308 	return (B_TRUE);
2309 }
2310 
2311 static boolean_t
2312 ipsec_init_outbound_ports(ipsec_selector_t *sel, mblk_t *mp, ipha_t *ipha,
2313     ip6_t *ip6h)
2314 {
2315 	/*
2316 	 * XXX cut&paste shared with ipsec_init_inbound_sel
2317 	 */
2318 	uint16_t *ports;
2319 	ushort_t hdr_len;
2320 	mblk_t *spare_mp = NULL;
2321 	uint8_t *nexthdrp;
2322 	uint8_t nexthdr;
2323 	uint8_t *typecode;
2324 	uint8_t check_proto;
2325 
2326 	ASSERT((ipha == NULL && ip6h != NULL) ||
2327 	    (ipha != NULL && ip6h == NULL));
2328 
2329 	if (ip6h != NULL) {
2330 		check_proto = IPPROTO_ICMPV6;
2331 		nexthdr = ip6h->ip6_nxt;
2332 		switch (nexthdr) {
2333 		case IPPROTO_HOPOPTS:
2334 		case IPPROTO_ROUTING:
2335 		case IPPROTO_DSTOPTS:
2336 			/*
2337 			 * Use ip_hdr_length_nexthdr_v6().  And have a spare
2338 			 * mblk that's contiguous to feed it
2339 			 */
2340 			spare_mp = msgpullup(mp, -1);
2341 			if (spare_mp == NULL ||
2342 			    !ip_hdr_length_nexthdr_v6(spare_mp,
2343 				(ip6_t *)spare_mp->b_rptr, &hdr_len,
2344 				&nexthdrp)) {
2345 				/* Always works, even if NULL. */
2346 				freemsg(spare_mp);
2347 				freemsg(mp);
2348 				return (B_FALSE);
2349 			} else {
2350 				nexthdr = *nexthdrp;
2351 				/* We can just extract based on hdr_len now. */
2352 			}
2353 			break;
2354 		default:
2355 			hdr_len = IPV6_HDR_LEN;
2356 			break;
2357 		}
2358 	} else {
2359 		check_proto = IPPROTO_ICMP;
2360 		hdr_len = IPH_HDR_LENGTH(ipha);
2361 		nexthdr = ipha->ipha_protocol;
2362 	}
2363 
2364 	sel->ips_protocol = nexthdr;
2365 	if (nexthdr != IPPROTO_TCP && nexthdr != IPPROTO_UDP &&
2366 	    nexthdr != IPPROTO_SCTP && nexthdr != check_proto) {
2367 		sel->ips_local_port = sel->ips_remote_port = 0;
2368 		freemsg(spare_mp);  /* Always works, even if NULL. */
2369 		return (B_TRUE);
2370 	}
2371 
2372 	if (&mp->b_rptr[hdr_len] + 4 > mp->b_wptr) {
2373 		/* If we didn't pullup a copy already, do so now. */
2374 		/*
2375 		 * XXX performance, will upper-layers frequently split TCP/UDP
2376 		 * apart from IP or options?  If so, perhaps we should revisit
2377 		 * the spare_mp strategy.
2378 		 *
2379 		 * XXX should this be msgpullup(mp, hdr_len+4) ???
2380 		 */
2381 		if (spare_mp == NULL &&
2382 		    (spare_mp = msgpullup(mp, -1)) == NULL) {
2383 			freemsg(mp);
2384 			return (B_FALSE);
2385 		}
2386 		ports = (uint16_t *)&spare_mp->b_rptr[hdr_len];
2387 	} else {
2388 		ports = (uint16_t *)&mp->b_rptr[hdr_len];
2389 	}
2390 
2391 	if (nexthdr == check_proto) {
2392 		typecode = (uint8_t *)ports;
2393 		sel->ips_icmp_type = *typecode++;
2394 		sel->ips_icmp_code = *typecode;
2395 		sel->ips_remote_port = sel->ips_local_port = 0;
2396 		freemsg(spare_mp);	/* Always works, even if NULL */
2397 		return (B_TRUE);
2398 	}
2399 
2400 	sel->ips_local_port = *ports++;
2401 	sel->ips_remote_port = *ports;
2402 	freemsg(spare_mp);	/* Always works, even if NULL */
2403 	return (B_TRUE);
2404 }
2405 
2406 /*
2407  * Create an ipsec_action_t based on the way an inbound packet was protected.
2408  * Used to reflect traffic back to a sender.
2409  *
2410  * We don't bother interning the action into the hash table.
2411  */
2412 ipsec_action_t *
2413 ipsec_in_to_out_action(ipsec_in_t *ii)
2414 {
2415 	ipsa_t *ah_assoc, *esp_assoc;
2416 	uint_t auth_alg = 0, encr_alg = 0, espa_alg = 0;
2417 	ipsec_action_t *ap;
2418 	boolean_t unique;
2419 
2420 	ap = kmem_cache_alloc(ipsec_action_cache, KM_NOSLEEP);
2421 
2422 	if (ap == NULL)
2423 		return (NULL);
2424 
2425 	bzero(ap, sizeof (*ap));
2426 	HASH_NULL(ap, ipa_hash);
2427 	ap->ipa_next = NULL;
2428 	ap->ipa_refs = 1;
2429 
2430 	/*
2431 	 * Get the algorithms that were used for this packet.
2432 	 */
2433 	ap->ipa_act.ipa_type = IPSEC_ACT_APPLY;
2434 	ap->ipa_act.ipa_log = 0;
2435 	ah_assoc = ii->ipsec_in_ah_sa;
2436 	ap->ipa_act.ipa_apply.ipp_use_ah = (ah_assoc != NULL);
2437 
2438 	esp_assoc = ii->ipsec_in_esp_sa;
2439 	ap->ipa_act.ipa_apply.ipp_use_esp = (esp_assoc != NULL);
2440 
2441 	if (esp_assoc != NULL) {
2442 		encr_alg = esp_assoc->ipsa_encr_alg;
2443 		espa_alg = esp_assoc->ipsa_auth_alg;
2444 		ap->ipa_act.ipa_apply.ipp_use_espa = (espa_alg != 0);
2445 	}
2446 	if (ah_assoc != NULL)
2447 		auth_alg = ah_assoc->ipsa_auth_alg;
2448 
2449 	ap->ipa_act.ipa_apply.ipp_encr_alg = (uint8_t)encr_alg;
2450 	ap->ipa_act.ipa_apply.ipp_auth_alg = (uint8_t)auth_alg;
2451 	ap->ipa_act.ipa_apply.ipp_esp_auth_alg = (uint8_t)espa_alg;
2452 	ap->ipa_act.ipa_apply.ipp_use_se = ii->ipsec_in_decaps;
2453 	unique = B_FALSE;
2454 
2455 	if (esp_assoc != NULL) {
2456 		ap->ipa_act.ipa_apply.ipp_espa_minbits =
2457 		    esp_assoc->ipsa_authkeybits;
2458 		ap->ipa_act.ipa_apply.ipp_espa_maxbits =
2459 		    esp_assoc->ipsa_authkeybits;
2460 		ap->ipa_act.ipa_apply.ipp_espe_minbits =
2461 		    esp_assoc->ipsa_encrkeybits;
2462 		ap->ipa_act.ipa_apply.ipp_espe_maxbits =
2463 		    esp_assoc->ipsa_encrkeybits;
2464 		ap->ipa_act.ipa_apply.ipp_km_proto = esp_assoc->ipsa_kmp;
2465 		ap->ipa_act.ipa_apply.ipp_km_cookie = esp_assoc->ipsa_kmc;
2466 		if (esp_assoc->ipsa_flags & IPSA_F_UNIQUE)
2467 			unique = B_TRUE;
2468 	}
2469 	if (ah_assoc != NULL) {
2470 		ap->ipa_act.ipa_apply.ipp_ah_minbits =
2471 		    ah_assoc->ipsa_authkeybits;
2472 		ap->ipa_act.ipa_apply.ipp_ah_maxbits =
2473 		    ah_assoc->ipsa_authkeybits;
2474 		ap->ipa_act.ipa_apply.ipp_km_proto = ah_assoc->ipsa_kmp;
2475 		ap->ipa_act.ipa_apply.ipp_km_cookie = ah_assoc->ipsa_kmc;
2476 		if (ah_assoc->ipsa_flags & IPSA_F_UNIQUE)
2477 			unique = B_TRUE;
2478 	}
2479 	ap->ipa_act.ipa_apply.ipp_use_unique = unique;
2480 	ap->ipa_want_unique = unique;
2481 	ap->ipa_allow_clear = B_FALSE;
2482 	ap->ipa_want_se = ii->ipsec_in_decaps;
2483 	ap->ipa_want_ah = (ah_assoc != NULL);
2484 	ap->ipa_want_esp = (esp_assoc != NULL);
2485 
2486 	ap->ipa_ovhd = ipsec_act_ovhd(&ap->ipa_act);
2487 
2488 	ap->ipa_act.ipa_apply.ipp_replay_depth = 0; /* don't care */
2489 
2490 	return (ap);
2491 }
2492 
2493 
2494 /*
2495  * Compute the worst-case amount of extra space required by an action.
2496  * Note that, because of the ESP considerations listed below, this is
2497  * actually not the same as the best-case reduction in the MTU; in the
2498  * future, we should pass additional information to this function to
2499  * allow the actual MTU impact to be computed.
2500  *
2501  * AH: Revisit this if we implement algorithms with
2502  * a verifier size of more than 12 bytes.
2503  *
2504  * ESP: A more exact but more messy computation would take into
2505  * account the interaction between the cipher block size and the
2506  * effective MTU, yielding the inner payload size which reflects a
2507  * packet with *minimum* ESP padding..
2508  */
2509 static int32_t
2510 ipsec_act_ovhd(const ipsec_act_t *act)
2511 {
2512 	int32_t overhead = 0;
2513 
2514 	if (act->ipa_type == IPSEC_ACT_APPLY) {
2515 		const ipsec_prot_t *ipp = &act->ipa_apply;
2516 
2517 		if (ipp->ipp_use_ah)
2518 			overhead += IPSEC_MAX_AH_HDR_SIZE;
2519 		if (ipp->ipp_use_esp) {
2520 			overhead += IPSEC_MAX_ESP_HDR_SIZE;
2521 			overhead += sizeof (struct udphdr);
2522 		}
2523 		if (ipp->ipp_use_se)
2524 			overhead += IP_SIMPLE_HDR_LENGTH;
2525 	}
2526 	return (overhead);
2527 }
2528 
2529 /*
2530  * This hash function is used only when creating policies and thus is not
2531  * performance-critical for packet flows.
2532  *
2533  * Future work: canonicalize the structures hashed with this (i.e.,
2534  * zeroize padding) so the hash works correctly.
2535  */
2536 /* ARGSUSED */
2537 static uint32_t
2538 policy_hash(int size, const void *start, const void *end)
2539 {
2540 	return (0);
2541 }
2542 
2543 
2544 /*
2545  * Hash function macros for each address type.
2546  *
2547  * The IPV6 hash function assumes that the low order 32-bits of the
2548  * address (typically containing the low order 24 bits of the mac
2549  * address) are reasonably well-distributed.  Revisit this if we run
2550  * into trouble from lots of collisions on ::1 addresses and the like
2551  * (seems unlikely).
2552  */
2553 #define	IPSEC_IPV4_HASH(a) ((a) % ipsec_spd_hashsize)
2554 #define	IPSEC_IPV6_HASH(a) ((a.s6_addr32[3]) % ipsec_spd_hashsize)
2555 
2556 /*
2557  * These two hash functions should produce coordinated values
2558  * but have slightly different roles.
2559  */
2560 static uint32_t
2561 selkey_hash(const ipsec_selkey_t *selkey)
2562 {
2563 	uint32_t valid = selkey->ipsl_valid;
2564 
2565 	if (!(valid & IPSL_REMOTE_ADDR))
2566 		return (IPSEC_SEL_NOHASH);
2567 
2568 	if (valid & IPSL_IPV4) {
2569 		if (selkey->ipsl_remote_pfxlen == 32)
2570 			return (IPSEC_IPV4_HASH(selkey->ipsl_remote.ipsad_v4));
2571 	}
2572 	if (valid & IPSL_IPV6) {
2573 		if (selkey->ipsl_remote_pfxlen == 128)
2574 			return (IPSEC_IPV6_HASH(selkey->ipsl_remote.ipsad_v6));
2575 	}
2576 	return (IPSEC_SEL_NOHASH);
2577 }
2578 
2579 static uint32_t
2580 selector_hash(ipsec_selector_t *sel)
2581 {
2582 	if (sel->ips_isv4) {
2583 		return (IPSEC_IPV4_HASH(sel->ips_remote_addr_v4));
2584 	}
2585 	return (IPSEC_IPV6_HASH(sel->ips_remote_addr_v6));
2586 }
2587 
2588 /*
2589  * Intern actions into the action hash table.
2590  */
2591 ipsec_action_t *
2592 ipsec_act_find(const ipsec_act_t *a, int n)
2593 {
2594 	int i;
2595 	uint32_t hval;
2596 	ipsec_action_t *ap;
2597 	ipsec_action_t *prev = NULL;
2598 	int32_t overhead, maxovhd = 0;
2599 	boolean_t allow_clear = B_FALSE;
2600 	boolean_t want_ah = B_FALSE;
2601 	boolean_t want_esp = B_FALSE;
2602 	boolean_t want_se = B_FALSE;
2603 	boolean_t want_unique = B_FALSE;
2604 
2605 	/*
2606 	 * TODO: should canonicalize a[] (i.e., zeroize any padding)
2607 	 * so we can use a non-trivial policy_hash function.
2608 	 */
2609 	for (i = n-1; i >= 0; i--) {
2610 		hval = policy_hash(IPSEC_ACTION_HASH_SIZE, &a[i], &a[n]);
2611 
2612 		HASH_LOCK(ipsec_action_hash, hval);
2613 
2614 		for (HASH_ITERATE(ap, ipa_hash, ipsec_action_hash, hval)) {
2615 			if (bcmp(&ap->ipa_act, &a[i], sizeof (*a)) != 0)
2616 				continue;
2617 			if (ap->ipa_next != prev)
2618 				continue;
2619 			break;
2620 		}
2621 		if (ap != NULL) {
2622 			HASH_UNLOCK(ipsec_action_hash, hval);
2623 			prev = ap;
2624 			continue;
2625 		}
2626 		/*
2627 		 * need to allocate a new one..
2628 		 */
2629 		ap = kmem_cache_alloc(ipsec_action_cache, KM_NOSLEEP);
2630 		if (ap == NULL) {
2631 			HASH_UNLOCK(ipsec_action_hash, hval);
2632 			if (prev != NULL)
2633 				ipsec_action_free(prev);
2634 			return (NULL);
2635 		}
2636 		HASH_INSERT(ap, ipa_hash, ipsec_action_hash, hval);
2637 
2638 		ap->ipa_next = prev;
2639 		ap->ipa_act = a[i];
2640 
2641 		overhead = ipsec_act_ovhd(&a[i]);
2642 		if (maxovhd < overhead)
2643 			maxovhd = overhead;
2644 
2645 		if ((a[i].ipa_type == IPSEC_ACT_BYPASS) ||
2646 		    (a[i].ipa_type == IPSEC_ACT_CLEAR))
2647 			allow_clear = B_TRUE;
2648 		if (a[i].ipa_type == IPSEC_ACT_APPLY) {
2649 			const ipsec_prot_t *ipp = &a[i].ipa_apply;
2650 
2651 			ASSERT(ipp->ipp_use_ah || ipp->ipp_use_esp);
2652 			want_ah |= ipp->ipp_use_ah;
2653 			want_esp |= ipp->ipp_use_esp;
2654 			want_se |= ipp->ipp_use_se;
2655 			want_unique |= ipp->ipp_use_unique;
2656 		}
2657 		ap->ipa_allow_clear = allow_clear;
2658 		ap->ipa_want_ah = want_ah;
2659 		ap->ipa_want_esp = want_esp;
2660 		ap->ipa_want_se = want_se;
2661 		ap->ipa_want_unique = want_unique;
2662 		ap->ipa_refs = 1; /* from the hash table */
2663 		ap->ipa_ovhd = maxovhd;
2664 		if (prev)
2665 			prev->ipa_refs++;
2666 		prev = ap;
2667 		HASH_UNLOCK(ipsec_action_hash, hval);
2668 	}
2669 
2670 	ap->ipa_refs++;		/* caller's reference */
2671 
2672 	return (ap);
2673 }
2674 
2675 /*
2676  * Called when refcount goes to 0, indicating that all references to this
2677  * node are gone.
2678  *
2679  * This does not unchain the action from the hash table.
2680  */
2681 void
2682 ipsec_action_free(ipsec_action_t *ap)
2683 {
2684 	for (;;) {
2685 		ipsec_action_t *np = ap->ipa_next;
2686 		ASSERT(ap->ipa_refs == 0);
2687 		ASSERT(ap->ipa_hash.hash_pp == NULL);
2688 		kmem_cache_free(ipsec_action_cache, ap);
2689 		ap = np;
2690 		/* Inlined IPACT_REFRELE -- avoid recursion */
2691 		if (ap == NULL)
2692 			break;
2693 		membar_exit();
2694 		if (atomic_add_32_nv(&(ap)->ipa_refs, -1) != 0)
2695 			break;
2696 		/* End inlined IPACT_REFRELE */
2697 	}
2698 }
2699 
2700 /*
2701  * Periodically sweep action hash table for actions with refcount==1, and
2702  * nuke them.  We cannot do this "on demand" (i.e., from IPACT_REFRELE)
2703  * because we can't close the race between another thread finding the action
2704  * in the hash table without holding the bucket lock during IPACT_REFRELE.
2705  * Instead, we run this function sporadically to clean up after ourselves;
2706  * we also set it as the "reclaim" function for the action kmem_cache.
2707  *
2708  * Note that it may take several passes of ipsec_action_gc() to free all
2709  * "stale" actions.
2710  */
2711 /* ARGSUSED */
2712 static void
2713 ipsec_action_reclaim(void *dummy)
2714 {
2715 	int i;
2716 
2717 	for (i = 0; i < IPSEC_ACTION_HASH_SIZE; i++) {
2718 		ipsec_action_t *ap, *np;
2719 
2720 		/* skip the lock if nobody home */
2721 		if (ipsec_action_hash[i].hash_head == NULL)
2722 			continue;
2723 
2724 		HASH_LOCK(ipsec_action_hash, i);
2725 		for (ap = ipsec_action_hash[i].hash_head;
2726 		    ap != NULL; ap = np) {
2727 			ASSERT(ap->ipa_refs > 0);
2728 			np = ap->ipa_hash.hash_next;
2729 			if (ap->ipa_refs > 1)
2730 				continue;
2731 			HASH_UNCHAIN(ap, ipa_hash, ipsec_action_hash, i);
2732 			IPACT_REFRELE(ap);
2733 		}
2734 		HASH_UNLOCK(ipsec_action_hash, i);
2735 	}
2736 }
2737 
2738 /*
2739  * Intern a selector set into the selector set hash table.
2740  * This is simpler than the actions case..
2741  */
2742 static ipsec_sel_t *
2743 ipsec_find_sel(ipsec_selkey_t *selkey)
2744 {
2745 	ipsec_sel_t *sp;
2746 	uint32_t hval, bucket;
2747 
2748 	/*
2749 	 * Exactly one AF bit should be set in selkey.
2750 	 */
2751 	ASSERT(!(selkey->ipsl_valid & IPSL_IPV4) ^
2752 	    !(selkey->ipsl_valid & IPSL_IPV6));
2753 
2754 	hval = selkey_hash(selkey);
2755 	selkey->ipsl_hval = hval;
2756 
2757 	bucket = (hval == IPSEC_SEL_NOHASH) ? 0 : hval;
2758 
2759 	ASSERT(!HASH_LOCKED(ipsec_sel_hash, bucket));
2760 	HASH_LOCK(ipsec_sel_hash, bucket);
2761 
2762 	for (HASH_ITERATE(sp, ipsl_hash, ipsec_sel_hash, bucket)) {
2763 		if (bcmp(&sp->ipsl_key, selkey, sizeof (*selkey)) == 0)
2764 			break;
2765 	}
2766 	if (sp != NULL) {
2767 		sp->ipsl_refs++;
2768 
2769 		HASH_UNLOCK(ipsec_sel_hash, bucket);
2770 		return (sp);
2771 	}
2772 
2773 	sp = kmem_cache_alloc(ipsec_sel_cache, KM_NOSLEEP);
2774 	if (sp == NULL) {
2775 		HASH_UNLOCK(ipsec_sel_hash, bucket);
2776 		return (NULL);
2777 	}
2778 
2779 	HASH_INSERT(sp, ipsl_hash, ipsec_sel_hash, bucket);
2780 	sp->ipsl_refs = 2;	/* one for hash table, one for caller */
2781 	sp->ipsl_key = *selkey;
2782 
2783 	HASH_UNLOCK(ipsec_sel_hash, bucket);
2784 
2785 	return (sp);
2786 }
2787 
2788 static void
2789 ipsec_sel_rel(ipsec_sel_t **spp)
2790 {
2791 	ipsec_sel_t *sp = *spp;
2792 	int hval = sp->ipsl_key.ipsl_hval;
2793 	*spp = NULL;
2794 
2795 	if (hval == IPSEC_SEL_NOHASH)
2796 		hval = 0;
2797 
2798 	ASSERT(!HASH_LOCKED(ipsec_sel_hash, hval));
2799 	HASH_LOCK(ipsec_sel_hash, hval);
2800 	if (--sp->ipsl_refs == 1) {
2801 		HASH_UNCHAIN(sp, ipsl_hash, ipsec_sel_hash, hval);
2802 		sp->ipsl_refs--;
2803 		HASH_UNLOCK(ipsec_sel_hash, hval);
2804 		ASSERT(sp->ipsl_refs == 0);
2805 		kmem_cache_free(ipsec_sel_cache, sp);
2806 		/* Caller unlocks */
2807 		return;
2808 	}
2809 
2810 	HASH_UNLOCK(ipsec_sel_hash, hval);
2811 }
2812 
2813 /*
2814  * Free a policy rule which we know is no longer being referenced.
2815  */
2816 void
2817 ipsec_policy_free(ipsec_policy_t *ipp)
2818 {
2819 	ASSERT(ipp->ipsp_refs == 0);
2820 	ASSERT(ipp->ipsp_sel != NULL);
2821 	ASSERT(ipp->ipsp_act != NULL);
2822 	ipsec_sel_rel(&ipp->ipsp_sel);
2823 	IPACT_REFRELE(ipp->ipsp_act);
2824 	kmem_cache_free(ipsec_pol_cache, ipp);
2825 }
2826 
2827 /*
2828  * Construction of new policy rules; construct a policy, and add it to
2829  * the appropriate tables.
2830  */
2831 ipsec_policy_t *
2832 ipsec_policy_create(ipsec_selkey_t *keys, const ipsec_act_t *a,
2833     int nacts, int prio)
2834 {
2835 	ipsec_action_t *ap;
2836 	ipsec_sel_t *sp;
2837 	ipsec_policy_t *ipp;
2838 
2839 	ipp = kmem_cache_alloc(ipsec_pol_cache, KM_NOSLEEP);
2840 	ap = ipsec_act_find(a, nacts);
2841 	sp = ipsec_find_sel(keys);
2842 
2843 	if ((ap == NULL) || (sp == NULL) || (ipp == NULL)) {
2844 		if (ap != NULL) {
2845 			IPACT_REFRELE(ap);
2846 		}
2847 		if (sp != NULL)
2848 			ipsec_sel_rel(&sp);
2849 		if (ipp != NULL)
2850 			kmem_cache_free(ipsec_pol_cache, ipp);
2851 		return (NULL);
2852 	}
2853 
2854 	HASH_NULL(ipp, ipsp_hash);
2855 
2856 	ipp->ipsp_refs = 1;	/* caller's reference */
2857 	ipp->ipsp_sel = sp;
2858 	ipp->ipsp_act = ap;
2859 	ipp->ipsp_prio = prio;	/* rule priority */
2860 	ipp->ipsp_index = ipsec_next_policy_index++;
2861 
2862 	return (ipp);
2863 }
2864 
2865 static void
2866 ipsec_update_present_flags()
2867 {
2868 	boolean_t hashpol = (avl_numnodes(&system_policy.iph_rulebyid) > 0);
2869 
2870 	if (hashpol) {
2871 		ipsec_outbound_v4_policy_present = B_TRUE;
2872 		ipsec_outbound_v6_policy_present = B_TRUE;
2873 		ipsec_inbound_v4_policy_present = B_TRUE;
2874 		ipsec_inbound_v6_policy_present = B_TRUE;
2875 		return;
2876 	}
2877 
2878 	ipsec_outbound_v4_policy_present = (NULL !=
2879 	    system_policy.iph_root[IPSEC_TYPE_OUTBOUND].
2880 	    ipr_nonhash[IPSEC_AF_V4]);
2881 	ipsec_outbound_v6_policy_present = (NULL !=
2882 	    system_policy.iph_root[IPSEC_TYPE_OUTBOUND].
2883 	    ipr_nonhash[IPSEC_AF_V6]);
2884 	ipsec_inbound_v4_policy_present = (NULL !=
2885 	    system_policy.iph_root[IPSEC_TYPE_INBOUND].
2886 	    ipr_nonhash[IPSEC_AF_V4]);
2887 	ipsec_inbound_v6_policy_present = (NULL !=
2888 	    system_policy.iph_root[IPSEC_TYPE_INBOUND].
2889 	    ipr_nonhash[IPSEC_AF_V6]);
2890 }
2891 
2892 boolean_t
2893 ipsec_policy_delete(ipsec_policy_head_t *php, ipsec_selkey_t *keys, int dir)
2894 {
2895 	ipsec_sel_t *sp;
2896 	ipsec_policy_t *ip, *nip, *head;
2897 	int af;
2898 	ipsec_policy_root_t *pr = &php->iph_root[dir];
2899 
2900 	sp = ipsec_find_sel(keys);
2901 
2902 	if (sp == NULL)
2903 		return (B_FALSE);
2904 
2905 	af = (sp->ipsl_key.ipsl_valid & IPSL_IPV4) ? IPSEC_AF_V4 : IPSEC_AF_V6;
2906 
2907 	rw_enter(&php->iph_lock, RW_WRITER);
2908 
2909 	if (keys->ipsl_hval == IPSEC_SEL_NOHASH) {
2910 		head = pr->ipr_nonhash[af];
2911 	} else {
2912 		head = pr->ipr_hash[keys->ipsl_hval].hash_head;
2913 	}
2914 
2915 	for (ip = head; ip != NULL; ip = nip) {
2916 		nip = ip->ipsp_hash.hash_next;
2917 		if (ip->ipsp_sel != sp) {
2918 			continue;
2919 		}
2920 
2921 		IPPOL_UNCHAIN(php, ip);
2922 
2923 		php->iph_gen++;
2924 		ipsec_update_present_flags();
2925 
2926 		rw_exit(&php->iph_lock);
2927 
2928 		ipsec_sel_rel(&sp);
2929 
2930 		return (B_TRUE);
2931 	}
2932 
2933 	rw_exit(&php->iph_lock);
2934 	ipsec_sel_rel(&sp);
2935 	return (B_FALSE);
2936 }
2937 
2938 int
2939 ipsec_policy_delete_index(ipsec_policy_head_t *php, uint64_t policy_index)
2940 {
2941 	boolean_t found = B_FALSE;
2942 	ipsec_policy_t ipkey;
2943 	ipsec_policy_t *ip;
2944 	avl_index_t where;
2945 
2946 	(void) memset(&ipkey, 0, sizeof (ipkey));
2947 	ipkey.ipsp_index = policy_index;
2948 
2949 	rw_enter(&php->iph_lock, RW_WRITER);
2950 
2951 	/*
2952 	 * We could be cleverer here about the walk.
2953 	 * but well, (k+1)*log(N) will do for now (k==number of matches,
2954 	 * N==number of table entries
2955 	 */
2956 	for (;;) {
2957 		ip = (ipsec_policy_t *)avl_find(&php->iph_rulebyid,
2958 		    (void *)&ipkey, &where);
2959 		ASSERT(ip == NULL);
2960 
2961 		ip = avl_nearest(&php->iph_rulebyid, where, AVL_AFTER);
2962 
2963 		if (ip == NULL)
2964 			break;
2965 
2966 		if (ip->ipsp_index != policy_index) {
2967 			ASSERT(ip->ipsp_index > policy_index);
2968 			break;
2969 		}
2970 
2971 		IPPOL_UNCHAIN(php, ip);
2972 		found = B_TRUE;
2973 	}
2974 
2975 	if (found) {
2976 		php->iph_gen++;
2977 		ipsec_update_present_flags();
2978 	}
2979 
2980 	rw_exit(&php->iph_lock);
2981 
2982 	return (found ? 0 : ENOENT);
2983 }
2984 
2985 /*
2986  * Given a constructed ipsec_policy_t policy rule, see if it can be entered
2987  * into the correct policy ruleset.
2988  *
2989  * Returns B_TRUE if it can be entered, B_FALSE if it can't be (because a
2990  * duplicate policy exists with exactly the same selectors), or an icmp
2991  * rule exists with a different encryption/authentication action.
2992  */
2993 boolean_t
2994 ipsec_check_policy(ipsec_policy_head_t *php, ipsec_policy_t *ipp, int direction)
2995 {
2996 	ipsec_policy_root_t *pr = &php->iph_root[direction];
2997 	int af = -1;
2998 	ipsec_policy_t *p2, *head;
2999 	uint8_t check_proto;
3000 	ipsec_selkey_t *selkey = &ipp->ipsp_sel->ipsl_key;
3001 	uint32_t	valid = selkey->ipsl_valid;
3002 
3003 	if (valid & IPSL_IPV6) {
3004 		ASSERT(!(valid & IPSL_IPV4));
3005 		af = IPSEC_AF_V6;
3006 		check_proto = IPPROTO_ICMPV6;
3007 	} else {
3008 		ASSERT(valid & IPSL_IPV4);
3009 		af = IPSEC_AF_V4;
3010 		check_proto = IPPROTO_ICMP;
3011 	}
3012 
3013 	ASSERT(RW_WRITE_HELD(&php->iph_lock));
3014 
3015 	/*
3016 	 * Double-check that we don't have any duplicate selectors here.
3017 	 * Because selectors are interned below, we need only compare pointers
3018 	 * for equality.
3019 	 */
3020 	if (selkey->ipsl_hval == IPSEC_SEL_NOHASH) {
3021 		head = pr->ipr_nonhash[af];
3022 	} else {
3023 		head = pr->ipr_hash[selkey->ipsl_hval].hash_head;
3024 	}
3025 
3026 	for (p2 = head; p2 != NULL; p2 = p2->ipsp_hash.hash_next) {
3027 		if (p2->ipsp_sel == ipp->ipsp_sel)
3028 			return (B_FALSE);
3029 	}
3030 
3031 	/*
3032 	 * If it's ICMP and not a drop or pass rule, run through the ICMP
3033 	 * rules and make sure the action is either new or the same as any
3034 	 * other actions.  We don't have to check the full chain because
3035 	 * discard and bypass will override all other actions
3036 	 */
3037 
3038 	if (valid & IPSL_PROTOCOL &&
3039 	    selkey->ipsl_proto == check_proto &&
3040 	    (ipp->ipsp_act->ipa_act.ipa_type == IPSEC_ACT_APPLY)) {
3041 
3042 		for (p2 = head; p2 != NULL; p2 = p2->ipsp_hash.hash_next) {
3043 
3044 			if (p2->ipsp_sel->ipsl_key.ipsl_valid & IPSL_PROTOCOL &&
3045 			    p2->ipsp_sel->ipsl_key.ipsl_proto == check_proto &&
3046 			    (p2->ipsp_act->ipa_act.ipa_type ==
3047 				IPSEC_ACT_APPLY)) {
3048 				return (ipsec_compare_action(p2, ipp));
3049 			}
3050 		}
3051 	}
3052 
3053 	return (B_TRUE);
3054 }
3055 
3056 /*
3057  * compare the action chains of two policies for equality
3058  * B_TRUE -> effective equality
3059  */
3060 
3061 static boolean_t
3062 ipsec_compare_action(ipsec_policy_t *p1, ipsec_policy_t *p2)
3063 {
3064 
3065 	ipsec_action_t *act1, *act2;
3066 
3067 	/* We have a valid rule. Let's compare the actions */
3068 	if (p1->ipsp_act == p2->ipsp_act) {
3069 		/* same action. We are good */
3070 		return (B_TRUE);
3071 	}
3072 
3073 	/* we have to walk the chain */
3074 
3075 	act1 = p1->ipsp_act;
3076 	act2 = p2->ipsp_act;
3077 
3078 	while (act1 != NULL && act2 != NULL) {
3079 
3080 		/* otherwise, Are we close enough? */
3081 		if (act1->ipa_allow_clear != act2->ipa_allow_clear ||
3082 		    act1->ipa_want_ah != act2->ipa_want_ah ||
3083 		    act1->ipa_want_esp != act2->ipa_want_esp ||
3084 		    act1->ipa_want_se != act2->ipa_want_se) {
3085 			/* Nope, we aren't */
3086 			return (B_FALSE);
3087 		}
3088 
3089 		if (act1->ipa_want_ah) {
3090 			if (act1->ipa_act.ipa_apply.ipp_auth_alg !=
3091 			    act2->ipa_act.ipa_apply.ipp_auth_alg) {
3092 				return (B_FALSE);
3093 			}
3094 
3095 			if (act1->ipa_act.ipa_apply.ipp_ah_minbits !=
3096 			    act2->ipa_act.ipa_apply.ipp_ah_minbits ||
3097 			    act1->ipa_act.ipa_apply.ipp_ah_maxbits !=
3098 			    act2->ipa_act.ipa_apply.ipp_ah_maxbits) {
3099 				return (B_FALSE);
3100 			}
3101 		}
3102 
3103 		if (act1->ipa_want_esp) {
3104 			if (act1->ipa_act.ipa_apply.ipp_use_esp !=
3105 			    act2->ipa_act.ipa_apply.ipp_use_esp ||
3106 			    act1->ipa_act.ipa_apply.ipp_use_espa !=
3107 			    act2->ipa_act.ipa_apply.ipp_use_espa) {
3108 				return (B_FALSE);
3109 			}
3110 
3111 			if (act1->ipa_act.ipa_apply.ipp_use_esp) {
3112 				if (act1->ipa_act.ipa_apply.ipp_encr_alg !=
3113 				    act2->ipa_act.ipa_apply.ipp_encr_alg) {
3114 					return (B_FALSE);
3115 				}
3116 
3117 				if (act1->ipa_act.ipa_apply.ipp_espe_minbits !=
3118 				    act2->ipa_act.ipa_apply.ipp_espe_minbits ||
3119 				    act1->ipa_act.ipa_apply.ipp_espe_maxbits !=
3120 				    act2->ipa_act.ipa_apply.ipp_espe_maxbits) {
3121 					return (B_FALSE);
3122 				}
3123 			}
3124 
3125 			if (act1->ipa_act.ipa_apply.ipp_use_espa) {
3126 				if (act1->ipa_act.ipa_apply.ipp_esp_auth_alg !=
3127 				    act2->ipa_act.ipa_apply.ipp_esp_auth_alg) {
3128 					return (B_FALSE);
3129 				}
3130 
3131 				if (act1->ipa_act.ipa_apply.ipp_espa_minbits !=
3132 				    act2->ipa_act.ipa_apply.ipp_espa_minbits ||
3133 				    act1->ipa_act.ipa_apply.ipp_espa_maxbits !=
3134 				    act2->ipa_act.ipa_apply.ipp_espa_maxbits) {
3135 					return (B_FALSE);
3136 				}
3137 			}
3138 
3139 		}
3140 
3141 		act1 = act1->ipa_next;
3142 		act2 = act2->ipa_next;
3143 	}
3144 
3145 	if (act1 != NULL || act2 != NULL) {
3146 		return (B_FALSE);
3147 	}
3148 
3149 	return (B_TRUE);
3150 }
3151 
3152 
3153 /*
3154  * Given a constructed ipsec_policy_t policy rule, enter it into
3155  * the correct policy ruleset.
3156  *
3157  * ipsec_check_policy() is assumed to have succeeded first (to check for
3158  * duplicates).
3159  */
3160 void
3161 ipsec_enter_policy(ipsec_policy_head_t *php, ipsec_policy_t *ipp, int direction)
3162 {
3163 	ipsec_policy_root_t *pr = &php->iph_root[direction];
3164 	ipsec_selkey_t *selkey = &ipp->ipsp_sel->ipsl_key;
3165 	uint32_t valid = selkey->ipsl_valid;
3166 	uint32_t hval = selkey->ipsl_hval;
3167 	int af = -1;
3168 
3169 	ASSERT(RW_WRITE_HELD(&php->iph_lock));
3170 
3171 	if (valid & IPSL_IPV6) {
3172 		ASSERT(!(valid & IPSL_IPV4));
3173 		af = IPSEC_AF_V6;
3174 	} else {
3175 		ASSERT(valid & IPSL_IPV4);
3176 		af = IPSEC_AF_V4;
3177 	}
3178 
3179 	php->iph_gen++;
3180 
3181 	if (hval == IPSEC_SEL_NOHASH) {
3182 		HASHLIST_INSERT(ipp, ipsp_hash, pr->ipr_nonhash[af]);
3183 	} else {
3184 		HASH_LOCK(pr->ipr_hash, hval);
3185 		HASH_INSERT(ipp, ipsp_hash, pr->ipr_hash, hval);
3186 		HASH_UNLOCK(pr->ipr_hash, hval);
3187 	}
3188 
3189 	ipsec_insert_always(&php->iph_rulebyid, ipp);
3190 
3191 	ipsec_update_present_flags();
3192 }
3193 
3194 static void
3195 ipsec_ipr_flush(ipsec_policy_head_t *php, ipsec_policy_root_t *ipr)
3196 {
3197 	ipsec_policy_t *ip, *nip;
3198 
3199 	int af, chain, nchain;
3200 
3201 	for (af = 0; af < IPSEC_NAF; af++) {
3202 		for (ip = ipr->ipr_nonhash[af]; ip != NULL; ip = nip) {
3203 			nip = ip->ipsp_hash.hash_next;
3204 			IPPOL_UNCHAIN(php, ip);
3205 		}
3206 		ipr->ipr_nonhash[af] = NULL;
3207 	}
3208 	nchain = ipr->ipr_nchains;
3209 
3210 	for (chain = 0; chain < nchain; chain++) {
3211 		for (ip = ipr->ipr_hash[chain].hash_head; ip != NULL;
3212 		    ip = nip) {
3213 			nip = ip->ipsp_hash.hash_next;
3214 			IPPOL_UNCHAIN(php, ip);
3215 		}
3216 		ipr->ipr_hash[chain].hash_head = NULL;
3217 	}
3218 }
3219 
3220 
3221 void
3222 ipsec_polhead_flush(ipsec_policy_head_t *php)
3223 {
3224 	int dir;
3225 
3226 	ASSERT(RW_WRITE_HELD(&php->iph_lock));
3227 
3228 	for (dir = 0; dir < IPSEC_NTYPES; dir++)
3229 		ipsec_ipr_flush(php, &php->iph_root[dir]);
3230 
3231 	ipsec_update_present_flags();
3232 }
3233 
3234 void
3235 ipsec_polhead_free(ipsec_policy_head_t *php)
3236 {
3237 	ASSERT(php->iph_refs == 0);
3238 	rw_enter(&php->iph_lock, RW_WRITER);
3239 	ipsec_polhead_flush(php);
3240 	rw_exit(&php->iph_lock);
3241 	rw_destroy(&php->iph_lock);
3242 	kmem_free(php, sizeof (*php));
3243 }
3244 
3245 static void
3246 ipsec_ipr_init(ipsec_policy_root_t *ipr)
3247 {
3248 	int af;
3249 
3250 	ipr->ipr_nchains = 0;
3251 	ipr->ipr_hash = NULL;
3252 
3253 	for (af = 0; af < IPSEC_NAF; af++) {
3254 		ipr->ipr_nonhash[af] = NULL;
3255 	}
3256 }
3257 
3258 extern ipsec_policy_head_t *
3259 ipsec_polhead_create(void)
3260 {
3261 	ipsec_policy_head_t *php;
3262 
3263 	php = kmem_alloc(sizeof (*php), KM_NOSLEEP);
3264 	if (php == NULL)
3265 		return (php);
3266 
3267 	rw_init(&php->iph_lock, NULL, RW_DEFAULT, NULL);
3268 	php->iph_refs = 1;
3269 	php->iph_gen = 0;
3270 
3271 	ipsec_ipr_init(&php->iph_root[IPSEC_TYPE_INBOUND]);
3272 	ipsec_ipr_init(&php->iph_root[IPSEC_TYPE_OUTBOUND]);
3273 
3274 	avl_create(&php->iph_rulebyid, ipsec_policy_cmpbyid,
3275 	    sizeof (ipsec_policy_t), offsetof(ipsec_policy_t, ipsp_byid));
3276 
3277 	return (php);
3278 }
3279 
3280 /*
3281  * Clone the policy head into a new polhead; release one reference to the
3282  * old one and return the only reference to the new one.
3283  * If the old one had a refcount of 1, just return it.
3284  */
3285 extern ipsec_policy_head_t *
3286 ipsec_polhead_split(ipsec_policy_head_t *php)
3287 {
3288 	ipsec_policy_head_t *nphp;
3289 
3290 	if (php == NULL)
3291 		return (ipsec_polhead_create());
3292 	else if (php->iph_refs == 1)
3293 		return (php);
3294 
3295 	nphp = ipsec_polhead_create();
3296 	if (nphp == NULL)
3297 		return (NULL);
3298 
3299 	if (ipsec_copy_polhead(php, nphp) != 0) {
3300 		ipsec_polhead_free(nphp);
3301 		return (NULL);
3302 	}
3303 	IPPH_REFRELE(php);
3304 	return (nphp);
3305 }
3306 
3307 /*
3308  * When sending a response to a ICMP request or generating a RST
3309  * in the TCP case, the outbound packets need to go at the same level
3310  * of protection as the incoming ones i.e we associate our outbound
3311  * policy with how the packet came in. We call this after we have
3312  * accepted the incoming packet which may or may not have been in
3313  * clear and hence we are sending the reply back with the policy
3314  * matching the incoming datagram's policy.
3315  *
3316  * NOTE : This technology serves two purposes :
3317  *
3318  * 1) If we have multiple outbound policies, we send out a reply
3319  *    matching with how it came in rather than matching the outbound
3320  *    policy.
3321  *
3322  * 2) For assymetric policies, we want to make sure that incoming
3323  *    and outgoing has the same level of protection. Assymetric
3324  *    policies exist only with global policy where we may not have
3325  *    both outbound and inbound at the same time.
3326  *
3327  * NOTE2:	This function is called by cleartext cases, so it needs to be
3328  *		in IP proper.
3329  */
3330 boolean_t
3331 ipsec_in_to_out(mblk_t *ipsec_mp, ipha_t *ipha, ip6_t *ip6h)
3332 {
3333 	ipsec_in_t  *ii;
3334 	ipsec_out_t  *io;
3335 	boolean_t v4;
3336 	mblk_t *mp;
3337 	boolean_t secure, attach_if;
3338 	uint_t ifindex;
3339 	ipsec_selector_t sel;
3340 	ipsec_action_t *reflect_action = NULL;
3341 	zoneid_t zoneid;
3342 
3343 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL);
3344 
3345 	bzero((void*)&sel, sizeof (sel));
3346 
3347 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
3348 
3349 	mp = ipsec_mp->b_cont;
3350 	ASSERT(mp != NULL);
3351 
3352 	if (ii->ipsec_in_action != NULL) {
3353 		/* transfer reference.. */
3354 		reflect_action = ii->ipsec_in_action;
3355 		ii->ipsec_in_action = NULL;
3356 	} else if (!ii->ipsec_in_loopback)
3357 		reflect_action = ipsec_in_to_out_action(ii);
3358 	secure = ii->ipsec_in_secure;
3359 	attach_if = ii->ipsec_in_attach_if;
3360 	ifindex = ii->ipsec_in_ill_index;
3361 	zoneid = ii->ipsec_in_zoneid;
3362 	v4 = ii->ipsec_in_v4;
3363 
3364 	ipsec_in_release_refs(ii);
3365 
3366 	/*
3367 	 * The caller is going to send the datagram out which might
3368 	 * go on the wire or delivered locally through ip_wput_local.
3369 	 *
3370 	 * 1) If it goes out on the wire, new associations will be
3371 	 *    obtained.
3372 	 * 2) If it is delivered locally, ip_wput_local will convert
3373 	 *    this IPSEC_OUT to a IPSEC_IN looking at the requests.
3374 	 */
3375 
3376 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
3377 	bzero(io, sizeof (ipsec_out_t));
3378 	io->ipsec_out_type = IPSEC_OUT;
3379 	io->ipsec_out_len = sizeof (ipsec_out_t);
3380 	io->ipsec_out_frtn.free_func = ipsec_out_free;
3381 	io->ipsec_out_frtn.free_arg = (char *)io;
3382 	io->ipsec_out_act = reflect_action;
3383 
3384 	if (!ipsec_init_outbound_ports(&sel, mp, ipha, ip6h))
3385 		return (B_FALSE);
3386 
3387 	io->ipsec_out_src_port = sel.ips_local_port;
3388 	io->ipsec_out_dst_port = sel.ips_remote_port;
3389 	io->ipsec_out_proto = sel.ips_protocol;
3390 	io->ipsec_out_icmp_type = sel.ips_icmp_type;
3391 	io->ipsec_out_icmp_code = sel.ips_icmp_code;
3392 
3393 	/*
3394 	 * Don't use global policy for this, as we want
3395 	 * to use the same protection that was applied to the inbound packet.
3396 	 */
3397 	io->ipsec_out_use_global_policy = B_FALSE;
3398 	io->ipsec_out_proc_begin = B_FALSE;
3399 	io->ipsec_out_secure = secure;
3400 	io->ipsec_out_v4 = v4;
3401 	io->ipsec_out_attach_if = attach_if;
3402 	io->ipsec_out_ill_index = ifindex;
3403 	io->ipsec_out_zoneid = zoneid;
3404 	return (B_TRUE);
3405 }
3406 
3407 mblk_t *
3408 ipsec_in_tag(mblk_t *mp, mblk_t *cont)
3409 {
3410 	ipsec_in_t *ii = (ipsec_in_t *)mp->b_rptr;
3411 	ipsec_in_t *nii;
3412 	mblk_t *nmp;
3413 	frtn_t nfrtn;
3414 
3415 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
3416 	ASSERT(ii->ipsec_in_len == sizeof (ipsec_in_t));
3417 
3418 	nmp = ipsec_in_alloc(ii->ipsec_in_v4);
3419 
3420 	ASSERT(nmp->b_datap->db_type == M_CTL);
3421 	ASSERT(nmp->b_wptr == (nmp->b_rptr + sizeof (ipsec_info_t)));
3422 
3423 	/*
3424 	 * Bump refcounts.
3425 	 */
3426 	if (ii->ipsec_in_ah_sa != NULL)
3427 		IPSA_REFHOLD(ii->ipsec_in_ah_sa);
3428 	if (ii->ipsec_in_esp_sa != NULL)
3429 		IPSA_REFHOLD(ii->ipsec_in_esp_sa);
3430 	if (ii->ipsec_in_policy != NULL)
3431 		IPPH_REFHOLD(ii->ipsec_in_policy);
3432 
3433 	/*
3434 	 * Copy everything, but preserve the free routine provided by
3435 	 * ipsec_in_alloc().
3436 	 */
3437 	nii = (ipsec_in_t *)nmp->b_rptr;
3438 	nfrtn = nii->ipsec_in_frtn;
3439 	bcopy(ii, nii, sizeof (*ii));
3440 	nii->ipsec_in_frtn = nfrtn;
3441 
3442 	nmp->b_cont = cont;
3443 
3444 	return (nmp);
3445 }
3446 
3447 mblk_t *
3448 ipsec_out_tag(mblk_t *mp, mblk_t *cont)
3449 {
3450 	ipsec_out_t *io = (ipsec_out_t *)mp->b_rptr;
3451 	ipsec_out_t *nio;
3452 	mblk_t *nmp;
3453 	frtn_t nfrtn;
3454 
3455 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
3456 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
3457 
3458 	nmp = ipsec_alloc_ipsec_out();
3459 	if (nmp == NULL) {
3460 		freemsg(cont);	/* XXX ip_drop_packet() ? */
3461 		return (NULL);
3462 	}
3463 	ASSERT(nmp->b_datap->db_type == M_CTL);
3464 	ASSERT(nmp->b_wptr == (nmp->b_rptr + sizeof (ipsec_info_t)));
3465 
3466 	/*
3467 	 * Bump refcounts.
3468 	 */
3469 	if (io->ipsec_out_ah_sa != NULL)
3470 		IPSA_REFHOLD(io->ipsec_out_ah_sa);
3471 	if (io->ipsec_out_esp_sa != NULL)
3472 		IPSA_REFHOLD(io->ipsec_out_esp_sa);
3473 	if (io->ipsec_out_polhead != NULL)
3474 		IPPH_REFHOLD(io->ipsec_out_polhead);
3475 	if (io->ipsec_out_policy != NULL)
3476 		IPPOL_REFHOLD(io->ipsec_out_policy);
3477 	if (io->ipsec_out_act != NULL)
3478 		IPACT_REFHOLD(io->ipsec_out_act);
3479 	if (io->ipsec_out_latch != NULL)
3480 		IPLATCH_REFHOLD(io->ipsec_out_latch);
3481 	if (io->ipsec_out_cred != NULL)
3482 		crhold(io->ipsec_out_cred);
3483 
3484 	/*
3485 	 * Copy everything, but preserve the free routine provided by
3486 	 * ipsec_alloc_ipsec_out().
3487 	 */
3488 	nio = (ipsec_out_t *)nmp->b_rptr;
3489 	nfrtn = nio->ipsec_out_frtn;
3490 	bcopy(io, nio, sizeof (*io));
3491 	nio->ipsec_out_frtn = nfrtn;
3492 
3493 	nmp->b_cont = cont;
3494 
3495 	return (nmp);
3496 }
3497 
3498 static void
3499 ipsec_out_release_refs(ipsec_out_t *io)
3500 {
3501 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
3502 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
3503 
3504 	/* Note: IPSA_REFRELE is multi-line macro */
3505 	if (io->ipsec_out_ah_sa != NULL)
3506 		IPSA_REFRELE(io->ipsec_out_ah_sa);
3507 	if (io->ipsec_out_esp_sa != NULL)
3508 		IPSA_REFRELE(io->ipsec_out_esp_sa);
3509 	if (io->ipsec_out_polhead != NULL)
3510 		IPPH_REFRELE(io->ipsec_out_polhead);
3511 	if (io->ipsec_out_policy != NULL)
3512 		IPPOL_REFRELE(io->ipsec_out_policy);
3513 	if (io->ipsec_out_act != NULL)
3514 		IPACT_REFRELE(io->ipsec_out_act);
3515 	if (io->ipsec_out_cred != NULL) {
3516 		crfree(io->ipsec_out_cred);
3517 		io->ipsec_out_cred = NULL;
3518 	}
3519 	if (io->ipsec_out_latch) {
3520 		IPLATCH_REFRELE(io->ipsec_out_latch);
3521 		io->ipsec_out_latch = NULL;
3522 	}
3523 }
3524 
3525 static void
3526 ipsec_out_free(void *arg)
3527 {
3528 	ipsec_out_t *io = (ipsec_out_t *)arg;
3529 	ipsec_out_release_refs(io);
3530 	kmem_cache_free(ipsec_info_cache, arg);
3531 }
3532 
3533 static void
3534 ipsec_in_release_refs(ipsec_in_t *ii)
3535 {
3536 	/* Note: IPSA_REFRELE is multi-line macro */
3537 	if (ii->ipsec_in_ah_sa != NULL)
3538 		IPSA_REFRELE(ii->ipsec_in_ah_sa);
3539 	if (ii->ipsec_in_esp_sa != NULL)
3540 		IPSA_REFRELE(ii->ipsec_in_esp_sa);
3541 	if (ii->ipsec_in_policy != NULL)
3542 		IPPH_REFRELE(ii->ipsec_in_policy);
3543 	if (ii->ipsec_in_da != NULL) {
3544 		freeb(ii->ipsec_in_da);
3545 		ii->ipsec_in_da = NULL;
3546 	}
3547 }
3548 
3549 static void
3550 ipsec_in_free(void *arg)
3551 {
3552 	ipsec_in_t *ii = (ipsec_in_t *)arg;
3553 	ipsec_in_release_refs(ii);
3554 	kmem_cache_free(ipsec_info_cache, arg);
3555 }
3556 
3557 /*
3558  * This is called only for outbound datagrams if the datagram needs to
3559  * go out secure.  A NULL mp can be passed to get an ipsec_out. This
3560  * facility is used by ip_unbind.
3561  *
3562  * NOTE : o As the data part could be modified by ipsec_out_process etc.
3563  *	    we can't make it fast by calling a dup.
3564  */
3565 mblk_t *
3566 ipsec_alloc_ipsec_out()
3567 {
3568 	mblk_t *ipsec_mp;
3569 
3570 	ipsec_out_t *io = kmem_cache_alloc(ipsec_info_cache, KM_NOSLEEP);
3571 
3572 	if (io == NULL)
3573 		return (NULL);
3574 
3575 	bzero(io, sizeof (ipsec_out_t));
3576 
3577 	io->ipsec_out_type = IPSEC_OUT;
3578 	io->ipsec_out_len = sizeof (ipsec_out_t);
3579 	io->ipsec_out_frtn.free_func = ipsec_out_free;
3580 	io->ipsec_out_frtn.free_arg = (char *)io;
3581 
3582 	/*
3583 	 * Set the zoneid to ALL_ZONES which is used as an invalid value. Code
3584 	 * using ipsec_out_zoneid should assert that the zoneid has been set to
3585 	 * a sane value.
3586 	 */
3587 	io->ipsec_out_zoneid = ALL_ZONES;
3588 
3589 	ipsec_mp = desballoc((uint8_t *)io, sizeof (ipsec_info_t), BPRI_HI,
3590 	    &io->ipsec_out_frtn);
3591 	if (ipsec_mp == NULL) {
3592 		ipsec_out_free(io);
3593 
3594 		return (NULL);
3595 	}
3596 	ipsec_mp->b_datap->db_type = M_CTL;
3597 	ipsec_mp->b_wptr = ipsec_mp->b_rptr + sizeof (ipsec_info_t);
3598 
3599 	return (ipsec_mp);
3600 }
3601 
3602 /*
3603  * Attach an IPSEC_OUT; use pol for policy if it is non-null.
3604  * Otherwise initialize using conn.
3605  *
3606  * If pol is non-null, we consume a reference to it.
3607  */
3608 mblk_t *
3609 ipsec_attach_ipsec_out(mblk_t *mp, conn_t *connp, ipsec_policy_t *pol,
3610     uint8_t proto)
3611 {
3612 	mblk_t *ipsec_mp;
3613 
3614 	ASSERT((pol != NULL) || (connp != NULL));
3615 
3616 	ipsec_mp = ipsec_alloc_ipsec_out();
3617 	if (ipsec_mp == NULL) {
3618 		(void) mi_strlog(CONNP_TO_WQ(connp), 0, SL_ERROR|SL_NOTE,
3619 		    "ipsec_attach_ipsec_out: Allocation failure\n");
3620 		BUMP_MIB(&ip_mib, ipOutDiscards);
3621 		ip_drop_packet(mp, B_FALSE, NULL, NULL, &ipdrops_spd_nomem,
3622 		    &spd_dropper);
3623 		return (NULL);
3624 	}
3625 	ipsec_mp->b_cont = mp;
3626 	return (ipsec_init_ipsec_out(ipsec_mp, connp, pol, proto));
3627 }
3628 
3629 /*
3630  * Initialize the IPSEC_OUT (ipsec_mp) using pol if it is non-null.
3631  * Otherwise initialize using conn.
3632  *
3633  * If pol is non-null, we consume a reference to it.
3634  */
3635 mblk_t *
3636 ipsec_init_ipsec_out(mblk_t *ipsec_mp, conn_t *connp, ipsec_policy_t *pol,
3637     uint8_t proto)
3638 {
3639 	mblk_t *mp;
3640 	ipsec_out_t *io;
3641 	ipsec_policy_t *p;
3642 	ipha_t *ipha;
3643 	ip6_t *ip6h;
3644 
3645 	ASSERT((pol != NULL) || (connp != NULL));
3646 
3647 	/*
3648 	 * If mp is NULL, we won't/should not be using it.
3649 	 */
3650 	mp = ipsec_mp->b_cont;
3651 
3652 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL);
3653 	ASSERT(ipsec_mp->b_wptr == (ipsec_mp->b_rptr + sizeof (ipsec_info_t)));
3654 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
3655 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
3656 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
3657 	io->ipsec_out_latch = NULL;
3658 	/*
3659 	 * Set the zoneid when we have the connp.
3660 	 * Otherwise, we're called from ip_wput_attach_policy() who will take
3661 	 * care of setting the zoneid.
3662 	 */
3663 	if (connp != NULL)
3664 		io->ipsec_out_zoneid = connp->conn_zoneid;
3665 
3666 	if (mp != NULL) {
3667 		ipha = (ipha_t *)mp->b_rptr;
3668 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
3669 			io->ipsec_out_v4 = B_TRUE;
3670 			ip6h = NULL;
3671 		} else {
3672 			io->ipsec_out_v4 = B_FALSE;
3673 			ip6h = (ip6_t *)ipha;
3674 			ipha = NULL;
3675 		}
3676 	} else {
3677 		ASSERT(connp != NULL && connp->conn_policy_cached);
3678 		ip6h = NULL;
3679 		ipha = NULL;
3680 		io->ipsec_out_v4 = !connp->conn_pkt_isv6;
3681 	}
3682 
3683 	p = NULL;
3684 
3685 	/*
3686 	 * Take latched policies over global policy.  Check here again for
3687 	 * this, in case we had conn_latch set while the packet was flying
3688 	 * around in IP.
3689 	 */
3690 	if (connp != NULL && connp->conn_latch != NULL) {
3691 		p = connp->conn_latch->ipl_out_policy;
3692 		io->ipsec_out_latch = connp->conn_latch;
3693 		IPLATCH_REFHOLD(connp->conn_latch);
3694 		if (p != NULL) {
3695 			IPPOL_REFHOLD(p);
3696 		}
3697 		io->ipsec_out_src_port = connp->conn_lport;
3698 		io->ipsec_out_dst_port = connp->conn_fport;
3699 		io->ipsec_out_icmp_type = io->ipsec_out_icmp_code = 0;
3700 		if (pol != NULL)
3701 			IPPOL_REFRELE(pol);
3702 	} else if (pol != NULL) {
3703 		ipsec_selector_t sel;
3704 
3705 		bzero((void*)&sel, sizeof (sel));
3706 
3707 		p = pol;
3708 		/*
3709 		 * conn does not have the port information. Get
3710 		 * it from the packet.
3711 		 */
3712 
3713 		if (!ipsec_init_outbound_ports(&sel, mp, ipha, ip6h)) {
3714 			/* XXX any cleanup required here?? */
3715 			return (NULL);
3716 		}
3717 		io->ipsec_out_src_port = sel.ips_local_port;
3718 		io->ipsec_out_dst_port = sel.ips_remote_port;
3719 		io->ipsec_out_icmp_type = sel.ips_icmp_type;
3720 		io->ipsec_out_icmp_code = sel.ips_icmp_code;
3721 	}
3722 
3723 	io->ipsec_out_proto = proto;
3724 	io->ipsec_out_use_global_policy = B_TRUE;
3725 	io->ipsec_out_secure = (p != NULL);
3726 	io->ipsec_out_policy = p;
3727 
3728 	if (p == NULL) {
3729 		if (connp->conn_policy != NULL) {
3730 			io->ipsec_out_secure = B_TRUE;
3731 			ASSERT(io->ipsec_out_latch == NULL);
3732 			ASSERT(io->ipsec_out_use_global_policy == B_TRUE);
3733 			io->ipsec_out_need_policy = B_TRUE;
3734 			ASSERT(io->ipsec_out_polhead == NULL);
3735 			IPPH_REFHOLD(connp->conn_policy);
3736 			io->ipsec_out_polhead = connp->conn_policy;
3737 		}
3738 	}
3739 	return (ipsec_mp);
3740 }
3741 
3742 /*
3743  * Allocate an IPSEC_IN mblk.  This will be prepended to an inbound datagram
3744  * and keep track of what-if-any IPsec processing will be applied to the
3745  * datagram.
3746  */
3747 mblk_t *
3748 ipsec_in_alloc(boolean_t isv4)
3749 {
3750 	mblk_t *ipsec_in;
3751 	ipsec_in_t *ii = kmem_cache_alloc(ipsec_info_cache, KM_NOSLEEP);
3752 
3753 	if (ii == NULL)
3754 		return (NULL);
3755 
3756 	bzero(ii, sizeof (ipsec_info_t));
3757 	ii->ipsec_in_type = IPSEC_IN;
3758 	ii->ipsec_in_len = sizeof (ipsec_in_t);
3759 
3760 	ii->ipsec_in_v4 = isv4;
3761 	ii->ipsec_in_secure = B_TRUE;
3762 
3763 	ii->ipsec_in_frtn.free_func = ipsec_in_free;
3764 	ii->ipsec_in_frtn.free_arg = (char *)ii;
3765 
3766 	ipsec_in = desballoc((uint8_t *)ii, sizeof (ipsec_info_t), BPRI_HI,
3767 	    &ii->ipsec_in_frtn);
3768 	if (ipsec_in == NULL) {
3769 		ip1dbg(("ipsec_in_alloc: IPSEC_IN allocation failure.\n"));
3770 		ipsec_in_free(ii);
3771 		return (NULL);
3772 	}
3773 
3774 	ipsec_in->b_datap->db_type = M_CTL;
3775 	ipsec_in->b_wptr += sizeof (ipsec_info_t);
3776 
3777 	return (ipsec_in);
3778 }
3779 
3780 /*
3781  * This is called from ip_wput_local when a packet which needs
3782  * security is looped back, to convert the IPSEC_OUT to a IPSEC_IN
3783  * before fanout, where the policy check happens.  In most of the
3784  * cases, IPSEC processing has *never* been done.  There is one case
3785  * (ip_wput_ire_fragmentit -> ip_wput_frag -> icmp_frag_needed) where
3786  * the packet is destined for localhost, IPSEC processing has already
3787  * been done.
3788  *
3789  * Future: This could happen after SA selection has occurred for
3790  * outbound.. which will tell us who the src and dst identities are..
3791  * Then it's just a matter of splicing the ah/esp SA pointers from the
3792  * ipsec_out_t to the ipsec_in_t.
3793  */
3794 void
3795 ipsec_out_to_in(mblk_t *ipsec_mp)
3796 {
3797 	ipsec_in_t  *ii;
3798 	ipsec_out_t *io;
3799 	ipsec_policy_t *pol;
3800 	ipsec_action_t *act;
3801 	boolean_t v4, icmp_loopback;
3802 
3803 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL);
3804 
3805 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
3806 
3807 	v4 = io->ipsec_out_v4;
3808 	icmp_loopback = io->ipsec_out_icmp_loopback;
3809 
3810 	act = io->ipsec_out_act;
3811 	if (act == NULL) {
3812 		pol = io->ipsec_out_policy;
3813 		if (pol != NULL) {
3814 			act = pol->ipsp_act;
3815 			IPACT_REFHOLD(act);
3816 		}
3817 	}
3818 	io->ipsec_out_act = NULL;
3819 
3820 	ipsec_out_release_refs(io);
3821 
3822 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
3823 	bzero(ii, sizeof (ipsec_in_t));
3824 	ii->ipsec_in_type = IPSEC_IN;
3825 	ii->ipsec_in_len = sizeof (ipsec_in_t);
3826 	ii->ipsec_in_loopback = B_TRUE;
3827 	ii->ipsec_in_frtn.free_func = ipsec_in_free;
3828 	ii->ipsec_in_frtn.free_arg = (char *)ii;
3829 	ii->ipsec_in_action = act;
3830 
3831 	/*
3832 	 * In most of the cases, we can't look at the ipsec_out_XXX_sa
3833 	 * because this never went through IPSEC processing. So, look at
3834 	 * the requests and infer whether it would have gone through
3835 	 * IPSEC processing or not. Initialize the "done" fields with
3836 	 * the requests. The possible values for "done" fields are :
3837 	 *
3838 	 * 1) zero, indicates that a particular preference was never
3839 	 *    requested.
3840 	 * 2) non-zero, indicates that it could be IPSEC_PREF_REQUIRED/
3841 	 *    IPSEC_PREF_NEVER. If IPSEC_REQ_DONE is set, it means that
3842 	 *    IPSEC processing has been completed.
3843 	 */
3844 	ii->ipsec_in_secure = B_TRUE;
3845 	ii->ipsec_in_v4 = v4;
3846 	ii->ipsec_in_icmp_loopback = icmp_loopback;
3847 	ii->ipsec_in_attach_if = B_FALSE;
3848 }
3849 
3850 /*
3851  * Consults global policy to see whether this datagram should
3852  * go out secure. If so it attaches a ipsec_mp in front and
3853  * returns.
3854  */
3855 mblk_t *
3856 ip_wput_attach_policy(mblk_t *ipsec_mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
3857     conn_t *connp, boolean_t unspec_src)
3858 {
3859 	mblk_t *mp;
3860 	ipsec_out_t *io = NULL;
3861 	ipsec_selector_t sel;
3862 	uint_t	ill_index;
3863 	boolean_t conn_dontroutex;
3864 	boolean_t conn_multicast_loopx;
3865 	boolean_t policy_present;
3866 
3867 	ASSERT((ipha != NULL && ip6h == NULL) ||
3868 	    (ip6h != NULL && ipha == NULL));
3869 
3870 	bzero((void*)&sel, sizeof (sel));
3871 
3872 	if (ipha != NULL)
3873 		policy_present = ipsec_outbound_v4_policy_present;
3874 	else
3875 		policy_present = ipsec_outbound_v6_policy_present;
3876 	/*
3877 	 * Fast Path to see if there is any policy.
3878 	 */
3879 	if (!policy_present) {
3880 		if (ipsec_mp->b_datap->db_type == M_CTL) {
3881 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
3882 			if (!io->ipsec_out_secure) {
3883 				/*
3884 				 * If there is no global policy and ip_wput
3885 				 * or ip_wput_multicast has attached this mp
3886 				 * for multicast case, free the ipsec_mp and
3887 				 * return the original mp.
3888 				 */
3889 				mp = ipsec_mp->b_cont;
3890 				freeb(ipsec_mp);
3891 				ipsec_mp = mp;
3892 				io = NULL;
3893 			}
3894 		}
3895 		if (((io == NULL) || (io->ipsec_out_polhead == NULL)) &&
3896 		    ((connp == NULL) || (connp->conn_policy == NULL)))
3897 			return (ipsec_mp);
3898 	}
3899 
3900 	ill_index = 0;
3901 	conn_multicast_loopx = conn_dontroutex = B_FALSE;
3902 	mp = ipsec_mp;
3903 	if (ipsec_mp->b_datap->db_type == M_CTL) {
3904 		mp = ipsec_mp->b_cont;
3905 		/*
3906 		 * This is a connection where we have some per-socket
3907 		 * policy or ip_wput has attached an ipsec_mp for
3908 		 * the multicast datagram.
3909 		 */
3910 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
3911 		if (!io->ipsec_out_secure) {
3912 			/*
3913 			 * This ipsec_mp was allocated in ip_wput or
3914 			 * ip_wput_multicast so that we will know the
3915 			 * value of ill_index, conn_dontroute,
3916 			 * conn_multicast_loop in the multicast case if
3917 			 * we inherit global policy here.
3918 			 */
3919 			ill_index = io->ipsec_out_ill_index;
3920 			conn_dontroutex = io->ipsec_out_dontroute;
3921 			conn_multicast_loopx = io->ipsec_out_multicast_loop;
3922 			freeb(ipsec_mp);
3923 			ipsec_mp = mp;
3924 			io = NULL;
3925 		}
3926 	}
3927 
3928 	if (ipha != NULL) {
3929 		sel.ips_local_addr_v4 = (ipha->ipha_src != 0 ?
3930 		    ipha->ipha_src : ire->ire_src_addr);
3931 		sel.ips_remote_addr_v4 = ip_get_dst(ipha);
3932 		sel.ips_protocol = (uint8_t)ipha->ipha_protocol;
3933 		sel.ips_isv4 = B_TRUE;
3934 	} else {
3935 		ushort_t hdr_len;
3936 		uint8_t	*nexthdrp;
3937 		boolean_t is_fragment;
3938 
3939 		sel.ips_isv4 = B_FALSE;
3940 		if (IN6_IS_ADDR_UNSPECIFIED(&ip6h->ip6_src)) {
3941 			if (!unspec_src)
3942 				sel.ips_local_addr_v6 = ire->ire_src_addr_v6;
3943 		} else {
3944 			sel.ips_local_addr_v6 = ip6h->ip6_src;
3945 		}
3946 
3947 		sel.ips_remote_addr_v6 = ip_get_dst_v6(ip6h, &is_fragment);
3948 		if (is_fragment) {
3949 			/*
3950 			 * It's a packet fragment for a packet that
3951 			 * we have already processed (since IPsec processing
3952 			 * is done before fragmentation), so we don't
3953 			 * have to do policy checks again. Fragments can
3954 			 * come back to us for processing if they have
3955 			 * been queued up due to flow control.
3956 			 */
3957 			if (ipsec_mp->b_datap->db_type == M_CTL) {
3958 				mp = ipsec_mp->b_cont;
3959 				freeb(ipsec_mp);
3960 				ipsec_mp = mp;
3961 			}
3962 			return (ipsec_mp);
3963 		}
3964 
3965 		/* IPv6 common-case. */
3966 		sel.ips_protocol = ip6h->ip6_nxt;
3967 		switch (ip6h->ip6_nxt) {
3968 		case IPPROTO_TCP:
3969 		case IPPROTO_UDP:
3970 		case IPPROTO_SCTP:
3971 		case IPPROTO_ICMPV6:
3972 			break;
3973 		default:
3974 			if (!ip_hdr_length_nexthdr_v6(mp, ip6h,
3975 			    &hdr_len, &nexthdrp)) {
3976 				BUMP_MIB(&ip6_mib, ipv6OutDiscards);
3977 				freemsg(ipsec_mp); /* Not IPsec-related drop. */
3978 				return (NULL);
3979 			}
3980 			sel.ips_protocol = *nexthdrp;
3981 			break;
3982 		}
3983 	}
3984 
3985 	if (!ipsec_init_outbound_ports(&sel, mp, ipha, ip6h)) {
3986 		if (ipha != NULL) {
3987 			BUMP_MIB(&ip_mib, ipOutDiscards);
3988 		} else {
3989 			BUMP_MIB(&ip6_mib, ipv6OutDiscards);
3990 		}
3991 
3992 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, NULL,
3993 		    &ipdrops_spd_nomem, &spd_dropper);
3994 		return (NULL);
3995 	}
3996 
3997 	if (io != NULL) {
3998 		/*
3999 		 * We seem to have some local policy (we already have
4000 		 * an ipsec_out).  Look at global policy and see
4001 		 * whether we have to inherit or not.
4002 		 */
4003 		io->ipsec_out_need_policy = B_FALSE;
4004 		ipsec_mp = ipsec_apply_global_policy(ipsec_mp, connp, &sel);
4005 		ASSERT((io->ipsec_out_policy != NULL) ||
4006 		    (io->ipsec_out_act != NULL));
4007 		ASSERT(io->ipsec_out_need_policy == B_FALSE);
4008 		return (ipsec_mp);
4009 	}
4010 	ipsec_mp = ipsec_attach_global_policy(mp, connp, &sel);
4011 	if (ipsec_mp == NULL)
4012 		return (mp);
4013 
4014 	/*
4015 	 * Copy the right port information.
4016 	 */
4017 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL);
4018 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
4019 
4020 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
4021 	ASSERT((io->ipsec_out_policy != NULL) ||
4022 	    (io->ipsec_out_act != NULL));
4023 	io->ipsec_out_src_port = sel.ips_local_port;
4024 	io->ipsec_out_dst_port = sel.ips_remote_port;
4025 	io->ipsec_out_icmp_type = sel.ips_icmp_type;
4026 	io->ipsec_out_icmp_code = sel.ips_icmp_code;
4027 	/*
4028 	 * Set ill_index, conn_dontroute and conn_multicast_loop
4029 	 * for multicast datagrams.
4030 	 */
4031 	io->ipsec_out_ill_index = ill_index;
4032 	io->ipsec_out_dontroute = conn_dontroutex;
4033 	io->ipsec_out_multicast_loop = conn_multicast_loopx;
4034 	/*
4035 	 * When conn is non-NULL, the zoneid is set by ipsec_init_ipsec_out().
4036 	 * Otherwise set the zoneid based on the ire.
4037 	 */
4038 	if (connp == NULL)
4039 		io->ipsec_out_zoneid = ire->ire_zoneid;
4040 	return (ipsec_mp);
4041 }
4042 
4043 /*
4044  * When appropriate, this function caches inbound and outbound policy
4045  * for this connection.
4046  *
4047  * XXX need to work out more details about per-interface policy and
4048  * caching here!
4049  *
4050  * XXX may want to split inbound and outbound caching for ill..
4051  */
4052 int
4053 ipsec_conn_cache_policy(conn_t *connp, boolean_t isv4)
4054 {
4055 	boolean_t global_policy_present;
4056 
4057 	/*
4058 	 * There is no policy latching for ICMP sockets because we can't
4059 	 * decide on which policy to use until we see the packet and get
4060 	 * type/code selectors.
4061 	 */
4062 	if (connp->conn_ulp == IPPROTO_ICMP ||
4063 	    connp->conn_ulp == IPPROTO_ICMPV6) {
4064 		connp->conn_in_enforce_policy =
4065 		    connp->conn_out_enforce_policy = B_TRUE;
4066 		if (connp->conn_latch != NULL) {
4067 			IPLATCH_REFRELE(connp->conn_latch);
4068 			connp->conn_latch = NULL;
4069 		}
4070 		connp->conn_flags |= IPCL_CHECK_POLICY;
4071 		return (0);
4072 	}
4073 
4074 	global_policy_present = isv4 ?
4075 	    (ipsec_outbound_v4_policy_present ||
4076 		ipsec_inbound_v4_policy_present) :
4077 	    (ipsec_outbound_v6_policy_present ||
4078 		ipsec_inbound_v6_policy_present);
4079 
4080 	if ((connp->conn_policy != NULL) || global_policy_present) {
4081 		ipsec_selector_t sel;
4082 		ipsec_policy_t	*p;
4083 
4084 		if (connp->conn_latch == NULL &&
4085 		    (connp->conn_latch = iplatch_create()) == NULL) {
4086 			return (ENOMEM);
4087 		}
4088 
4089 		sel.ips_protocol = connp->conn_ulp;
4090 		sel.ips_local_port = connp->conn_lport;
4091 		sel.ips_remote_port = connp->conn_fport;
4092 		sel.ips_is_icmp_inv_acq = 0;
4093 		sel.ips_isv4 = isv4;
4094 		if (isv4) {
4095 			sel.ips_local_addr_v4 = connp->conn_src;
4096 			sel.ips_remote_addr_v4 = connp->conn_rem;
4097 		} else {
4098 			sel.ips_local_addr_v6 = connp->conn_srcv6;
4099 			sel.ips_remote_addr_v6 = connp->conn_remv6;
4100 		}
4101 
4102 		p = ipsec_find_policy(IPSEC_TYPE_INBOUND, connp, NULL, &sel);
4103 		if (connp->conn_latch->ipl_in_policy != NULL)
4104 			IPPOL_REFRELE(connp->conn_latch->ipl_in_policy);
4105 		connp->conn_latch->ipl_in_policy = p;
4106 		connp->conn_in_enforce_policy = (p != NULL);
4107 
4108 		p = ipsec_find_policy(IPSEC_TYPE_OUTBOUND, connp, NULL, &sel);
4109 		if (connp->conn_latch->ipl_out_policy != NULL)
4110 			IPPOL_REFRELE(connp->conn_latch->ipl_out_policy);
4111 		connp->conn_latch->ipl_out_policy = p;
4112 		connp->conn_out_enforce_policy = (p != NULL);
4113 
4114 		/* Clear the latched actions too, in case we're recaching. */
4115 		if (connp->conn_latch->ipl_out_action != NULL)
4116 			IPACT_REFRELE(connp->conn_latch->ipl_out_action);
4117 		if (connp->conn_latch->ipl_in_action != NULL)
4118 			IPACT_REFRELE(connp->conn_latch->ipl_in_action);
4119 	}
4120 
4121 	/*
4122 	 * We may or may not have policy for this endpoint.  We still set
4123 	 * conn_policy_cached so that inbound datagrams don't have to look
4124 	 * at global policy as policy is considered latched for these
4125 	 * endpoints.  We should not set conn_policy_cached until the conn
4126 	 * reflects the actual policy. If we *set* this before inheriting
4127 	 * the policy there is a window where the check
4128 	 * CONN_INBOUND_POLICY_PRESENT, will neither check with the policy
4129 	 * on the conn (because we have not yet copied the policy on to
4130 	 * conn and hence not set conn_in_enforce_policy) nor with the
4131 	 * global policy (because conn_policy_cached is already set).
4132 	 */
4133 	connp->conn_policy_cached = B_TRUE;
4134 	if (connp->conn_in_enforce_policy)
4135 		connp->conn_flags |= IPCL_CHECK_POLICY;
4136 	return (0);
4137 }
4138 
4139 void
4140 iplatch_free(ipsec_latch_t *ipl)
4141 {
4142 	if (ipl->ipl_out_policy != NULL)
4143 		IPPOL_REFRELE(ipl->ipl_out_policy);
4144 	if (ipl->ipl_in_policy != NULL)
4145 		IPPOL_REFRELE(ipl->ipl_in_policy);
4146 	if (ipl->ipl_in_action != NULL)
4147 		IPACT_REFRELE(ipl->ipl_in_action);
4148 	if (ipl->ipl_out_action != NULL)
4149 		IPACT_REFRELE(ipl->ipl_out_action);
4150 	if (ipl->ipl_local_cid != NULL)
4151 		IPSID_REFRELE(ipl->ipl_local_cid);
4152 	if (ipl->ipl_remote_cid != NULL)
4153 		IPSID_REFRELE(ipl->ipl_remote_cid);
4154 	if (ipl->ipl_local_id != NULL)
4155 		crfree(ipl->ipl_local_id);
4156 	mutex_destroy(&ipl->ipl_lock);
4157 	kmem_free(ipl, sizeof (*ipl));
4158 }
4159 
4160 ipsec_latch_t *
4161 iplatch_create()
4162 {
4163 	ipsec_latch_t *ipl = kmem_alloc(sizeof (*ipl), KM_NOSLEEP);
4164 	if (ipl == NULL)
4165 		return (ipl);
4166 	bzero(ipl, sizeof (*ipl));
4167 	mutex_init(&ipl->ipl_lock, NULL, MUTEX_DEFAULT, NULL);
4168 	ipl->ipl_refcnt = 1;
4169 	return (ipl);
4170 }
4171 
4172 /*
4173  * Identity hash table.
4174  *
4175  * Identities are refcounted and "interned" into the hash table.
4176  * Only references coming from other objects (SA's, latching state)
4177  * are counted in ipsid_refcnt.
4178  *
4179  * Locking: IPSID_REFHOLD is safe only when (a) the object's hash bucket
4180  * is locked, (b) we know that the refcount must be > 0.
4181  *
4182  * The ipsid_next and ipsid_ptpn fields are only to be referenced or
4183  * modified when the bucket lock is held; in particular, we only
4184  * delete objects while holding the bucket lock, and we only increase
4185  * the refcount from 0 to 1 while the bucket lock is held.
4186  */
4187 
4188 #define	IPSID_HASHSIZE 64
4189 
4190 typedef struct ipsif_s
4191 {
4192 	ipsid_t *ipsif_head;
4193 	kmutex_t ipsif_lock;
4194 } ipsif_t;
4195 
4196 ipsif_t ipsid_buckets[IPSID_HASHSIZE];
4197 
4198 /*
4199  * Hash function for ID hash table.
4200  */
4201 static uint32_t
4202 ipsid_hash(int idtype, char *idstring)
4203 {
4204 	uint32_t hval = idtype;
4205 	unsigned char c;
4206 
4207 	while ((c = *idstring++) != 0) {
4208 		hval = (hval << 4) | (hval >> 28);
4209 		hval ^= c;
4210 	}
4211 	hval = hval ^ (hval >> 16);
4212 	return (hval & (IPSID_HASHSIZE-1));
4213 }
4214 
4215 /*
4216  * Look up identity string in hash table.  Return identity object
4217  * corresponding to the name -- either preexisting, or newly allocated.
4218  *
4219  * Return NULL if we need to allocate a new one and can't get memory.
4220  */
4221 ipsid_t *
4222 ipsid_lookup(int idtype, char *idstring)
4223 {
4224 	ipsid_t *retval;
4225 	char *nstr;
4226 	int idlen = strlen(idstring) + 1;
4227 
4228 	ipsif_t *bucket = &ipsid_buckets[ipsid_hash(idtype, idstring)];
4229 
4230 	mutex_enter(&bucket->ipsif_lock);
4231 
4232 	for (retval = bucket->ipsif_head; retval != NULL;
4233 	    retval = retval->ipsid_next) {
4234 		if (idtype != retval->ipsid_type)
4235 			continue;
4236 		if (bcmp(idstring, retval->ipsid_cid, idlen) != 0)
4237 			continue;
4238 
4239 		IPSID_REFHOLD(retval);
4240 		mutex_exit(&bucket->ipsif_lock);
4241 		return (retval);
4242 	}
4243 
4244 	retval = kmem_alloc(sizeof (*retval), KM_NOSLEEP);
4245 	if (!retval) {
4246 		mutex_exit(&bucket->ipsif_lock);
4247 		return (NULL);
4248 	}
4249 
4250 	nstr = kmem_alloc(idlen, KM_NOSLEEP);
4251 	if (!nstr) {
4252 		mutex_exit(&bucket->ipsif_lock);
4253 		kmem_free(retval, sizeof (*retval));
4254 		return (NULL);
4255 	}
4256 
4257 	retval->ipsid_refcnt = 1;
4258 	retval->ipsid_next = bucket->ipsif_head;
4259 	if (retval->ipsid_next != NULL)
4260 		retval->ipsid_next->ipsid_ptpn = &retval->ipsid_next;
4261 	retval->ipsid_ptpn = &bucket->ipsif_head;
4262 	retval->ipsid_type = idtype;
4263 	retval->ipsid_cid = nstr;
4264 	bucket->ipsif_head = retval;
4265 	bcopy(idstring, nstr, idlen);
4266 	mutex_exit(&bucket->ipsif_lock);
4267 
4268 	return (retval);
4269 }
4270 
4271 /*
4272  * Garbage collect the identity hash table.
4273  */
4274 void
4275 ipsid_gc()
4276 {
4277 	int i, len;
4278 	ipsid_t *id, *nid;
4279 	ipsif_t *bucket;
4280 
4281 	for (i = 0; i < IPSID_HASHSIZE; i++) {
4282 		bucket = &ipsid_buckets[i];
4283 		mutex_enter(&bucket->ipsif_lock);
4284 		for (id = bucket->ipsif_head; id != NULL; id = nid) {
4285 			nid = id->ipsid_next;
4286 			if (id->ipsid_refcnt == 0) {
4287 				*id->ipsid_ptpn = nid;
4288 				if (nid != NULL)
4289 					nid->ipsid_ptpn = id->ipsid_ptpn;
4290 				len = strlen(id->ipsid_cid) + 1;
4291 				kmem_free(id->ipsid_cid, len);
4292 				kmem_free(id, sizeof (*id));
4293 			}
4294 		}
4295 		mutex_exit(&bucket->ipsif_lock);
4296 	}
4297 }
4298 
4299 /*
4300  * Return true if two identities are the same.
4301  */
4302 boolean_t
4303 ipsid_equal(ipsid_t *id1, ipsid_t *id2)
4304 {
4305 	if (id1 == id2)
4306 		return (B_TRUE);
4307 #ifdef DEBUG
4308 	if ((id1 == NULL) || (id2 == NULL))
4309 		return (B_FALSE);
4310 	/*
4311 	 * test that we're interning id's correctly..
4312 	 */
4313 	ASSERT((strcmp(id1->ipsid_cid, id2->ipsid_cid) != 0) ||
4314 	    (id1->ipsid_type != id2->ipsid_type));
4315 #endif
4316 	return (B_FALSE);
4317 }
4318 
4319 /*
4320  * Initialize identity table; called during module initialization.
4321  */
4322 static void
4323 ipsid_init()
4324 {
4325 	ipsif_t *bucket;
4326 	int i;
4327 
4328 	for (i = 0; i < IPSID_HASHSIZE; i++) {
4329 		bucket = &ipsid_buckets[i];
4330 		mutex_init(&bucket->ipsif_lock, NULL, MUTEX_DEFAULT, NULL);
4331 	}
4332 }
4333 
4334 /*
4335  * Free identity table (preparatory to module unload)
4336  */
4337 static void
4338 ipsid_fini()
4339 {
4340 	ipsif_t *bucket;
4341 	int i;
4342 
4343 	for (i = 0; i < IPSID_HASHSIZE; i++) {
4344 		bucket = &ipsid_buckets[i];
4345 		mutex_destroy(&bucket->ipsif_lock);
4346 	}
4347 }
4348 
4349 /*
4350  * Update the minimum and maximum supported key sizes for the
4351  * specified algorithm. Must be called while holding the algorithms lock.
4352  */
4353 void
4354 ipsec_alg_fix_min_max(ipsec_alginfo_t *alg, ipsec_algtype_t alg_type)
4355 {
4356 	size_t crypto_min = (size_t)-1, crypto_max = 0;
4357 	size_t cur_crypto_min, cur_crypto_max;
4358 	boolean_t is_valid;
4359 	crypto_mechanism_info_t *mech_infos;
4360 	uint_t nmech_infos;
4361 	int crypto_rc, i;
4362 	crypto_mech_usage_t mask;
4363 
4364 	ASSERT(MUTEX_HELD(&alg_lock));
4365 
4366 	/*
4367 	 * Compute the min, max, and default key sizes (in number of
4368 	 * increments to the default key size in bits) as defined
4369 	 * by the algorithm mappings. This range of key sizes is used
4370 	 * for policy related operations. The effective key sizes
4371 	 * supported by the framework could be more limited than
4372 	 * those defined for an algorithm.
4373 	 */
4374 	alg->alg_default_bits = alg->alg_key_sizes[0];
4375 	if (alg->alg_increment != 0) {
4376 		/* key sizes are defined by range & increment */
4377 		alg->alg_minbits = alg->alg_key_sizes[1];
4378 		alg->alg_maxbits = alg->alg_key_sizes[2];
4379 
4380 		alg->alg_default = SADB_ALG_DEFAULT_INCR(alg->alg_minbits,
4381 		    alg->alg_increment, alg->alg_default_bits);
4382 	} else if (alg->alg_nkey_sizes == 0) {
4383 		/* no specified key size for algorithm */
4384 		alg->alg_minbits = alg->alg_maxbits = 0;
4385 	} else {
4386 		/* key sizes are defined by enumeration */
4387 		alg->alg_minbits = (uint16_t)-1;
4388 		alg->alg_maxbits = 0;
4389 
4390 		for (i = 0; i < alg->alg_nkey_sizes; i++) {
4391 			if (alg->alg_key_sizes[i] < alg->alg_minbits)
4392 				alg->alg_minbits = alg->alg_key_sizes[i];
4393 			if (alg->alg_key_sizes[i] > alg->alg_maxbits)
4394 				alg->alg_maxbits = alg->alg_key_sizes[i];
4395 		}
4396 		alg->alg_default = 0;
4397 	}
4398 
4399 	if (!(alg->alg_flags & ALG_FLAG_VALID))
4400 		return;
4401 
4402 	/*
4403 	 * Mechanisms do not apply to the NULL encryption
4404 	 * algorithm, so simply return for this case.
4405 	 */
4406 	if (alg->alg_id == SADB_EALG_NULL)
4407 		return;
4408 
4409 	/*
4410 	 * Find the min and max key sizes supported by the cryptographic
4411 	 * framework providers.
4412 	 */
4413 
4414 	/* get the key sizes supported by the framework */
4415 	crypto_rc = crypto_get_all_mech_info(alg->alg_mech_type,
4416 	    &mech_infos, &nmech_infos, KM_SLEEP);
4417 	if (crypto_rc != CRYPTO_SUCCESS || nmech_infos == 0) {
4418 		alg->alg_flags &= ~ALG_FLAG_VALID;
4419 		return;
4420 	}
4421 
4422 	/* min and max key sizes supported by framework */
4423 	for (i = 0, is_valid = B_FALSE; i < nmech_infos; i++) {
4424 		int unit_bits;
4425 
4426 		/*
4427 		 * Ignore entries that do not support the operations
4428 		 * needed for the algorithm type.
4429 		 */
4430 		if (alg_type == IPSEC_ALG_AUTH)
4431 			mask = CRYPTO_MECH_USAGE_MAC;
4432 		else
4433 			mask = CRYPTO_MECH_USAGE_ENCRYPT |
4434 				CRYPTO_MECH_USAGE_DECRYPT;
4435 		if ((mech_infos[i].mi_usage & mask) != mask)
4436 			continue;
4437 
4438 		unit_bits = (mech_infos[i].mi_keysize_unit ==
4439 		    CRYPTO_KEYSIZE_UNIT_IN_BYTES)  ? 8 : 1;
4440 		/* adjust min/max supported by framework */
4441 		cur_crypto_min = mech_infos[i].mi_min_key_size * unit_bits;
4442 		cur_crypto_max = mech_infos[i].mi_max_key_size * unit_bits;
4443 
4444 		if (cur_crypto_min < crypto_min)
4445 			crypto_min = cur_crypto_min;
4446 
4447 		/*
4448 		 * CRYPTO_EFFECTIVELY_INFINITE is a special value of
4449 		 * the crypto framework which means "no upper limit".
4450 		 */
4451 		if (mech_infos[i].mi_max_key_size ==
4452 		    CRYPTO_EFFECTIVELY_INFINITE)
4453 			crypto_max = (size_t)-1;
4454 		else if (cur_crypto_max > crypto_max)
4455 			crypto_max = cur_crypto_max;
4456 
4457 		is_valid = B_TRUE;
4458 	}
4459 
4460 	kmem_free(mech_infos, sizeof (crypto_mechanism_info_t) *
4461 	    nmech_infos);
4462 
4463 	if (!is_valid) {
4464 		/* no key sizes supported by framework */
4465 		alg->alg_flags &= ~ALG_FLAG_VALID;
4466 		return;
4467 	}
4468 
4469 	/*
4470 	 * Determine min and max key sizes from alg_key_sizes[].
4471 	 * defined for the algorithm entry. Adjust key sizes based on
4472 	 * those supported by the framework.
4473 	 */
4474 	alg->alg_ef_default_bits = alg->alg_key_sizes[0];
4475 	if (alg->alg_increment != 0) {
4476 		/* supported key sizes are defined by range  & increment */
4477 		crypto_min = ALGBITS_ROUND_UP(crypto_min, alg->alg_increment);
4478 		crypto_max = ALGBITS_ROUND_DOWN(crypto_max, alg->alg_increment);
4479 
4480 		alg->alg_ef_minbits = MAX(alg->alg_minbits,
4481 		    (uint16_t)crypto_min);
4482 		alg->alg_ef_maxbits = MIN(alg->alg_maxbits,
4483 		    (uint16_t)crypto_max);
4484 
4485 		/*
4486 		 * If the sizes supported by the framework are outside
4487 		 * the range of sizes defined by the algorithm mappings,
4488 		 * the algorithm cannot be used. Check for this
4489 		 * condition here.
4490 		 */
4491 		if (alg->alg_ef_minbits > alg->alg_ef_maxbits) {
4492 			alg->alg_flags &= ~ALG_FLAG_VALID;
4493 			return;
4494 		}
4495 
4496 		if (alg->alg_ef_default_bits < alg->alg_ef_minbits)
4497 		    alg->alg_ef_default_bits = alg->alg_ef_minbits;
4498 		if (alg->alg_ef_default_bits > alg->alg_ef_maxbits)
4499 		    alg->alg_ef_default_bits = alg->alg_ef_maxbits;
4500 
4501 		alg->alg_ef_default = SADB_ALG_DEFAULT_INCR(alg->alg_ef_minbits,
4502 		    alg->alg_increment, alg->alg_ef_default_bits);
4503 	} else if (alg->alg_nkey_sizes == 0) {
4504 		/* no specified key size for algorithm */
4505 		alg->alg_ef_minbits = alg->alg_ef_maxbits = 0;
4506 	} else {
4507 		/* supported key sizes are defined by enumeration */
4508 		alg->alg_ef_minbits = (uint16_t)-1;
4509 		alg->alg_ef_maxbits = 0;
4510 
4511 		for (i = 0, is_valid = B_FALSE; i < alg->alg_nkey_sizes; i++) {
4512 			/*
4513 			 * Ignore the current key size if it is not in the
4514 			 * range of sizes supported by the framework.
4515 			 */
4516 			if (alg->alg_key_sizes[i] < crypto_min ||
4517 			    alg->alg_key_sizes[i] > crypto_max)
4518 				continue;
4519 			if (alg->alg_key_sizes[i] < alg->alg_ef_minbits)
4520 				alg->alg_ef_minbits = alg->alg_key_sizes[i];
4521 			if (alg->alg_key_sizes[i] > alg->alg_ef_maxbits)
4522 				alg->alg_ef_maxbits = alg->alg_key_sizes[i];
4523 			is_valid = B_TRUE;
4524 		}
4525 
4526 		if (!is_valid) {
4527 			alg->alg_flags &= ~ALG_FLAG_VALID;
4528 			return;
4529 		}
4530 		alg->alg_ef_default = 0;
4531 	}
4532 }
4533 
4534 /*
4535  * Free the memory used by the specified algorithm.
4536  */
4537 void
4538 ipsec_alg_free(ipsec_alginfo_t *alg)
4539 {
4540 	if (alg == NULL)
4541 		return;
4542 
4543 	if (alg->alg_key_sizes != NULL)
4544 		kmem_free(alg->alg_key_sizes,
4545 		    (alg->alg_nkey_sizes + 1) * sizeof (uint16_t));
4546 
4547 	if (alg->alg_block_sizes != NULL)
4548 		kmem_free(alg->alg_block_sizes,
4549 		    (alg->alg_nblock_sizes + 1) * sizeof (uint16_t));
4550 
4551 	kmem_free(alg, sizeof (*alg));
4552 }
4553 
4554 /*
4555  * Check the validity of the specified key size for an algorithm.
4556  * Returns B_TRUE if key size is valid, B_FALSE otherwise.
4557  */
4558 boolean_t
4559 ipsec_valid_key_size(uint16_t key_size, ipsec_alginfo_t *alg)
4560 {
4561 	if (key_size < alg->alg_ef_minbits || key_size > alg->alg_ef_maxbits)
4562 		return (B_FALSE);
4563 
4564 	if (alg->alg_increment == 0 && alg->alg_nkey_sizes != 0) {
4565 		/*
4566 		 * If the key sizes are defined by enumeration, the new
4567 		 * key size must be equal to one of the supported values.
4568 		 */
4569 		int i;
4570 
4571 		for (i = 0; i < alg->alg_nkey_sizes; i++)
4572 			if (key_size == alg->alg_key_sizes[i])
4573 				break;
4574 		if (i == alg->alg_nkey_sizes)
4575 			return (B_FALSE);
4576 	}
4577 
4578 	return (B_TRUE);
4579 }
4580 
4581 /*
4582  * Callback function invoked by the crypto framework when a provider
4583  * registers or unregisters. This callback updates the algorithms
4584  * tables when a crypto algorithm is no longer available or becomes
4585  * available, and triggers the freeing/creation of context templates
4586  * associated with existing SAs, if needed.
4587  */
4588 void
4589 ipsec_prov_update_callback(uint32_t event, void *event_arg)
4590 {
4591 	crypto_notify_event_change_t *prov_change =
4592 	    (crypto_notify_event_change_t *)event_arg;
4593 	uint_t algidx, algid, algtype, mech_count, mech_idx;
4594 	ipsec_alginfo_t *alg;
4595 	ipsec_alginfo_t oalg;
4596 	crypto_mech_name_t *mechs;
4597 	boolean_t alg_changed = B_FALSE;
4598 
4599 	/* ignore events for which we didn't register */
4600 	if (event != CRYPTO_EVENT_PROVIDERS_CHANGE) {
4601 		ip1dbg(("ipsec_prov_update_callback: unexpected event 0x%x "
4602 			" received from crypto framework\n", event));
4603 		return;
4604 	}
4605 
4606 	mechs = crypto_get_mech_list(&mech_count, KM_SLEEP);
4607 	if (mechs == NULL)
4608 		return;
4609 
4610 	/*
4611 	 * Walk the list of currently defined IPsec algorithm. Update
4612 	 * the algorithm valid flag and trigger an update of the
4613 	 * SAs that depend on that algorithm.
4614 	 */
4615 	mutex_enter(&alg_lock);
4616 	for (algtype = 0; algtype < IPSEC_NALGTYPES; algtype++) {
4617 		for (algidx = 0; algidx < ipsec_nalgs[algtype]; algidx++) {
4618 
4619 			algid = ipsec_sortlist[algtype][algidx];
4620 			alg = ipsec_alglists[algtype][algid];
4621 			ASSERT(alg != NULL);
4622 
4623 			/*
4624 			 * Skip the algorithms which do not map to the
4625 			 * crypto framework provider being added or removed.
4626 			 */
4627 			if (strncmp(alg->alg_mech_name,
4628 			    prov_change->ec_mech_name,
4629 			    CRYPTO_MAX_MECH_NAME) != 0)
4630 				continue;
4631 
4632 			/*
4633 			 * Determine if the mechanism is valid. If it
4634 			 * is not, mark the algorithm as being invalid. If
4635 			 * it is, mark the algorithm as being valid.
4636 			 */
4637 			for (mech_idx = 0; mech_idx < mech_count; mech_idx++)
4638 				if (strncmp(alg->alg_mech_name,
4639 				    mechs[mech_idx], CRYPTO_MAX_MECH_NAME) == 0)
4640 					break;
4641 			if (mech_idx == mech_count &&
4642 			    alg->alg_flags & ALG_FLAG_VALID) {
4643 				alg->alg_flags &= ~ALG_FLAG_VALID;
4644 				alg_changed = B_TRUE;
4645 			} else if (mech_idx < mech_count &&
4646 			    !(alg->alg_flags & ALG_FLAG_VALID)) {
4647 				alg->alg_flags |= ALG_FLAG_VALID;
4648 				alg_changed = B_TRUE;
4649 			}
4650 
4651 			/*
4652 			 * Update the supported key sizes, regardless
4653 			 * of whether a crypto provider was added or
4654 			 * removed.
4655 			 */
4656 			oalg = *alg;
4657 			ipsec_alg_fix_min_max(alg, algtype);
4658 			if (!alg_changed &&
4659 			    alg->alg_ef_minbits != oalg.alg_ef_minbits ||
4660 			    alg->alg_ef_maxbits != oalg.alg_ef_maxbits ||
4661 			    alg->alg_ef_default != oalg.alg_ef_default ||
4662 			    alg->alg_ef_default_bits !=
4663 			    oalg.alg_ef_default_bits)
4664 				alg_changed = B_TRUE;
4665 
4666 			/*
4667 			 * Update the affected SAs if a software provider is
4668 			 * being added or removed.
4669 			 */
4670 			if (prov_change->ec_provider_type ==
4671 			    CRYPTO_SW_PROVIDER)
4672 				sadb_alg_update(algtype, alg->alg_id,
4673 				    prov_change->ec_change ==
4674 				    CRYPTO_EVENT_CHANGE_ADDED);
4675 		}
4676 	}
4677 	mutex_exit(&alg_lock);
4678 	crypto_free_mech_list(mechs, mech_count);
4679 
4680 	if (alg_changed) {
4681 		/*
4682 		 * An algorithm has changed, i.e. it became valid or
4683 		 * invalid, or its support key sizes have changed.
4684 		 * Notify ipsecah and ipsecesp of this change so
4685 		 * that they can send a SADB_REGISTER to their consumers.
4686 		 */
4687 		ipsecah_algs_changed();
4688 		ipsecesp_algs_changed();
4689 	}
4690 }
4691 
4692 /*
4693  * Registers with the crypto framework to be notified of crypto
4694  * providers changes. Used to update the algorithm tables and
4695  * to free or create context templates if needed. Invoked after IPsec
4696  * is loaded successfully.
4697  */
4698 void
4699 ipsec_register_prov_update(void)
4700 {
4701 	prov_update_handle = crypto_notify_events(
4702 	    ipsec_prov_update_callback, CRYPTO_EVENT_PROVIDERS_CHANGE);
4703 }
4704 
4705 /*
4706  * Unregisters from the framework to be notified of crypto providers
4707  * changes. Called from ipsec_policy_destroy().
4708  */
4709 static void
4710 ipsec_unregister_prov_update(void)
4711 {
4712 	if (prov_update_handle != NULL)
4713 		crypto_unnotify_events(prov_update_handle);
4714 }
4715