xref: /illumos-gate/usr/src/uts/common/inet/ip/spdsock.c (revision 88ecc943b4eb72f7c4fbbd8435997b85ef171fc3)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #include <sys/param.h>
27 #include <sys/types.h>
28 #include <sys/stream.h>
29 #include <sys/strsubr.h>
30 #include <sys/strsun.h>
31 #include <sys/stropts.h>
32 #include <sys/zone.h>
33 #include <sys/vnode.h>
34 #include <sys/sysmacros.h>
35 #define	_SUN_TPI_VERSION 2
36 #include <sys/tihdr.h>
37 #include <sys/ddi.h>
38 #include <sys/sunddi.h>
39 #include <sys/mkdev.h>
40 #include <sys/debug.h>
41 #include <sys/kmem.h>
42 #include <sys/cmn_err.h>
43 #include <sys/suntpi.h>
44 #include <sys/policy.h>
45 
46 #include <sys/socket.h>
47 #include <netinet/in.h>
48 #include <net/pfkeyv2.h>
49 #include <net/pfpolicy.h>
50 
51 #include <inet/common.h>
52 #include <netinet/ip6.h>
53 #include <inet/ip.h>
54 #include <inet/ip6.h>
55 #include <inet/mi.h>
56 #include <inet/proto_set.h>
57 #include <inet/nd.h>
58 #include <inet/ip_if.h>
59 #include <inet/tun.h>
60 #include <inet/optcom.h>
61 #include <inet/ipsec_info.h>
62 #include <inet/ipsec_impl.h>
63 #include <inet/spdsock.h>
64 #include <inet/sadb.h>
65 
66 #include <sys/isa_defs.h>
67 
68 #include <c2/audit.h>
69 
70 /*
71  * This is a transport provider for the PF_POLICY IPsec policy
72  * management socket, which provides a management interface into the
73  * SPD, allowing policy rules to be added, deleted, and queried.
74  *
75  * This effectively replaces the old private SIOC*IPSECONFIG ioctls
76  * with an extensible interface which will hopefully be public some
77  * day.
78  *
79  * See <net/pfpolicy.h> for more details on the protocol.
80  *
81  * We link against drv/ip and call directly into it to manipulate the
82  * SPD; see ipsec_impl.h for the policy data structures and spd.c for
83  * the code which maintains them.
84  *
85  * The MT model of this is QPAIR with the addition of some explicit
86  * locking to protect system-wide policy data structures.
87  */
88 
89 static vmem_t *spdsock_vmem;		/* for minor numbers. */
90 
91 #define	ALIGNED64(x) IS_P2ALIGNED((x), sizeof (uint64_t))
92 
93 /* Default structure copied into T_INFO_ACK messages (from rts.c...) */
94 static struct T_info_ack spdsock_g_t_info_ack = {
95 	T_INFO_ACK,
96 	T_INFINITE,	/* TSDU_size. Maximum size messages. */
97 	T_INVALID,	/* ETSDU_size. No expedited data. */
98 	T_INVALID,	/* CDATA_size. No connect data. */
99 	T_INVALID,	/* DDATA_size. No disconnect data. */
100 	0,		/* ADDR_size. */
101 	0,		/* OPT_size. No user-settable options */
102 	64 * 1024,	/* TIDU_size. spdsock allows maximum size messages. */
103 	T_COTS,		/* SERV_type. spdsock supports connection oriented. */
104 	TS_UNBND,	/* CURRENT_state. This is set from spdsock_state. */
105 	(XPG4_1)	/* Provider flags */
106 };
107 
108 /* Named Dispatch Parameter Management Structure */
109 typedef struct spdsockparam_s {
110 	uint_t	spdsock_param_min;
111 	uint_t	spdsock_param_max;
112 	uint_t	spdsock_param_value;
113 	char *spdsock_param_name;
114 } spdsockparam_t;
115 
116 /*
117  * Table of NDD variables supported by spdsock. These are loaded into
118  * spdsock_g_nd in spdsock_init_nd.
119  * All of these are alterable, within the min/max values given, at run time.
120  */
121 static	spdsockparam_t	lcl_param_arr[] = {
122 	/* min	max	value	name */
123 	{ 4096, 65536,	8192,	"spdsock_xmit_hiwat"},
124 	{ 0,	65536,	1024,	"spdsock_xmit_lowat"},
125 	{ 4096, 65536,	8192,	"spdsock_recv_hiwat"},
126 	{ 65536, 1024*1024*1024, 256*1024,	"spdsock_max_buf"},
127 	{ 0,	3,	0,	"spdsock_debug"},
128 };
129 #define	spds_xmit_hiwat	spds_params[0].spdsock_param_value
130 #define	spds_xmit_lowat	spds_params[1].spdsock_param_value
131 #define	spds_recv_hiwat	spds_params[2].spdsock_param_value
132 #define	spds_max_buf	spds_params[3].spdsock_param_value
133 #define	spds_debug		spds_params[4].spdsock_param_value
134 
135 #define	ss0dbg(a)	printf a
136 /* NOTE:  != 0 instead of > 0 so lint doesn't complain. */
137 #define	ss1dbg(spds, a)	if (spds->spds_debug != 0) printf a
138 #define	ss2dbg(spds, a)	if (spds->spds_debug > 1) printf a
139 #define	ss3dbg(spds, a)	if (spds->spds_debug > 2) printf a
140 
141 #define	RESET_SPDSOCK_DUMP_POLHEAD(ss, iph) { \
142 	ASSERT(RW_READ_HELD(&(iph)->iph_lock)); \
143 	(ss)->spdsock_dump_head = (iph); \
144 	(ss)->spdsock_dump_gen = (iph)->iph_gen; \
145 	(ss)->spdsock_dump_cur_type = 0; \
146 	(ss)->spdsock_dump_cur_af = IPSEC_AF_V4; \
147 	(ss)->spdsock_dump_cur_rule = NULL; \
148 	(ss)->spdsock_dump_count = 0; \
149 	(ss)->spdsock_dump_cur_chain = 0; \
150 }
151 
152 static int spdsock_close(queue_t *);
153 static int spdsock_open(queue_t *, dev_t *, int, int, cred_t *);
154 static void spdsock_wput(queue_t *, mblk_t *);
155 static void spdsock_wsrv(queue_t *);
156 static void spdsock_rsrv(queue_t *);
157 static void *spdsock_stack_init(netstackid_t stackid, netstack_t *ns);
158 static void spdsock_stack_fini(netstackid_t stackid, void *arg);
159 static void spdsock_loadcheck(void *);
160 static void spdsock_merge_algs(spd_stack_t *);
161 static void spdsock_flush_one(ipsec_policy_head_t *, netstack_t *);
162 static mblk_t *spdsock_dump_next_record(spdsock_t *);
163 
164 static struct module_info info = {
165 	5138, "spdsock", 1, INFPSZ, 512, 128
166 };
167 
168 static struct qinit rinit = {
169 	NULL, (pfi_t)spdsock_rsrv, spdsock_open, spdsock_close,
170 	NULL, &info
171 };
172 
173 static struct qinit winit = {
174 	(pfi_t)spdsock_wput, (pfi_t)spdsock_wsrv, NULL, NULL, NULL, &info
175 };
176 
177 struct streamtab spdsockinfo = {
178 	&rinit, &winit
179 };
180 
181 /* mapping from alg type to protocol number, as per RFC 2407 */
182 static const uint_t algproto[] = {
183 	PROTO_IPSEC_AH,
184 	PROTO_IPSEC_ESP,
185 };
186 
187 #define	NALGPROTOS	(sizeof (algproto) / sizeof (algproto[0]))
188 
189 /* mapping from kernel exec mode to spdsock exec mode */
190 static const uint_t execmodes[] = {
191 	SPD_ALG_EXEC_MODE_SYNC,
192 	SPD_ALG_EXEC_MODE_ASYNC
193 };
194 
195 #define	NEXECMODES	(sizeof (execmodes) / sizeof (execmodes[0]))
196 
197 #define	ALL_ACTIVE_POLHEADS ((ipsec_policy_head_t *)-1)
198 #define	ALL_INACTIVE_POLHEADS ((ipsec_policy_head_t *)-2)
199 
200 #define	ITP_NAME(itp) (itp != NULL ? itp->itp_name : NULL)
201 
202 /* ARGSUSED */
203 static int
204 spdsock_param_get(q, mp, cp, cr)
205 	queue_t	*q;
206 	mblk_t	*mp;
207 	caddr_t	cp;
208 	cred_t *cr;
209 {
210 	spdsockparam_t	*spdsockpa = (spdsockparam_t *)cp;
211 	uint_t value;
212 	spdsock_t *ss = (spdsock_t *)q->q_ptr;
213 	spd_stack_t	*spds = ss->spdsock_spds;
214 
215 	mutex_enter(&spds->spds_param_lock);
216 	value = spdsockpa->spdsock_param_value;
217 	mutex_exit(&spds->spds_param_lock);
218 
219 	(void) mi_mpprintf(mp, "%u", value);
220 	return (0);
221 }
222 
223 /* This routine sets an NDD variable in a spdsockparam_t structure. */
224 /* ARGSUSED */
225 static int
226 spdsock_param_set(q, mp, value, cp, cr)
227 	queue_t	*q;
228 	mblk_t	*mp;
229 	char *value;
230 	caddr_t	cp;
231 	cred_t *cr;
232 {
233 	ulong_t	new_value;
234 	spdsockparam_t	*spdsockpa = (spdsockparam_t *)cp;
235 	spdsock_t *ss = (spdsock_t *)q->q_ptr;
236 	spd_stack_t	*spds = ss->spdsock_spds;
237 
238 	/* Convert the value from a string into a long integer. */
239 	if (ddi_strtoul(value, NULL, 10, &new_value) != 0)
240 		return (EINVAL);
241 
242 	mutex_enter(&spds->spds_param_lock);
243 	/*
244 	 * Fail the request if the new value does not lie within the
245 	 * required bounds.
246 	 */
247 	if (new_value < spdsockpa->spdsock_param_min ||
248 	    new_value > spdsockpa->spdsock_param_max) {
249 		mutex_exit(&spds->spds_param_lock);
250 		return (EINVAL);
251 	}
252 
253 	/* Set the new value */
254 	spdsockpa->spdsock_param_value = new_value;
255 	mutex_exit(&spds->spds_param_lock);
256 
257 	return (0);
258 }
259 
260 /*
261  * Initialize at module load time
262  */
263 boolean_t
264 spdsock_ddi_init(void)
265 {
266 	spdsock_max_optsize = optcom_max_optsize(
267 	    spdsock_opt_obj.odb_opt_des_arr, spdsock_opt_obj.odb_opt_arr_cnt);
268 
269 	spdsock_vmem = vmem_create("spdsock", (void *)1, MAXMIN, 1,
270 	    NULL, NULL, NULL, 1, VM_SLEEP | VMC_IDENTIFIER);
271 
272 	/*
273 	 * We want to be informed each time a stack is created or
274 	 * destroyed in the kernel, so we can maintain the
275 	 * set of spd_stack_t's.
276 	 */
277 	netstack_register(NS_SPDSOCK, spdsock_stack_init, NULL,
278 	    spdsock_stack_fini);
279 
280 	return (B_TRUE);
281 }
282 
283 /*
284  * Walk through the param array specified registering each element with the
285  * named dispatch handler.
286  */
287 static boolean_t
288 spdsock_param_register(IDP *ndp, spdsockparam_t *ssp, int cnt)
289 {
290 	for (; cnt-- > 0; ssp++) {
291 		if (ssp->spdsock_param_name != NULL &&
292 		    ssp->spdsock_param_name[0]) {
293 			if (!nd_load(ndp,
294 			    ssp->spdsock_param_name,
295 			    spdsock_param_get, spdsock_param_set,
296 			    (caddr_t)ssp)) {
297 				nd_free(ndp);
298 				return (B_FALSE);
299 			}
300 		}
301 	}
302 	return (B_TRUE);
303 }
304 
305 /*
306  * Initialize for each stack instance
307  */
308 /* ARGSUSED */
309 static void *
310 spdsock_stack_init(netstackid_t stackid, netstack_t *ns)
311 {
312 	spd_stack_t	*spds;
313 	spdsockparam_t	*ssp;
314 
315 	spds = (spd_stack_t *)kmem_zalloc(sizeof (*spds), KM_SLEEP);
316 	spds->spds_netstack = ns;
317 
318 	ASSERT(spds->spds_g_nd == NULL);
319 
320 	ssp = (spdsockparam_t *)kmem_alloc(sizeof (lcl_param_arr), KM_SLEEP);
321 	spds->spds_params = ssp;
322 	bcopy(lcl_param_arr, ssp, sizeof (lcl_param_arr));
323 
324 	(void) spdsock_param_register(&spds->spds_g_nd, ssp,
325 	    A_CNT(lcl_param_arr));
326 
327 	mutex_init(&spds->spds_param_lock, NULL, MUTEX_DEFAULT, NULL);
328 	mutex_init(&spds->spds_alg_lock, NULL, MUTEX_DEFAULT, NULL);
329 
330 	return (spds);
331 }
332 
333 void
334 spdsock_ddi_destroy(void)
335 {
336 	vmem_destroy(spdsock_vmem);
337 
338 	netstack_unregister(NS_SPDSOCK);
339 }
340 
341 /* ARGSUSED */
342 static void
343 spdsock_stack_fini(netstackid_t stackid, void *arg)
344 {
345 	spd_stack_t *spds = (spd_stack_t *)arg;
346 
347 	freemsg(spds->spds_mp_algs);
348 	mutex_destroy(&spds->spds_param_lock);
349 	mutex_destroy(&spds->spds_alg_lock);
350 	nd_free(&spds->spds_g_nd);
351 	kmem_free(spds->spds_params, sizeof (lcl_param_arr));
352 	spds->spds_params = NULL;
353 
354 	kmem_free(spds, sizeof (*spds));
355 }
356 
357 /*
358  * NOTE: large quantities of this should be shared with keysock.
359  * Would be nice to combine some of this into a common module, but
360  * not possible given time pressures.
361  */
362 
363 /*
364  * High-level reality checking of extensions.
365  */
366 /* ARGSUSED */ /* XXX */
367 static boolean_t
368 ext_check(spd_ext_t *ext)
369 {
370 	spd_if_t *tunname = (spd_if_t *)ext;
371 	int i;
372 	char *idstr;
373 
374 	if (ext->spd_ext_type == SPD_EXT_TUN_NAME) {
375 		/* (NOTE:  Modified from SADB_EXT_IDENTITY..) */
376 
377 		/*
378 		 * Make sure the strings in these identities are
379 		 * null-terminated.  Let's "proactively" null-terminate the
380 		 * string at the last byte if it's not terminated sooner.
381 		 */
382 		i = SPD_64TO8(tunname->spd_if_len) - sizeof (spd_if_t);
383 		idstr = (char *)(tunname + 1);
384 		while (*idstr != '\0' && i > 0) {
385 			i--;
386 			idstr++;
387 		}
388 		if (i == 0) {
389 			/*
390 			 * I.e., if the bozo user didn't NULL-terminate the
391 			 * string...
392 			 */
393 			idstr--;
394 			*idstr = '\0';
395 		}
396 	}
397 	return (B_TRUE);	/* For now... */
398 }
399 
400 
401 
402 /* Return values for spdsock_get_ext(). */
403 #define	KGE_OK	0
404 #define	KGE_DUP	1
405 #define	KGE_UNK	2
406 #define	KGE_LEN	3
407 #define	KGE_CHK	4
408 
409 /*
410  * Parse basic extension headers and return in the passed-in pointer vector.
411  * Return values include:
412  *
413  *	KGE_OK	Everything's nice and parsed out.
414  *		If there are no extensions, place NULL in extv[0].
415  *	KGE_DUP	There is a duplicate extension.
416  *		First instance in appropriate bin.  First duplicate in
417  *		extv[0].
418  *	KGE_UNK	Unknown extension type encountered.  extv[0] contains
419  *		unknown header.
420  *	KGE_LEN	Extension length error.
421  *	KGE_CHK	High-level reality check failed on specific extension.
422  *
423  * My apologies for some of the pointer arithmetic in here.  I'm thinking
424  * like an assembly programmer, yet trying to make the compiler happy.
425  */
426 static int
427 spdsock_get_ext(spd_ext_t *extv[], spd_msg_t *basehdr, uint_t msgsize)
428 {
429 	bzero(extv, sizeof (spd_ext_t *) * (SPD_EXT_MAX + 1));
430 
431 	/* Use extv[0] as the "current working pointer". */
432 
433 	extv[0] = (spd_ext_t *)(basehdr + 1);
434 
435 	while (extv[0] < (spd_ext_t *)(((uint8_t *)basehdr) + msgsize)) {
436 		/* Check for unknown headers. */
437 		if (extv[0]->spd_ext_type == 0 ||
438 		    extv[0]->spd_ext_type > SPD_EXT_MAX)
439 			return (KGE_UNK);
440 
441 		/*
442 		 * Check length.  Use uint64_t because extlen is in units
443 		 * of 64-bit words.  If length goes beyond the msgsize,
444 		 * return an error.  (Zero length also qualifies here.)
445 		 */
446 		if (extv[0]->spd_ext_len == 0 ||
447 		    (void *)((uint64_t *)extv[0] + extv[0]->spd_ext_len) >
448 		    (void *)((uint8_t *)basehdr + msgsize))
449 			return (KGE_LEN);
450 
451 		/* Check for redundant headers. */
452 		if (extv[extv[0]->spd_ext_type] != NULL)
453 			return (KGE_DUP);
454 
455 		/*
456 		 * Reality check the extension if possible at the spdsock
457 		 * level.
458 		 */
459 		if (!ext_check(extv[0]))
460 			return (KGE_CHK);
461 
462 		/* If I make it here, assign the appropriate bin. */
463 		extv[extv[0]->spd_ext_type] = extv[0];
464 
465 		/* Advance pointer (See above for uint64_t ptr reasoning.) */
466 		extv[0] = (spd_ext_t *)
467 		    ((uint64_t *)extv[0] + extv[0]->spd_ext_len);
468 	}
469 
470 	/* Everything's cool. */
471 
472 	/*
473 	 * If extv[0] == NULL, then there are no extension headers in this
474 	 * message.  Ensure that this is the case.
475 	 */
476 	if (extv[0] == (spd_ext_t *)(basehdr + 1))
477 		extv[0] = NULL;
478 
479 	return (KGE_OK);
480 }
481 
482 static const int bad_ext_diag[] = {
483 	SPD_DIAGNOSTIC_MALFORMED_LCLPORT,
484 	SPD_DIAGNOSTIC_MALFORMED_REMPORT,
485 	SPD_DIAGNOSTIC_MALFORMED_PROTO,
486 	SPD_DIAGNOSTIC_MALFORMED_LCLADDR,
487 	SPD_DIAGNOSTIC_MALFORMED_REMADDR,
488 	SPD_DIAGNOSTIC_MALFORMED_ACTION,
489 	SPD_DIAGNOSTIC_MALFORMED_RULE,
490 	SPD_DIAGNOSTIC_MALFORMED_RULESET,
491 	SPD_DIAGNOSTIC_MALFORMED_ICMP_TYPECODE
492 };
493 
494 static const int dup_ext_diag[] = {
495 	SPD_DIAGNOSTIC_DUPLICATE_LCLPORT,
496 	SPD_DIAGNOSTIC_DUPLICATE_REMPORT,
497 	SPD_DIAGNOSTIC_DUPLICATE_PROTO,
498 	SPD_DIAGNOSTIC_DUPLICATE_LCLADDR,
499 	SPD_DIAGNOSTIC_DUPLICATE_REMADDR,
500 	SPD_DIAGNOSTIC_DUPLICATE_ACTION,
501 	SPD_DIAGNOSTIC_DUPLICATE_RULE,
502 	SPD_DIAGNOSTIC_DUPLICATE_RULESET,
503 	SPD_DIAGNOSTIC_DUPLICATE_ICMP_TYPECODE
504 };
505 
506 /*
507  * Transmit a PF_POLICY error message to the instance either pointed to
508  * by ks, the instance with serial number serial, or more, depending.
509  *
510  * The faulty message (or a reasonable facsimile thereof) is in mp.
511  * This function will free mp or recycle it for delivery, thereby causing
512  * the stream head to free it.
513  */
514 static void
515 spdsock_error(queue_t *q, mblk_t *mp, int error, int diagnostic)
516 {
517 	spd_msg_t *spmsg = (spd_msg_t *)mp->b_rptr;
518 
519 	ASSERT(mp->b_datap->db_type == M_DATA);
520 
521 	if (spmsg->spd_msg_type < SPD_MIN ||
522 	    spmsg->spd_msg_type > SPD_MAX)
523 		spmsg->spd_msg_type = SPD_RESERVED;
524 
525 	/*
526 	 * Strip out extension headers.
527 	 */
528 	ASSERT(mp->b_rptr + sizeof (*spmsg) <= mp->b_datap->db_lim);
529 	mp->b_wptr = mp->b_rptr + sizeof (*spmsg);
530 	spmsg->spd_msg_len = SPD_8TO64(sizeof (spd_msg_t));
531 	spmsg->spd_msg_errno = (uint8_t)error;
532 	spmsg->spd_msg_diagnostic = (uint16_t)diagnostic;
533 
534 	qreply(q, mp);
535 }
536 
537 static void
538 spdsock_diag(queue_t *q, mblk_t *mp, int diagnostic)
539 {
540 	spdsock_error(q, mp, EINVAL, diagnostic);
541 }
542 
543 static void
544 spd_echo(queue_t *q, mblk_t *mp)
545 {
546 	qreply(q, mp);
547 }
548 
549 /*
550  * Do NOT consume a reference to itp.
551  */
552 /*ARGSUSED*/
553 static void
554 spdsock_flush_node(ipsec_tun_pol_t *itp, void *cookie, netstack_t *ns)
555 {
556 	boolean_t active = (boolean_t)cookie;
557 	ipsec_policy_head_t *iph;
558 
559 	iph = active ? itp->itp_policy : itp->itp_inactive;
560 	IPPH_REFHOLD(iph);
561 	mutex_enter(&itp->itp_lock);
562 	spdsock_flush_one(iph, ns);
563 	if (active)
564 		itp->itp_flags &= ~ITPF_PFLAGS;
565 	else
566 		itp->itp_flags &= ~ITPF_IFLAGS;
567 	mutex_exit(&itp->itp_lock);
568 }
569 
570 /*
571  * Clear out one polhead.
572  */
573 static void
574 spdsock_flush_one(ipsec_policy_head_t *iph, netstack_t *ns)
575 {
576 	rw_enter(&iph->iph_lock, RW_WRITER);
577 	ipsec_polhead_flush(iph, ns);
578 	rw_exit(&iph->iph_lock);
579 	IPPH_REFRELE(iph, ns);
580 }
581 
582 static void
583 spdsock_flush(queue_t *q, ipsec_policy_head_t *iph, ipsec_tun_pol_t *itp,
584     mblk_t *mp)
585 {
586 	boolean_t active;
587 	spdsock_t *ss = (spdsock_t *)q->q_ptr;
588 	netstack_t *ns = ss->spdsock_spds->spds_netstack;
589 
590 	if (iph != ALL_ACTIVE_POLHEADS && iph != ALL_INACTIVE_POLHEADS) {
591 		spdsock_flush_one(iph, ns);
592 		if (audit_active) {
593 			spd_msg_t *spmsg = (spd_msg_t *)mp->b_rptr;
594 			cred_t *cr;
595 			pid_t cpid;
596 
597 			cr = msg_getcred(mp, &cpid);
598 			active = (spmsg->spd_msg_spdid == SPD_ACTIVE);
599 			audit_pf_policy(SPD_FLUSH, cr, ns,
600 			    ITP_NAME(itp), active, 0, cpid);
601 		}
602 	} else {
603 		active = (iph == ALL_ACTIVE_POLHEADS);
604 
605 		/* First flush the global policy. */
606 		spdsock_flush_one(active ? ipsec_system_policy(ns) :
607 		    ipsec_inactive_policy(ns), ns);
608 		if (audit_active) {
609 			cred_t *cr;
610 			pid_t cpid;
611 
612 			cr = msg_getcred(mp, &cpid);
613 			audit_pf_policy(SPD_FLUSH, cr, ns, NULL,
614 			    active, 0, cpid);
615 		}
616 		/* Then flush every tunnel's appropriate one. */
617 		itp_walk(spdsock_flush_node, (void *)active, ns);
618 		if (audit_active) {
619 			cred_t *cr;
620 			pid_t cpid;
621 
622 			cr = msg_getcred(mp, &cpid);
623 			audit_pf_policy(SPD_FLUSH, cr, ns,
624 			    "all tunnels", active, 0, cpid);
625 		}
626 	}
627 
628 	spd_echo(q, mp);
629 }
630 
631 static boolean_t
632 spdsock_ext_to_sel(spd_ext_t **extv, ipsec_selkey_t *sel, int *diag)
633 {
634 	bzero(sel, sizeof (*sel));
635 
636 	if (extv[SPD_EXT_PROTO] != NULL) {
637 		struct spd_proto *pr =
638 		    (struct spd_proto *)extv[SPD_EXT_PROTO];
639 		sel->ipsl_proto = pr->spd_proto_number;
640 		sel->ipsl_valid |= IPSL_PROTOCOL;
641 	}
642 	if (extv[SPD_EXT_LCLPORT] != NULL) {
643 		struct spd_portrange *pr =
644 		    (struct spd_portrange *)extv[SPD_EXT_LCLPORT];
645 		sel->ipsl_lport = pr->spd_ports_minport;
646 		sel->ipsl_valid |= IPSL_LOCAL_PORT;
647 	}
648 	if (extv[SPD_EXT_REMPORT] != NULL) {
649 		struct spd_portrange *pr =
650 		    (struct spd_portrange *)extv[SPD_EXT_REMPORT];
651 		sel->ipsl_rport = pr->spd_ports_minport;
652 		sel->ipsl_valid |= IPSL_REMOTE_PORT;
653 	}
654 
655 	if (extv[SPD_EXT_ICMP_TYPECODE] != NULL) {
656 		struct spd_typecode *tc=
657 		    (struct spd_typecode *)extv[SPD_EXT_ICMP_TYPECODE];
658 
659 		sel->ipsl_valid |= IPSL_ICMP_TYPE;
660 		sel->ipsl_icmp_type = tc->spd_typecode_type;
661 		if (tc->spd_typecode_type_end < tc->spd_typecode_type)
662 			sel->ipsl_icmp_type_end = tc->spd_typecode_type;
663 		else
664 			sel->ipsl_icmp_type_end = tc->spd_typecode_type_end;
665 
666 		if (tc->spd_typecode_code != 255) {
667 			sel->ipsl_valid |= IPSL_ICMP_CODE;
668 			sel->ipsl_icmp_code = tc->spd_typecode_code;
669 			if (tc->spd_typecode_code_end < tc->spd_typecode_code)
670 				sel->ipsl_icmp_code_end = tc->spd_typecode_code;
671 			else
672 				sel->ipsl_icmp_code_end =
673 				    tc->spd_typecode_code_end;
674 		}
675 	}
676 #define	ADDR2SEL(sel, extv, field, pfield, extn, bit)			      \
677 	if ((extv)[(extn)] != NULL) {					      \
678 		uint_t addrlen;						      \
679 		struct spd_address *ap = 				      \
680 			(struct spd_address *)((extv)[(extn)]); 	      \
681 		addrlen = (ap->spd_address_af == AF_INET6) ? 		      \
682 			IPV6_ADDR_LEN : IP_ADDR_LEN;			      \
683 		if (SPD_64TO8(ap->spd_address_len) < 			      \
684 			(addrlen + sizeof (*ap))) {			      \
685 			*diag = SPD_DIAGNOSTIC_BAD_ADDR_LEN;		      \
686 			return (B_FALSE);				      \
687 		}							      \
688 		bcopy((ap+1), &((sel)->field), addrlen);		      \
689 		(sel)->pfield = ap->spd_address_prefixlen;		      \
690 		(sel)->ipsl_valid |= (bit);				      \
691 		(sel)->ipsl_valid |= (ap->spd_address_af == AF_INET6) ?	      \
692 			IPSL_IPV6 : IPSL_IPV4;				      \
693 	}
694 
695 	ADDR2SEL(sel, extv, ipsl_local, ipsl_local_pfxlen,
696 	    SPD_EXT_LCLADDR, IPSL_LOCAL_ADDR);
697 	ADDR2SEL(sel, extv, ipsl_remote, ipsl_remote_pfxlen,
698 	    SPD_EXT_REMADDR, IPSL_REMOTE_ADDR);
699 
700 	if ((sel->ipsl_valid & (IPSL_IPV6|IPSL_IPV4)) ==
701 	    (IPSL_IPV6|IPSL_IPV4)) {
702 		*diag = SPD_DIAGNOSTIC_MIXED_AF;
703 		return (B_FALSE);
704 	}
705 
706 #undef ADDR2SEL
707 
708 	return (B_TRUE);
709 }
710 
711 static boolean_t
712 spd_convert_type(uint32_t type, ipsec_act_t *act)
713 {
714 	switch (type) {
715 	case SPD_ACTTYPE_DROP:
716 		act->ipa_type = IPSEC_ACT_DISCARD;
717 		return (B_TRUE);
718 
719 	case SPD_ACTTYPE_PASS:
720 		act->ipa_type = IPSEC_ACT_CLEAR;
721 		return (B_TRUE);
722 
723 	case SPD_ACTTYPE_IPSEC:
724 		act->ipa_type = IPSEC_ACT_APPLY;
725 		return (B_TRUE);
726 	}
727 	return (B_FALSE);
728 }
729 
730 static boolean_t
731 spd_convert_flags(uint32_t flags, ipsec_act_t *act)
732 {
733 	/*
734 	 * Note use of !! for boolean canonicalization.
735 	 */
736 	act->ipa_apply.ipp_use_ah = !!(flags & SPD_APPLY_AH);
737 	act->ipa_apply.ipp_use_esp = !!(flags & SPD_APPLY_ESP);
738 	act->ipa_apply.ipp_use_espa = !!(flags & SPD_APPLY_ESPA);
739 	act->ipa_apply.ipp_use_se = !!(flags & SPD_APPLY_SE);
740 	act->ipa_apply.ipp_use_unique = !!(flags & SPD_APPLY_UNIQUE);
741 	return (B_TRUE);
742 }
743 
744 static void
745 spdsock_reset_act(ipsec_act_t *act)
746 {
747 	bzero(act, sizeof (*act));
748 	act->ipa_apply.ipp_espe_maxbits = IPSEC_MAX_KEYBITS;
749 	act->ipa_apply.ipp_espa_maxbits = IPSEC_MAX_KEYBITS;
750 	act->ipa_apply.ipp_ah_maxbits = IPSEC_MAX_KEYBITS;
751 }
752 
753 /*
754  * Sanity check action against reality, and shrink-wrap key sizes..
755  */
756 static boolean_t
757 spdsock_check_action(ipsec_act_t *act, boolean_t tunnel_polhead, int *diag,
758     spd_stack_t *spds)
759 {
760 	if (tunnel_polhead && act->ipa_apply.ipp_use_unique) {
761 		*diag = SPD_DIAGNOSTIC_ADD_INCON_FLAGS;
762 		return (B_FALSE);
763 	}
764 	if ((act->ipa_type != IPSEC_ACT_APPLY) &&
765 	    (act->ipa_apply.ipp_use_ah ||
766 	    act->ipa_apply.ipp_use_esp ||
767 	    act->ipa_apply.ipp_use_espa ||
768 	    act->ipa_apply.ipp_use_se ||
769 	    act->ipa_apply.ipp_use_unique)) {
770 		*diag = SPD_DIAGNOSTIC_ADD_INCON_FLAGS;
771 		return (B_FALSE);
772 	}
773 	if ((act->ipa_type == IPSEC_ACT_APPLY) &&
774 	    !act->ipa_apply.ipp_use_ah &&
775 	    !act->ipa_apply.ipp_use_esp) {
776 		*diag = SPD_DIAGNOSTIC_ADD_INCON_FLAGS;
777 		return (B_FALSE);
778 	}
779 	return (ipsec_check_action(act, diag, spds->spds_netstack));
780 }
781 
782 /*
783  * We may be short a few error checks here..
784  */
785 static boolean_t
786 spdsock_ext_to_actvec(spd_ext_t **extv, ipsec_act_t **actpp, uint_t *nactp,
787     int *diag, spd_stack_t *spds)
788 {
789 	struct spd_ext_actions *sactp =
790 	    (struct spd_ext_actions *)extv[SPD_EXT_ACTION];
791 	ipsec_act_t act, *actp, *endactp;
792 	struct spd_attribute *attrp, *endattrp;
793 	uint64_t *endp;
794 	int nact;
795 	boolean_t tunnel_polhead;
796 
797 	tunnel_polhead = (extv[SPD_EXT_TUN_NAME] != NULL &&
798 	    (((struct spd_rule *)extv[SPD_EXT_RULE])->spd_rule_flags &
799 	    SPD_RULE_FLAG_TUNNEL));
800 
801 	*actpp = NULL;
802 	*nactp = 0;
803 
804 	if (sactp == NULL) {
805 		*diag = SPD_DIAGNOSTIC_NO_ACTION_EXT;
806 		return (B_FALSE);
807 	}
808 
809 	/*
810 	 * Parse the "action" extension and convert into an action chain.
811 	 */
812 
813 	nact = sactp->spd_actions_count;
814 
815 	endp = (uint64_t *)sactp;
816 	endp += sactp->spd_actions_len;
817 	endattrp = (struct spd_attribute *)endp;
818 
819 	actp = kmem_alloc(sizeof (*actp) * nact, KM_NOSLEEP);
820 	if (actp == NULL) {
821 		*diag = SPD_DIAGNOSTIC_ADD_NO_MEM;
822 		return (B_FALSE);
823 	}
824 	*actpp = actp;
825 	*nactp = nact;
826 	endactp = actp + nact;
827 
828 	spdsock_reset_act(&act);
829 	attrp = (struct spd_attribute *)(&sactp[1]);
830 
831 	for (; attrp < endattrp; attrp++) {
832 		switch (attrp->spd_attr_tag) {
833 		case SPD_ATTR_NOP:
834 			break;
835 
836 		case SPD_ATTR_EMPTY:
837 			spdsock_reset_act(&act);
838 			break;
839 
840 		case SPD_ATTR_END:
841 			attrp = endattrp;
842 			/* FALLTHRU */
843 		case SPD_ATTR_NEXT:
844 			if (actp >= endactp) {
845 				*diag = SPD_DIAGNOSTIC_ADD_WRONG_ACT_COUNT;
846 				goto fail;
847 			}
848 			if (!spdsock_check_action(&act, tunnel_polhead,
849 			    diag, spds))
850 				goto fail;
851 			*actp++ = act;
852 			spdsock_reset_act(&act);
853 			break;
854 
855 		case SPD_ATTR_TYPE:
856 			if (!spd_convert_type(attrp->spd_attr_value, &act)) {
857 				*diag = SPD_DIAGNOSTIC_ADD_BAD_TYPE;
858 				goto fail;
859 			}
860 			break;
861 
862 		case SPD_ATTR_FLAGS:
863 			if (!tunnel_polhead && extv[SPD_EXT_TUN_NAME] != NULL) {
864 				/*
865 				 * Set "sa unique" for transport-mode
866 				 * tunnels whether we want to or not.
867 				 */
868 				attrp->spd_attr_value |= SPD_APPLY_UNIQUE;
869 			}
870 			if (!spd_convert_flags(attrp->spd_attr_value, &act)) {
871 				*diag = SPD_DIAGNOSTIC_ADD_BAD_FLAGS;
872 				goto fail;
873 			}
874 			break;
875 
876 		case SPD_ATTR_AH_AUTH:
877 			if (attrp->spd_attr_value == 0) {
878 				*diag = SPD_DIAGNOSTIC_UNSUPP_AH_ALG;
879 				goto fail;
880 			}
881 			act.ipa_apply.ipp_auth_alg = attrp->spd_attr_value;
882 			break;
883 
884 		case SPD_ATTR_ESP_ENCR:
885 			if (attrp->spd_attr_value == 0) {
886 				*diag = SPD_DIAGNOSTIC_UNSUPP_ESP_ENCR_ALG;
887 				goto fail;
888 			}
889 			act.ipa_apply.ipp_encr_alg = attrp->spd_attr_value;
890 			break;
891 
892 		case SPD_ATTR_ESP_AUTH:
893 			if (attrp->spd_attr_value == 0) {
894 				*diag = SPD_DIAGNOSTIC_UNSUPP_ESP_AUTH_ALG;
895 				goto fail;
896 			}
897 			act.ipa_apply.ipp_esp_auth_alg = attrp->spd_attr_value;
898 			break;
899 
900 		case SPD_ATTR_ENCR_MINBITS:
901 			act.ipa_apply.ipp_espe_minbits = attrp->spd_attr_value;
902 			break;
903 
904 		case SPD_ATTR_ENCR_MAXBITS:
905 			act.ipa_apply.ipp_espe_maxbits = attrp->spd_attr_value;
906 			break;
907 
908 		case SPD_ATTR_AH_MINBITS:
909 			act.ipa_apply.ipp_ah_minbits = attrp->spd_attr_value;
910 			break;
911 
912 		case SPD_ATTR_AH_MAXBITS:
913 			act.ipa_apply.ipp_ah_maxbits = attrp->spd_attr_value;
914 			break;
915 
916 		case SPD_ATTR_ESPA_MINBITS:
917 			act.ipa_apply.ipp_espa_minbits = attrp->spd_attr_value;
918 			break;
919 
920 		case SPD_ATTR_ESPA_MAXBITS:
921 			act.ipa_apply.ipp_espa_maxbits = attrp->spd_attr_value;
922 			break;
923 
924 		case SPD_ATTR_LIFE_SOFT_TIME:
925 		case SPD_ATTR_LIFE_HARD_TIME:
926 		case SPD_ATTR_LIFE_SOFT_BYTES:
927 		case SPD_ATTR_LIFE_HARD_BYTES:
928 			break;
929 
930 		case SPD_ATTR_KM_PROTO:
931 			act.ipa_apply.ipp_km_proto = attrp->spd_attr_value;
932 			break;
933 
934 		case SPD_ATTR_KM_COOKIE:
935 			act.ipa_apply.ipp_km_cookie = attrp->spd_attr_value;
936 			break;
937 
938 		case SPD_ATTR_REPLAY_DEPTH:
939 			act.ipa_apply.ipp_replay_depth = attrp->spd_attr_value;
940 			break;
941 		}
942 	}
943 	if (actp != endactp) {
944 		*diag = SPD_DIAGNOSTIC_ADD_WRONG_ACT_COUNT;
945 		goto fail;
946 	}
947 
948 	return (B_TRUE);
949 fail:
950 	ipsec_actvec_free(*actpp, nact);
951 	*actpp = NULL;
952 	return (B_FALSE);
953 }
954 
955 typedef struct
956 {
957 	ipsec_policy_t *pol;
958 	int dir;
959 } tmprule_t;
960 
961 static int
962 mkrule(ipsec_policy_head_t *iph, struct spd_rule *rule,
963     ipsec_selkey_t *sel, ipsec_act_t *actp, int nact, uint_t dir, uint_t af,
964     tmprule_t **rp, uint64_t *index, spd_stack_t *spds)
965 {
966 	ipsec_policy_t *pol;
967 
968 	sel->ipsl_valid &= ~(IPSL_IPV6|IPSL_IPV4);
969 	sel->ipsl_valid |= af;
970 
971 	pol = ipsec_policy_create(sel, actp, nact, rule->spd_rule_priority,
972 	    index, spds->spds_netstack);
973 	if (pol == NULL)
974 		return (ENOMEM);
975 
976 	(*rp)->pol = pol;
977 	(*rp)->dir = dir;
978 	(*rp)++;
979 
980 	if (!ipsec_check_policy(iph, pol, dir))
981 		return (EEXIST);
982 
983 	rule->spd_rule_index = pol->ipsp_index;
984 	return (0);
985 }
986 
987 static int
988 mkrulepair(ipsec_policy_head_t *iph, struct spd_rule *rule,
989     ipsec_selkey_t *sel, ipsec_act_t *actp, int nact, uint_t dir, uint_t afs,
990     tmprule_t **rp, uint64_t *index, spd_stack_t *spds)
991 {
992 	int error;
993 
994 	if (afs & IPSL_IPV4) {
995 		error = mkrule(iph, rule, sel, actp, nact, dir, IPSL_IPV4, rp,
996 		    index, spds);
997 		if (error != 0)
998 			return (error);
999 	}
1000 	if (afs & IPSL_IPV6) {
1001 		error = mkrule(iph, rule, sel, actp, nact, dir, IPSL_IPV6, rp,
1002 		    index, spds);
1003 		if (error != 0)
1004 			return (error);
1005 	}
1006 	return (0);
1007 }
1008 
1009 
1010 static void
1011 spdsock_addrule(queue_t *q, ipsec_policy_head_t *iph, mblk_t *mp,
1012     spd_ext_t **extv, ipsec_tun_pol_t *itp)
1013 {
1014 	ipsec_selkey_t sel;
1015 	ipsec_act_t *actp;
1016 	uint_t nact;
1017 	int diag = 0, error, afs;
1018 	struct spd_rule *rule = (struct spd_rule *)extv[SPD_EXT_RULE];
1019 	tmprule_t rules[4], *rulep = &rules[0];
1020 	boolean_t tunnel_mode, empty_itp, active;
1021 	uint64_t *index = (itp == NULL) ? NULL : &itp->itp_next_policy_index;
1022 	spdsock_t *ss = (spdsock_t *)q->q_ptr;
1023 	spd_stack_t	*spds = ss->spdsock_spds;
1024 
1025 	if (rule == NULL) {
1026 		spdsock_diag(q, mp, SPD_DIAGNOSTIC_NO_RULE_EXT);
1027 		if (audit_active) {
1028 			spd_msg_t *spmsg = (spd_msg_t *)mp->b_rptr;
1029 			cred_t *cr;
1030 			pid_t cpid;
1031 
1032 			cr = msg_getcred(mp, &cpid);
1033 			active = (spmsg->spd_msg_spdid == SPD_ACTIVE);
1034 			audit_pf_policy(SPD_ADDRULE, cr,
1035 			    spds->spds_netstack, ITP_NAME(itp), active,
1036 			    SPD_DIAGNOSTIC_NO_RULE_EXT, cpid);
1037 		}
1038 		return;
1039 	}
1040 
1041 	tunnel_mode = (rule->spd_rule_flags & SPD_RULE_FLAG_TUNNEL);
1042 
1043 	if (itp != NULL) {
1044 		mutex_enter(&itp->itp_lock);
1045 		ASSERT(itp->itp_policy == iph || itp->itp_inactive == iph);
1046 		active = (itp->itp_policy == iph);
1047 		if (ITP_P_ISACTIVE(itp, iph)) {
1048 			/* Check for mix-and-match of tunnel/transport. */
1049 			if ((tunnel_mode && !ITP_P_ISTUNNEL(itp, iph)) ||
1050 			    (!tunnel_mode && ITP_P_ISTUNNEL(itp, iph))) {
1051 				mutex_exit(&itp->itp_lock);
1052 				spdsock_error(q, mp, EBUSY, 0);
1053 				return;
1054 			}
1055 			empty_itp = B_FALSE;
1056 		} else {
1057 			empty_itp = B_TRUE;
1058 			itp->itp_flags = active ? ITPF_P_ACTIVE : ITPF_I_ACTIVE;
1059 			if (tunnel_mode)
1060 				itp->itp_flags |= active ? ITPF_P_TUNNEL :
1061 				    ITPF_I_TUNNEL;
1062 		}
1063 	} else {
1064 		empty_itp = B_FALSE;
1065 	}
1066 
1067 	if (rule->spd_rule_index != 0) {
1068 		diag = SPD_DIAGNOSTIC_INVALID_RULE_INDEX;
1069 		error = EINVAL;
1070 		goto fail2;
1071 	}
1072 
1073 	if (!spdsock_ext_to_sel(extv, &sel, &diag)) {
1074 		error = EINVAL;
1075 		goto fail2;
1076 	}
1077 
1078 	if (itp != NULL) {
1079 		if (tunnel_mode) {
1080 			if (sel.ipsl_valid &
1081 			    (IPSL_REMOTE_PORT | IPSL_LOCAL_PORT)) {
1082 				itp->itp_flags |= active ?
1083 				    ITPF_P_PER_PORT_SECURITY :
1084 				    ITPF_I_PER_PORT_SECURITY;
1085 			}
1086 		} else {
1087 			/*
1088 			 * For now, we don't allow transport-mode on a tunnel
1089 			 * with ANY specific selectors.  Bail if we have such
1090 			 * a request.
1091 			 */
1092 			if (sel.ipsl_valid & IPSL_WILDCARD) {
1093 				diag = SPD_DIAGNOSTIC_NO_TUNNEL_SELECTORS;
1094 				error = EINVAL;
1095 				goto fail2;
1096 			}
1097 		}
1098 	}
1099 
1100 	if (!spdsock_ext_to_actvec(extv, &actp, &nact, &diag, spds)) {
1101 		error = EINVAL;
1102 		goto fail2;
1103 	}
1104 	/*
1105 	 * If no addresses were specified, add both.
1106 	 */
1107 	afs = sel.ipsl_valid & (IPSL_IPV6|IPSL_IPV4);
1108 	if (afs == 0)
1109 		afs = (IPSL_IPV6|IPSL_IPV4);
1110 
1111 	rw_enter(&iph->iph_lock, RW_WRITER);
1112 
1113 	if (rule->spd_rule_flags & SPD_RULE_FLAG_OUTBOUND) {
1114 		error = mkrulepair(iph, rule, &sel, actp, nact,
1115 		    IPSEC_TYPE_OUTBOUND, afs, &rulep, index, spds);
1116 		if (error != 0)
1117 			goto fail;
1118 	}
1119 
1120 	if (rule->spd_rule_flags & SPD_RULE_FLAG_INBOUND) {
1121 		error = mkrulepair(iph, rule, &sel, actp, nact,
1122 		    IPSEC_TYPE_INBOUND, afs, &rulep, index, spds);
1123 		if (error != 0)
1124 			goto fail;
1125 	}
1126 
1127 	while ((--rulep) >= &rules[0]) {
1128 		ipsec_enter_policy(iph, rulep->pol, rulep->dir,
1129 		    spds->spds_netstack);
1130 	}
1131 	rw_exit(&iph->iph_lock);
1132 	if (itp != NULL)
1133 		mutex_exit(&itp->itp_lock);
1134 
1135 	ipsec_actvec_free(actp, nact);
1136 	spd_echo(q, mp);
1137 	if (audit_active) {
1138 		spd_msg_t *spmsg = (spd_msg_t *)mp->b_rptr;
1139 		cred_t *cr;
1140 		pid_t cpid;
1141 
1142 		cr = msg_getcred(mp, &cpid);
1143 		active = (spmsg->spd_msg_spdid == SPD_ACTIVE);
1144 		audit_pf_policy(SPD_ADDRULE, cr, spds->spds_netstack,
1145 		    ITP_NAME(itp), active, 0, cpid);
1146 	}
1147 	return;
1148 
1149 fail:
1150 	rw_exit(&iph->iph_lock);
1151 	while ((--rulep) >= &rules[0]) {
1152 		IPPOL_REFRELE(rulep->pol, spds->spds_netstack);
1153 	}
1154 	ipsec_actvec_free(actp, nact);
1155 fail2:
1156 	if (itp != NULL) {
1157 		if (empty_itp)
1158 			itp->itp_flags = 0;
1159 		mutex_exit(&itp->itp_lock);
1160 	}
1161 	spdsock_error(q, mp, error, diag);
1162 	if (audit_active) {
1163 		spd_msg_t *spmsg = (spd_msg_t *)mp->b_rptr;
1164 		cred_t *cr;
1165 		pid_t cpid;
1166 
1167 		cr = msg_getcred(mp, &cpid);
1168 		active = (spmsg->spd_msg_spdid == SPD_ACTIVE);
1169 		audit_pf_policy(SPD_ADDRULE, cr, spds->spds_netstack,
1170 		    ITP_NAME(itp), active, error, cpid);
1171 	}
1172 }
1173 
1174 void
1175 spdsock_deleterule(queue_t *q, ipsec_policy_head_t *iph, mblk_t *mp,
1176     spd_ext_t **extv, ipsec_tun_pol_t *itp)
1177 {
1178 	ipsec_selkey_t sel;
1179 	struct spd_rule *rule = (struct spd_rule *)extv[SPD_EXT_RULE];
1180 	int err, diag = 0;
1181 	spdsock_t *ss = (spdsock_t *)q->q_ptr;
1182 	netstack_t *ns = ss->spdsock_spds->spds_netstack;
1183 
1184 	if (rule == NULL) {
1185 		spdsock_diag(q, mp, SPD_DIAGNOSTIC_NO_RULE_EXT);
1186 		if (audit_active) {
1187 			boolean_t active;
1188 			spd_msg_t *spmsg = (spd_msg_t *)mp->b_rptr;
1189 			cred_t *cr;
1190 			pid_t cpid;
1191 
1192 			cr = msg_getcred(mp, &cpid);
1193 			active = (spmsg->spd_msg_spdid == SPD_ACTIVE);
1194 			audit_pf_policy(SPD_DELETERULE, cr, ns,
1195 			    ITP_NAME(itp), active, SPD_DIAGNOSTIC_NO_RULE_EXT,
1196 			    cpid);
1197 		}
1198 		return;
1199 	}
1200 
1201 	/*
1202 	 * Must enter itp_lock first to avoid deadlock.  See tun.c's
1203 	 * set_sec_simple() for the other case of itp_lock and iph_lock.
1204 	 */
1205 	if (itp != NULL)
1206 		mutex_enter(&itp->itp_lock);
1207 
1208 	if (rule->spd_rule_index != 0) {
1209 		if (ipsec_policy_delete_index(iph, rule->spd_rule_index, ns) !=
1210 		    0) {
1211 			err = ESRCH;
1212 			goto fail;
1213 		}
1214 	} else {
1215 		if (!spdsock_ext_to_sel(extv, &sel, &diag)) {
1216 			err = EINVAL;	/* diag already set... */
1217 			goto fail;
1218 		}
1219 
1220 		if ((rule->spd_rule_flags & SPD_RULE_FLAG_INBOUND) &&
1221 		    !ipsec_policy_delete(iph, &sel, IPSEC_TYPE_INBOUND, ns)) {
1222 			err = ESRCH;
1223 			goto fail;
1224 		}
1225 
1226 		if ((rule->spd_rule_flags & SPD_RULE_FLAG_OUTBOUND) &&
1227 		    !ipsec_policy_delete(iph, &sel, IPSEC_TYPE_OUTBOUND, ns)) {
1228 			err = ESRCH;
1229 			goto fail;
1230 		}
1231 	}
1232 
1233 	if (itp != NULL) {
1234 		ASSERT(iph == itp->itp_policy || iph == itp->itp_inactive);
1235 		rw_enter(&iph->iph_lock, RW_READER);
1236 		if (avl_numnodes(&iph->iph_rulebyid) == 0) {
1237 			if (iph == itp->itp_policy)
1238 				itp->itp_flags &= ~ITPF_PFLAGS;
1239 			else
1240 				itp->itp_flags &= ~ITPF_IFLAGS;
1241 		}
1242 		/* Can exit locks in any order. */
1243 		rw_exit(&iph->iph_lock);
1244 		mutex_exit(&itp->itp_lock);
1245 	}
1246 	spd_echo(q, mp);
1247 	if (audit_active) {
1248 		boolean_t active;
1249 		spd_msg_t *spmsg = (spd_msg_t *)mp->b_rptr;
1250 		cred_t *cr;
1251 		pid_t cpid;
1252 
1253 		cr = msg_getcred(mp, &cpid);
1254 		active = (spmsg->spd_msg_spdid == SPD_ACTIVE);
1255 		audit_pf_policy(SPD_DELETERULE, cr, ns, ITP_NAME(itp),
1256 		    active, 0, cpid);
1257 	}
1258 	return;
1259 fail:
1260 	if (itp != NULL)
1261 		mutex_exit(&itp->itp_lock);
1262 	spdsock_error(q, mp, err, diag);
1263 	if (audit_active) {
1264 		boolean_t active;
1265 		spd_msg_t *spmsg = (spd_msg_t *)mp->b_rptr;
1266 		cred_t *cr;
1267 		pid_t cpid;
1268 
1269 		cr = msg_getcred(mp, &cpid);
1270 		active = (spmsg->spd_msg_spdid == SPD_ACTIVE);
1271 		audit_pf_policy(SPD_DELETERULE, cr, ns, ITP_NAME(itp),
1272 		    active, err, cpid);
1273 	}
1274 }
1275 
1276 /* Do NOT consume a reference to itp. */
1277 /* ARGSUSED */
1278 static void
1279 spdsock_flip_node(ipsec_tun_pol_t *itp, void *ignoreme, netstack_t *ns)
1280 {
1281 	mutex_enter(&itp->itp_lock);
1282 	ITPF_SWAP(itp->itp_flags);
1283 	ipsec_swap_policy(itp->itp_policy, itp->itp_inactive, ns);
1284 	mutex_exit(&itp->itp_lock);
1285 }
1286 
1287 void
1288 spdsock_flip(queue_t *q, mblk_t *mp, spd_if_t *tunname)
1289 {
1290 	char *tname;
1291 	ipsec_tun_pol_t *itp;
1292 	spdsock_t *ss = (spdsock_t *)q->q_ptr;
1293 	netstack_t *ns = ss->spdsock_spds->spds_netstack;
1294 
1295 	if (tunname != NULL) {
1296 		tname = (char *)tunname->spd_if_name;
1297 		if (*tname == '\0') {
1298 			/* can't fail */
1299 			ipsec_swap_global_policy(ns);
1300 			if (audit_active) {
1301 				boolean_t active;
1302 				spd_msg_t *spmsg = (spd_msg_t *)mp->b_rptr;
1303 				cred_t *cr;
1304 				pid_t cpid;
1305 
1306 				cr = msg_getcred(mp, &cpid);
1307 				active = (spmsg->spd_msg_spdid == SPD_ACTIVE);
1308 				audit_pf_policy(SPD_FLIP, cr, ns,
1309 				    NULL, active, 0, cpid);
1310 			}
1311 			itp_walk(spdsock_flip_node, NULL, ns);
1312 			if (audit_active) {
1313 				boolean_t active;
1314 				spd_msg_t *spmsg = (spd_msg_t *)mp->b_rptr;
1315 				cred_t *cr;
1316 				pid_t cpid;
1317 
1318 				cr = msg_getcred(mp, &cpid);
1319 				active = (spmsg->spd_msg_spdid == SPD_ACTIVE);
1320 				audit_pf_policy(SPD_FLIP, cr, ns,
1321 				    "all tunnels", active, 0, cpid);
1322 			}
1323 		} else {
1324 			itp = get_tunnel_policy(tname, ns);
1325 			if (itp == NULL) {
1326 				/* Better idea for "tunnel not found"? */
1327 				spdsock_error(q, mp, ESRCH, 0);
1328 				if (audit_active) {
1329 					boolean_t active;
1330 					spd_msg_t *spmsg =
1331 					    (spd_msg_t *)mp->b_rptr;
1332 					cred_t *cr;
1333 					pid_t cpid;
1334 
1335 					cr = msg_getcred(mp, &cpid);
1336 					active = (spmsg->spd_msg_spdid ==
1337 					    SPD_ACTIVE);
1338 					audit_pf_policy(SPD_FLIP, cr, ns,
1339 					    ITP_NAME(itp), active,
1340 					    ESRCH, cpid);
1341 				}
1342 				return;
1343 			}
1344 			spdsock_flip_node(itp, NULL, NULL);
1345 			if (audit_active) {
1346 				boolean_t active;
1347 				spd_msg_t *spmsg = (spd_msg_t *)mp->b_rptr;
1348 				cred_t *cr;
1349 				pid_t cpid;
1350 
1351 				cr = msg_getcred(mp, &cpid);
1352 				active = (spmsg->spd_msg_spdid == SPD_ACTIVE);
1353 				audit_pf_policy(SPD_FLIP, cr, ns,
1354 				    ITP_NAME(itp), active, 0, cpid);
1355 			}
1356 			ITP_REFRELE(itp, ns);
1357 		}
1358 	} else {
1359 		ipsec_swap_global_policy(ns);	/* can't fail */
1360 		if (audit_active) {
1361 			boolean_t active;
1362 			spd_msg_t *spmsg = (spd_msg_t *)mp->b_rptr;
1363 			cred_t *cr;
1364 			pid_t cpid;
1365 
1366 			cr = msg_getcred(mp, &cpid);
1367 			active = (spmsg->spd_msg_spdid == SPD_ACTIVE);
1368 			audit_pf_policy(SPD_FLIP, cr,
1369 			    ns, NULL, active, 0, cpid);
1370 		}
1371 	}
1372 	spd_echo(q, mp);
1373 }
1374 
1375 /*
1376  * Unimplemented feature
1377  */
1378 /* ARGSUSED */
1379 static void
1380 spdsock_lookup(queue_t *q, ipsec_policy_head_t *iph, mblk_t *mp,
1381     spd_ext_t **extv, ipsec_tun_pol_t *itp)
1382 {
1383 	spdsock_error(q, mp, EINVAL, 0);
1384 }
1385 
1386 
1387 static mblk_t *
1388 spdsock_dump_ruleset(mblk_t *req, ipsec_policy_head_t *iph,
1389     uint32_t count, uint16_t error)
1390 {
1391 	size_t len = sizeof (spd_ruleset_ext_t) + sizeof (spd_msg_t);
1392 	spd_msg_t *msg;
1393 	spd_ruleset_ext_t *ruleset;
1394 	mblk_t *m = allocb(len, BPRI_HI);
1395 
1396 	ASSERT(RW_READ_HELD(&iph->iph_lock));
1397 
1398 	if (m == NULL) {
1399 		return (NULL);
1400 	}
1401 	msg = (spd_msg_t *)m->b_rptr;
1402 	ruleset = (spd_ruleset_ext_t *)(&msg[1]);
1403 
1404 	m->b_wptr = (uint8_t *)&ruleset[1];
1405 
1406 	*msg = *(spd_msg_t *)(req->b_rptr);
1407 	msg->spd_msg_len = SPD_8TO64(len);
1408 	msg->spd_msg_errno = error;
1409 
1410 	ruleset->spd_ruleset_len = SPD_8TO64(sizeof (*ruleset));
1411 	ruleset->spd_ruleset_type = SPD_EXT_RULESET;
1412 	ruleset->spd_ruleset_count = count;
1413 	ruleset->spd_ruleset_version = iph->iph_gen;
1414 	return (m);
1415 }
1416 
1417 static mblk_t *
1418 spdsock_dump_finish(spdsock_t *ss, int error)
1419 {
1420 	mblk_t *m;
1421 	ipsec_policy_head_t *iph = ss->spdsock_dump_head;
1422 	mblk_t *req = ss->spdsock_dump_req;
1423 	netstack_t *ns = ss->spdsock_spds->spds_netstack;
1424 
1425 	rw_enter(&iph->iph_lock, RW_READER);
1426 	m = spdsock_dump_ruleset(req, iph, ss->spdsock_dump_count, error);
1427 	rw_exit(&iph->iph_lock);
1428 	IPPH_REFRELE(iph, ns);
1429 	if (ss->spdsock_itp != NULL) {
1430 		ITP_REFRELE(ss->spdsock_itp, ns);
1431 		ss->spdsock_itp = NULL;
1432 	}
1433 	ss->spdsock_dump_req = NULL;
1434 	freemsg(req);
1435 
1436 	return (m);
1437 }
1438 
1439 /*
1440  * Rule encoding functions.
1441  * We do a two-pass encode.
1442  * If base != NULL, fill in encoded rule part starting at base+offset.
1443  * Always return "offset" plus length of to-be-encoded data.
1444  */
1445 static uint_t
1446 spdsock_encode_typecode(uint8_t *base, uint_t offset, uint8_t type,
1447     uint8_t type_end, uint8_t code, uint8_t code_end)
1448 {
1449 	struct spd_typecode *tcp;
1450 
1451 	ASSERT(ALIGNED64(offset));
1452 
1453 	if (base != NULL) {
1454 		tcp = (struct spd_typecode *)(base + offset);
1455 		tcp->spd_typecode_len = SPD_8TO64(sizeof (*tcp));
1456 		tcp->spd_typecode_exttype = SPD_EXT_ICMP_TYPECODE;
1457 		tcp->spd_typecode_code = code;
1458 		tcp->spd_typecode_type = type;
1459 		tcp->spd_typecode_type_end = type_end;
1460 		tcp->spd_typecode_code_end = code_end;
1461 	}
1462 	offset += sizeof (*tcp);
1463 
1464 	ASSERT(ALIGNED64(offset));
1465 
1466 	return (offset);
1467 }
1468 
1469 static uint_t
1470 spdsock_encode_proto(uint8_t *base, uint_t offset, uint8_t proto)
1471 {
1472 	struct spd_proto *spp;
1473 
1474 	ASSERT(ALIGNED64(offset));
1475 
1476 	if (base != NULL) {
1477 		spp = (struct spd_proto *)(base + offset);
1478 		spp->spd_proto_len = SPD_8TO64(sizeof (*spp));
1479 		spp->spd_proto_exttype = SPD_EXT_PROTO;
1480 		spp->spd_proto_number = proto;
1481 		spp->spd_proto_reserved1 = 0;
1482 		spp->spd_proto_reserved2 = 0;
1483 	}
1484 	offset += sizeof (*spp);
1485 
1486 	ASSERT(ALIGNED64(offset));
1487 
1488 	return (offset);
1489 }
1490 
1491 static uint_t
1492 spdsock_encode_port(uint8_t *base, uint_t offset, uint16_t ext, uint16_t port)
1493 {
1494 	struct spd_portrange *spp;
1495 
1496 	ASSERT(ALIGNED64(offset));
1497 
1498 	if (base != NULL) {
1499 		spp = (struct spd_portrange *)(base + offset);
1500 		spp->spd_ports_len = SPD_8TO64(sizeof (*spp));
1501 		spp->spd_ports_exttype = ext;
1502 		spp->spd_ports_minport = port;
1503 		spp->spd_ports_maxport = port;
1504 	}
1505 	offset += sizeof (*spp);
1506 
1507 	ASSERT(ALIGNED64(offset));
1508 
1509 	return (offset);
1510 }
1511 
1512 static uint_t
1513 spdsock_encode_addr(uint8_t *base, uint_t offset, uint16_t ext,
1514     const ipsec_selkey_t *sel, const ipsec_addr_t *addr, uint_t pfxlen)
1515 {
1516 	struct spd_address *sae;
1517 	ipsec_addr_t *spdaddr;
1518 	uint_t start = offset;
1519 	uint_t addrlen;
1520 	uint_t af;
1521 
1522 	if (sel->ipsl_valid & IPSL_IPV4) {
1523 		af = AF_INET;
1524 		addrlen = IP_ADDR_LEN;
1525 	} else {
1526 		af = AF_INET6;
1527 		addrlen = IPV6_ADDR_LEN;
1528 	}
1529 
1530 	ASSERT(ALIGNED64(offset));
1531 
1532 	if (base != NULL) {
1533 		sae = (struct spd_address *)(base + offset);
1534 		sae->spd_address_exttype = ext;
1535 		sae->spd_address_af = af;
1536 		sae->spd_address_prefixlen = pfxlen;
1537 		sae->spd_address_reserved2 = 0;
1538 
1539 		spdaddr = (ipsec_addr_t *)(&sae[1]);
1540 		bcopy(addr, spdaddr, addrlen);
1541 	}
1542 	offset += sizeof (*sae);
1543 	addrlen = roundup(addrlen, sizeof (uint64_t));
1544 	offset += addrlen;
1545 
1546 	ASSERT(ALIGNED64(offset));
1547 
1548 	if (base != NULL)
1549 		sae->spd_address_len = SPD_8TO64(offset - start);
1550 	return (offset);
1551 }
1552 
1553 static uint_t
1554 spdsock_encode_sel(uint8_t *base, uint_t offset, const ipsec_sel_t *sel)
1555 {
1556 	const ipsec_selkey_t *selkey = &sel->ipsl_key;
1557 
1558 	if (selkey->ipsl_valid & IPSL_PROTOCOL)
1559 		offset = spdsock_encode_proto(base, offset, selkey->ipsl_proto);
1560 	if (selkey->ipsl_valid & IPSL_LOCAL_PORT)
1561 		offset = spdsock_encode_port(base, offset, SPD_EXT_LCLPORT,
1562 		    selkey->ipsl_lport);
1563 	if (selkey->ipsl_valid & IPSL_REMOTE_PORT)
1564 		offset = spdsock_encode_port(base, offset, SPD_EXT_REMPORT,
1565 		    selkey->ipsl_rport);
1566 	if (selkey->ipsl_valid & IPSL_REMOTE_ADDR)
1567 		offset = spdsock_encode_addr(base, offset, SPD_EXT_REMADDR,
1568 		    selkey, &selkey->ipsl_remote, selkey->ipsl_remote_pfxlen);
1569 	if (selkey->ipsl_valid & IPSL_LOCAL_ADDR)
1570 		offset = spdsock_encode_addr(base, offset, SPD_EXT_LCLADDR,
1571 		    selkey, &selkey->ipsl_local, selkey->ipsl_local_pfxlen);
1572 	if (selkey->ipsl_valid & IPSL_ICMP_TYPE) {
1573 		offset = spdsock_encode_typecode(base, offset,
1574 		    selkey->ipsl_icmp_type, selkey->ipsl_icmp_type_end,
1575 		    (selkey->ipsl_valid & IPSL_ICMP_CODE) ?
1576 		    selkey->ipsl_icmp_code : 255,
1577 		    (selkey->ipsl_valid & IPSL_ICMP_CODE) ?
1578 		    selkey->ipsl_icmp_code_end : 255);
1579 	}
1580 	return (offset);
1581 }
1582 
1583 static uint_t
1584 spdsock_encode_actattr(uint8_t *base, uint_t offset, uint32_t tag,
1585     uint32_t value)
1586 {
1587 	struct spd_attribute *attr;
1588 
1589 	ASSERT(ALIGNED64(offset));
1590 
1591 	if (base != NULL) {
1592 		attr = (struct spd_attribute *)(base + offset);
1593 		attr->spd_attr_tag = tag;
1594 		attr->spd_attr_value = value;
1595 	}
1596 	offset += sizeof (struct spd_attribute);
1597 
1598 	ASSERT(ALIGNED64(offset));
1599 
1600 	return (offset);
1601 }
1602 
1603 
1604 #define	EMIT(t, v) offset = spdsock_encode_actattr(base, offset, (t), (v))
1605 
1606 static uint_t
1607 spdsock_encode_action(uint8_t *base, uint_t offset, const ipsec_action_t *ap)
1608 {
1609 	const struct ipsec_act *act = &(ap->ipa_act);
1610 	uint_t flags;
1611 
1612 	EMIT(SPD_ATTR_EMPTY, 0);
1613 	switch (act->ipa_type) {
1614 	case IPSEC_ACT_DISCARD:
1615 	case IPSEC_ACT_REJECT:
1616 		EMIT(SPD_ATTR_TYPE, SPD_ACTTYPE_DROP);
1617 		break;
1618 	case IPSEC_ACT_BYPASS:
1619 	case IPSEC_ACT_CLEAR:
1620 		EMIT(SPD_ATTR_TYPE, SPD_ACTTYPE_PASS);
1621 		break;
1622 
1623 	case IPSEC_ACT_APPLY:
1624 		EMIT(SPD_ATTR_TYPE, SPD_ACTTYPE_IPSEC);
1625 		flags = 0;
1626 		if (act->ipa_apply.ipp_use_ah)
1627 			flags |= SPD_APPLY_AH;
1628 		if (act->ipa_apply.ipp_use_esp)
1629 			flags |= SPD_APPLY_ESP;
1630 		if (act->ipa_apply.ipp_use_espa)
1631 			flags |= SPD_APPLY_ESPA;
1632 		if (act->ipa_apply.ipp_use_se)
1633 			flags |= SPD_APPLY_SE;
1634 		if (act->ipa_apply.ipp_use_unique)
1635 			flags |= SPD_APPLY_UNIQUE;
1636 		EMIT(SPD_ATTR_FLAGS, flags);
1637 		if (flags & SPD_APPLY_AH) {
1638 			EMIT(SPD_ATTR_AH_AUTH, act->ipa_apply.ipp_auth_alg);
1639 			EMIT(SPD_ATTR_AH_MINBITS,
1640 			    act->ipa_apply.ipp_ah_minbits);
1641 			EMIT(SPD_ATTR_AH_MAXBITS,
1642 			    act->ipa_apply.ipp_ah_maxbits);
1643 		}
1644 		if (flags & SPD_APPLY_ESP) {
1645 			EMIT(SPD_ATTR_ESP_ENCR, act->ipa_apply.ipp_encr_alg);
1646 			EMIT(SPD_ATTR_ENCR_MINBITS,
1647 			    act->ipa_apply.ipp_espe_minbits);
1648 			EMIT(SPD_ATTR_ENCR_MAXBITS,
1649 			    act->ipa_apply.ipp_espe_maxbits);
1650 			if (flags & SPD_APPLY_ESPA) {
1651 				EMIT(SPD_ATTR_ESP_AUTH,
1652 				    act->ipa_apply.ipp_esp_auth_alg);
1653 				EMIT(SPD_ATTR_ESPA_MINBITS,
1654 				    act->ipa_apply.ipp_espa_minbits);
1655 				EMIT(SPD_ATTR_ESPA_MAXBITS,
1656 				    act->ipa_apply.ipp_espa_maxbits);
1657 			}
1658 		}
1659 		if (act->ipa_apply.ipp_km_proto != 0)
1660 			EMIT(SPD_ATTR_KM_PROTO, act->ipa_apply.ipp_km_proto);
1661 		if (act->ipa_apply.ipp_km_cookie != 0)
1662 			EMIT(SPD_ATTR_KM_PROTO, act->ipa_apply.ipp_km_cookie);
1663 		if (act->ipa_apply.ipp_replay_depth != 0)
1664 			EMIT(SPD_ATTR_REPLAY_DEPTH,
1665 			    act->ipa_apply.ipp_replay_depth);
1666 		/* Add more here */
1667 		break;
1668 	}
1669 
1670 	return (offset);
1671 }
1672 
1673 static uint_t
1674 spdsock_encode_action_list(uint8_t *base, uint_t offset,
1675     const ipsec_action_t *ap)
1676 {
1677 	struct spd_ext_actions *act;
1678 	uint_t nact = 0;
1679 	uint_t start = offset;
1680 
1681 	ASSERT(ALIGNED64(offset));
1682 
1683 	if (base != NULL) {
1684 		act = (struct spd_ext_actions *)(base + offset);
1685 		act->spd_actions_len = 0;
1686 		act->spd_actions_exttype = SPD_EXT_ACTION;
1687 		act->spd_actions_count = 0;
1688 		act->spd_actions_reserved = 0;
1689 	}
1690 
1691 	offset += sizeof (*act);
1692 
1693 	ASSERT(ALIGNED64(offset));
1694 
1695 	while (ap != NULL) {
1696 		offset = spdsock_encode_action(base, offset, ap);
1697 		ap = ap->ipa_next;
1698 		nact++;
1699 		if (ap != NULL) {
1700 			EMIT(SPD_ATTR_NEXT, 0);
1701 		}
1702 	}
1703 	EMIT(SPD_ATTR_END, 0);
1704 
1705 	ASSERT(ALIGNED64(offset));
1706 
1707 	if (base != NULL) {
1708 		act->spd_actions_count = nact;
1709 		act->spd_actions_len = SPD_8TO64(offset - start);
1710 	}
1711 
1712 	return (offset);
1713 }
1714 
1715 #undef EMIT
1716 
1717 /* ARGSUSED */
1718 static uint_t
1719 spdsock_rule_flags(uint_t dir, uint_t af)
1720 {
1721 	uint_t flags = 0;
1722 
1723 	if (dir == IPSEC_TYPE_INBOUND)
1724 		flags |= SPD_RULE_FLAG_INBOUND;
1725 	if (dir == IPSEC_TYPE_OUTBOUND)
1726 		flags |= SPD_RULE_FLAG_OUTBOUND;
1727 
1728 	return (flags);
1729 }
1730 
1731 
1732 static uint_t
1733 spdsock_encode_rule_head(uint8_t *base, uint_t offset, spd_msg_t *req,
1734     const ipsec_policy_t *rule, uint_t dir, uint_t af, char *name,
1735     boolean_t tunnel)
1736 {
1737 	struct spd_msg *spmsg;
1738 	struct spd_rule *spr;
1739 	spd_if_t *sid;
1740 
1741 	uint_t start = offset;
1742 
1743 	ASSERT(ALIGNED64(offset));
1744 
1745 	if (base != NULL) {
1746 		spmsg = (struct spd_msg *)(base + offset);
1747 		bzero(spmsg, sizeof (*spmsg));
1748 		spmsg->spd_msg_version = PF_POLICY_V1;
1749 		spmsg->spd_msg_type = SPD_DUMP;
1750 		spmsg->spd_msg_seq = req->spd_msg_seq;
1751 		spmsg->spd_msg_pid = req->spd_msg_pid;
1752 	}
1753 	offset += sizeof (struct spd_msg);
1754 
1755 	ASSERT(ALIGNED64(offset));
1756 
1757 	if (base != NULL) {
1758 		spr = (struct spd_rule *)(base + offset);
1759 		spr->spd_rule_type = SPD_EXT_RULE;
1760 		spr->spd_rule_priority = rule->ipsp_prio;
1761 		spr->spd_rule_flags = spdsock_rule_flags(dir, af);
1762 		if (tunnel)
1763 			spr->spd_rule_flags |= SPD_RULE_FLAG_TUNNEL;
1764 		spr->spd_rule_unused = 0;
1765 		spr->spd_rule_len = SPD_8TO64(sizeof (*spr));
1766 		spr->spd_rule_index = rule->ipsp_index;
1767 	}
1768 	offset += sizeof (struct spd_rule);
1769 
1770 	/*
1771 	 * If we have an interface name (i.e. if this policy head came from
1772 	 * a tunnel), add the SPD_EXT_TUN_NAME extension.
1773 	 */
1774 	if (name != NULL) {
1775 
1776 		ASSERT(ALIGNED64(offset));
1777 
1778 		if (base != NULL) {
1779 			sid = (spd_if_t *)(base + offset);
1780 			sid->spd_if_exttype = SPD_EXT_TUN_NAME;
1781 			sid->spd_if_len = SPD_8TO64(sizeof (spd_if_t) +
1782 			    roundup((strlen(name) - 4), 8));
1783 			(void) strlcpy((char *)sid->spd_if_name, name,
1784 			    LIFNAMSIZ);
1785 		}
1786 
1787 		offset += sizeof (spd_if_t) + roundup((strlen(name) - 4), 8);
1788 	}
1789 
1790 	offset = spdsock_encode_sel(base, offset, rule->ipsp_sel);
1791 	offset = spdsock_encode_action_list(base, offset, rule->ipsp_act);
1792 
1793 	ASSERT(ALIGNED64(offset));
1794 
1795 	if (base != NULL) {
1796 		spmsg->spd_msg_len = SPD_8TO64(offset - start);
1797 	}
1798 	return (offset);
1799 }
1800 
1801 /* ARGSUSED */
1802 static mblk_t *
1803 spdsock_encode_rule(mblk_t *req, const ipsec_policy_t *rule,
1804     uint_t dir, uint_t af, char *name, boolean_t tunnel)
1805 {
1806 	mblk_t *m;
1807 	uint_t len;
1808 	spd_msg_t *mreq = (spd_msg_t *)req->b_rptr;
1809 
1810 	/*
1811 	 * Figure out how much space we'll need.
1812 	 */
1813 	len = spdsock_encode_rule_head(NULL, 0, mreq, rule, dir, af, name,
1814 	    tunnel);
1815 
1816 	/*
1817 	 * Allocate mblk.
1818 	 */
1819 	m = allocb(len, BPRI_HI);
1820 	if (m == NULL)
1821 		return (NULL);
1822 
1823 	/*
1824 	 * Fill it in..
1825 	 */
1826 	m->b_wptr = m->b_rptr + len;
1827 	bzero(m->b_rptr, len);
1828 	(void) spdsock_encode_rule_head(m->b_rptr, 0, mreq, rule, dir, af,
1829 	    name, tunnel);
1830 	return (m);
1831 }
1832 
1833 static ipsec_policy_t *
1834 spdsock_dump_next_in_chain(spdsock_t *ss, ipsec_policy_head_t *iph,
1835     ipsec_policy_t *cur)
1836 {
1837 	ASSERT(RW_READ_HELD(&iph->iph_lock));
1838 
1839 	ss->spdsock_dump_count++;
1840 	ss->spdsock_dump_cur_rule = cur->ipsp_hash.hash_next;
1841 	return (cur);
1842 }
1843 
1844 static ipsec_policy_t *
1845 spdsock_dump_next_rule(spdsock_t *ss, ipsec_policy_head_t *iph)
1846 {
1847 	ipsec_policy_t *cur;
1848 	ipsec_policy_root_t *ipr;
1849 	int chain, nchains, type, af;
1850 
1851 	ASSERT(RW_READ_HELD(&iph->iph_lock));
1852 
1853 	cur = ss->spdsock_dump_cur_rule;
1854 
1855 	if (cur != NULL)
1856 		return (spdsock_dump_next_in_chain(ss, iph, cur));
1857 
1858 	type = ss->spdsock_dump_cur_type;
1859 
1860 next:
1861 	chain = ss->spdsock_dump_cur_chain;
1862 	ipr = &iph->iph_root[type];
1863 	nchains = ipr->ipr_nchains;
1864 
1865 	while (chain < nchains) {
1866 		cur = ipr->ipr_hash[chain].hash_head;
1867 		chain++;
1868 		if (cur != NULL) {
1869 			ss->spdsock_dump_cur_chain = chain;
1870 			return (spdsock_dump_next_in_chain(ss, iph, cur));
1871 		}
1872 	}
1873 	ss->spdsock_dump_cur_chain = nchains;
1874 
1875 	af = ss->spdsock_dump_cur_af;
1876 	while (af < IPSEC_NAF) {
1877 		cur = ipr->ipr_nonhash[af];
1878 		af++;
1879 		if (cur != NULL) {
1880 			ss->spdsock_dump_cur_af = af;
1881 			return (spdsock_dump_next_in_chain(ss, iph, cur));
1882 		}
1883 	}
1884 
1885 	type++;
1886 	if (type >= IPSEC_NTYPES)
1887 		return (NULL);
1888 
1889 	ss->spdsock_dump_cur_chain = 0;
1890 	ss->spdsock_dump_cur_type = type;
1891 	ss->spdsock_dump_cur_af = IPSEC_AF_V4;
1892 	goto next;
1893 
1894 }
1895 
1896 /*
1897  * If we're done with one policy head, but have more to go, we iterate through
1898  * another IPsec tunnel policy head (itp).  Return NULL if it is an error
1899  * worthy of returning EAGAIN via PF_POLICY.
1900  */
1901 static ipsec_tun_pol_t *
1902 spdsock_dump_iterate_next_tunnel(spdsock_t *ss, ipsec_stack_t *ipss)
1903 {
1904 	ipsec_tun_pol_t *itp;
1905 
1906 	ASSERT(RW_READ_HELD(&ipss->ipsec_tunnel_policy_lock));
1907 	if (ipss->ipsec_tunnel_policy_gen > ss->spdsock_dump_tun_gen) {
1908 		/* Oops, state of the tunnel polheads changed. */
1909 		itp = NULL;
1910 	} else if (ss->spdsock_itp == NULL) {
1911 		/* Just finished global, find first node. */
1912 		itp = avl_first(&ipss->ipsec_tunnel_policies);
1913 	} else {
1914 		/* We just finished current polhead, find the next one. */
1915 		itp = AVL_NEXT(&ipss->ipsec_tunnel_policies, ss->spdsock_itp);
1916 	}
1917 	if (itp != NULL) {
1918 		ITP_REFHOLD(itp);
1919 	}
1920 	if (ss->spdsock_itp != NULL) {
1921 		ITP_REFRELE(ss->spdsock_itp, ipss->ipsec_netstack);
1922 	}
1923 	ss->spdsock_itp = itp;
1924 	return (itp);
1925 }
1926 
1927 static mblk_t *
1928 spdsock_dump_next_record(spdsock_t *ss)
1929 {
1930 	ipsec_policy_head_t *iph;
1931 	ipsec_policy_t *rule;
1932 	mblk_t *m;
1933 	ipsec_tun_pol_t *itp;
1934 	netstack_t *ns = ss->spdsock_spds->spds_netstack;
1935 	ipsec_stack_t *ipss = ns->netstack_ipsec;
1936 
1937 	iph = ss->spdsock_dump_head;
1938 
1939 	ASSERT(iph != NULL);
1940 
1941 	rw_enter(&iph->iph_lock, RW_READER);
1942 
1943 	if (iph->iph_gen != ss->spdsock_dump_gen) {
1944 		rw_exit(&iph->iph_lock);
1945 		return (spdsock_dump_finish(ss, EAGAIN));
1946 	}
1947 
1948 	while ((rule = spdsock_dump_next_rule(ss, iph)) == NULL) {
1949 		rw_exit(&iph->iph_lock);
1950 		if (--(ss->spdsock_dump_remaining_polheads) == 0)
1951 			return (spdsock_dump_finish(ss, 0));
1952 
1953 
1954 		/*
1955 		 * If we reach here, we have more policy heads (tunnel
1956 		 * entries) to dump.  Let's reset to a new policy head
1957 		 * and get some more rules.
1958 		 *
1959 		 * An empty policy head will have spdsock_dump_next_rule()
1960 		 * return NULL, and we loop (while dropping the number of
1961 		 * remaining polheads).  If we loop to 0, we finish.  We
1962 		 * keep looping until we hit 0 or until we have a rule to
1963 		 * encode.
1964 		 *
1965 		 * NOTE:  No need for ITP_REF*() macros here as we're only
1966 		 * going after and refholding the policy head itself.
1967 		 */
1968 		rw_enter(&ipss->ipsec_tunnel_policy_lock, RW_READER);
1969 		itp = spdsock_dump_iterate_next_tunnel(ss, ipss);
1970 		if (itp == NULL) {
1971 			rw_exit(&ipss->ipsec_tunnel_policy_lock);
1972 			return (spdsock_dump_finish(ss, EAGAIN));
1973 		}
1974 
1975 		/* Reset other spdsock_dump thingies. */
1976 		IPPH_REFRELE(ss->spdsock_dump_head, ns);
1977 		if (ss->spdsock_dump_active) {
1978 			ss->spdsock_dump_tunnel =
1979 			    itp->itp_flags & ITPF_P_TUNNEL;
1980 			iph = itp->itp_policy;
1981 		} else {
1982 			ss->spdsock_dump_tunnel =
1983 			    itp->itp_flags & ITPF_I_TUNNEL;
1984 			iph = itp->itp_inactive;
1985 		}
1986 		IPPH_REFHOLD(iph);
1987 		rw_exit(&ipss->ipsec_tunnel_policy_lock);
1988 
1989 		rw_enter(&iph->iph_lock, RW_READER);
1990 		RESET_SPDSOCK_DUMP_POLHEAD(ss, iph);
1991 	}
1992 
1993 	m = spdsock_encode_rule(ss->spdsock_dump_req, rule,
1994 	    ss->spdsock_dump_cur_type, ss->spdsock_dump_cur_af,
1995 	    (ss->spdsock_itp == NULL) ? NULL : ss->spdsock_itp->itp_name,
1996 	    ss->spdsock_dump_tunnel);
1997 	rw_exit(&iph->iph_lock);
1998 
1999 	if (m == NULL)
2000 		return (spdsock_dump_finish(ss, ENOMEM));
2001 	return (m);
2002 }
2003 
2004 /*
2005  * Dump records until we run into flow-control back-pressure.
2006  */
2007 static void
2008 spdsock_dump_some(queue_t *q, spdsock_t *ss)
2009 {
2010 	mblk_t *m, *dataind;
2011 
2012 	while ((ss->spdsock_dump_req != NULL) && canputnext(q)) {
2013 		m = spdsock_dump_next_record(ss);
2014 		if (m == NULL)
2015 			return;
2016 		dataind = allocb(sizeof (struct T_data_req), BPRI_HI);
2017 		if (dataind == NULL) {
2018 			freemsg(m);
2019 			return;
2020 		}
2021 		dataind->b_cont = m;
2022 		dataind->b_wptr += sizeof (struct T_data_req);
2023 		((struct T_data_ind *)dataind->b_rptr)->PRIM_type = T_DATA_IND;
2024 		((struct T_data_ind *)dataind->b_rptr)->MORE_flag = 0;
2025 		dataind->b_datap->db_type = M_PROTO;
2026 		putnext(q, dataind);
2027 	}
2028 }
2029 
2030 /*
2031  * Start dumping.
2032  * Format a start-of-dump record, and set up the stream and kick the rsrv
2033  * procedure to continue the job..
2034  */
2035 /* ARGSUSED */
2036 static void
2037 spdsock_dump(queue_t *q, ipsec_policy_head_t *iph, mblk_t *mp)
2038 {
2039 	spdsock_t *ss = (spdsock_t *)q->q_ptr;
2040 	netstack_t *ns = ss->spdsock_spds->spds_netstack;
2041 	ipsec_stack_t *ipss = ns->netstack_ipsec;
2042 	mblk_t *mr;
2043 
2044 	/* spdsock_open() already set spdsock_itp to NULL. */
2045 	if (iph == ALL_ACTIVE_POLHEADS || iph == ALL_INACTIVE_POLHEADS) {
2046 		rw_enter(&ipss->ipsec_tunnel_policy_lock, RW_READER);
2047 		ss->spdsock_dump_remaining_polheads = 1 +
2048 		    avl_numnodes(&ipss->ipsec_tunnel_policies);
2049 		ss->spdsock_dump_tun_gen = ipss->ipsec_tunnel_policy_gen;
2050 		rw_exit(&ipss->ipsec_tunnel_policy_lock);
2051 		if (iph == ALL_ACTIVE_POLHEADS) {
2052 			iph = ipsec_system_policy(ns);
2053 			ss->spdsock_dump_active = B_TRUE;
2054 		} else {
2055 			iph = ipsec_inactive_policy(ns);
2056 			ss->spdsock_dump_active = B_FALSE;
2057 		}
2058 		ASSERT(ss->spdsock_itp == NULL);
2059 	} else {
2060 		ss->spdsock_dump_remaining_polheads = 1;
2061 	}
2062 
2063 	rw_enter(&iph->iph_lock, RW_READER);
2064 
2065 	mr = spdsock_dump_ruleset(mp, iph, 0, 0);
2066 
2067 	if (!mr) {
2068 		rw_exit(&iph->iph_lock);
2069 		spdsock_error(q, mp, ENOMEM, 0);
2070 		return;
2071 	}
2072 
2073 	ss->spdsock_dump_req = mp;
2074 	RESET_SPDSOCK_DUMP_POLHEAD(ss, iph);
2075 
2076 	rw_exit(&iph->iph_lock);
2077 
2078 	qreply(q, mr);
2079 	qenable(OTHERQ(q));
2080 }
2081 
2082 /* Do NOT consume a reference to ITP. */
2083 void
2084 spdsock_clone_node(ipsec_tun_pol_t *itp, void *ep, netstack_t *ns)
2085 {
2086 	int *errptr = (int *)ep;
2087 
2088 	if (*errptr != 0)
2089 		return;	/* We've failed already for some reason. */
2090 	mutex_enter(&itp->itp_lock);
2091 	ITPF_CLONE(itp->itp_flags);
2092 	*errptr = ipsec_copy_polhead(itp->itp_policy, itp->itp_inactive, ns);
2093 	mutex_exit(&itp->itp_lock);
2094 }
2095 
2096 void
2097 spdsock_clone(queue_t *q, mblk_t *mp, spd_if_t *tunname)
2098 {
2099 	int error;
2100 	char *tname;
2101 	ipsec_tun_pol_t *itp;
2102 	spdsock_t *ss = (spdsock_t *)q->q_ptr;
2103 	netstack_t *ns = ss->spdsock_spds->spds_netstack;
2104 
2105 	if (tunname != NULL) {
2106 		tname = (char *)tunname->spd_if_name;
2107 		if (*tname == '\0') {
2108 			error = ipsec_clone_system_policy(ns);
2109 			if (audit_active) {
2110 				boolean_t active;
2111 				spd_msg_t *spmsg = (spd_msg_t *)mp->b_rptr;
2112 				cred_t *cr;
2113 				pid_t cpid;
2114 
2115 				cr = msg_getcred(mp, &cpid);
2116 				active = (spmsg->spd_msg_spdid == SPD_ACTIVE);
2117 				audit_pf_policy(SPD_CLONE, cr, ns,
2118 				    NULL, active, error, cpid);
2119 			}
2120 			if (error == 0) {
2121 				itp_walk(spdsock_clone_node, &error, ns);
2122 				if (audit_active) {
2123 					boolean_t active;
2124 					spd_msg_t *spmsg =
2125 					    (spd_msg_t *)mp->b_rptr;
2126 					cred_t *cr;
2127 					pid_t cpid;
2128 
2129 					cr = msg_getcred(mp, &cpid);
2130 					active = (spmsg->spd_msg_spdid ==
2131 					    SPD_ACTIVE);
2132 					audit_pf_policy(SPD_CLONE, cr,
2133 					    ns, "all tunnels", active, 0,
2134 					    cpid);
2135 				}
2136 			}
2137 		} else {
2138 			itp = get_tunnel_policy(tname, ns);
2139 			if (itp == NULL) {
2140 				spdsock_error(q, mp, ENOENT, 0);
2141 				if (audit_active) {
2142 					boolean_t active;
2143 					spd_msg_t *spmsg =
2144 					    (spd_msg_t *)mp->b_rptr;
2145 					cred_t *cr;
2146 					pid_t cpid;
2147 
2148 					cr = msg_getcred(mp, &cpid);
2149 					active = (spmsg->spd_msg_spdid ==
2150 					    SPD_ACTIVE);
2151 					audit_pf_policy(SPD_CLONE, cr,
2152 					    ns, ITP_NAME(itp), active, ENOENT,
2153 					    cpid);
2154 				}
2155 				return;
2156 			}
2157 			spdsock_clone_node(itp, &error, NULL);
2158 			ITP_REFRELE(itp, ns);
2159 			if (audit_active) {
2160 				boolean_t active;
2161 				spd_msg_t *spmsg = (spd_msg_t *)mp->b_rptr;
2162 				cred_t *cr;
2163 				pid_t cpid;
2164 
2165 				cr = msg_getcred(mp, &cpid);
2166 				active = (spmsg->spd_msg_spdid == SPD_ACTIVE);
2167 				audit_pf_policy(SPD_CLONE, cr, ns,
2168 				    ITP_NAME(itp), active, error, cpid);
2169 			}
2170 		}
2171 	} else {
2172 		error = ipsec_clone_system_policy(ns);
2173 		if (audit_active) {
2174 			boolean_t active;
2175 			spd_msg_t *spmsg = (spd_msg_t *)mp->b_rptr;
2176 			cred_t *cr;
2177 			pid_t cpid;
2178 
2179 			cr = msg_getcred(mp, &cpid);
2180 			active = (spmsg->spd_msg_spdid == SPD_ACTIVE);
2181 			audit_pf_policy(SPD_CLONE, cr, ns, NULL,
2182 			    active, error, cpid);
2183 		}
2184 	}
2185 
2186 	if (error != 0)
2187 		spdsock_error(q, mp, error, 0);
2188 	else
2189 		spd_echo(q, mp);
2190 }
2191 
2192 /*
2193  * Process a SPD_ALGLIST request. The caller expects separate alg entries
2194  * for AH authentication, ESP authentication, and ESP encryption.
2195  * The same distinction is then used when setting the min and max key
2196  * sizes when defining policies.
2197  */
2198 
2199 #define	SPDSOCK_AH_AUTH		0
2200 #define	SPDSOCK_ESP_AUTH	1
2201 #define	SPDSOCK_ESP_ENCR	2
2202 #define	SPDSOCK_NTYPES		3
2203 
2204 static const uint_t algattr[SPDSOCK_NTYPES] = {
2205 	SPD_ATTR_AH_AUTH,
2206 	SPD_ATTR_ESP_AUTH,
2207 	SPD_ATTR_ESP_ENCR
2208 };
2209 static const uint_t minbitsattr[SPDSOCK_NTYPES] = {
2210 	SPD_ATTR_AH_MINBITS,
2211 	SPD_ATTR_ESPA_MINBITS,
2212 	SPD_ATTR_ENCR_MINBITS
2213 };
2214 static const uint_t maxbitsattr[SPDSOCK_NTYPES] = {
2215 	SPD_ATTR_AH_MAXBITS,
2216 	SPD_ATTR_ESPA_MAXBITS,
2217 	SPD_ATTR_ENCR_MAXBITS
2218 };
2219 static const uint_t defbitsattr[SPDSOCK_NTYPES] = {
2220 	SPD_ATTR_AH_DEFBITS,
2221 	SPD_ATTR_ESPA_DEFBITS,
2222 	SPD_ATTR_ENCR_DEFBITS
2223 };
2224 static const uint_t incrbitsattr[SPDSOCK_NTYPES] = {
2225 	SPD_ATTR_AH_INCRBITS,
2226 	SPD_ATTR_ESPA_INCRBITS,
2227 	SPD_ATTR_ENCR_INCRBITS
2228 };
2229 
2230 #define	ATTRPERALG	6	/* fixed attributes per algs */
2231 
2232 void
2233 spdsock_alglist(queue_t *q, mblk_t *mp)
2234 {
2235 	uint_t algtype;
2236 	uint_t algidx;
2237 	uint_t algcount;
2238 	uint_t size;
2239 	mblk_t *m;
2240 	uint8_t *cur;
2241 	spd_msg_t *msg;
2242 	struct spd_ext_actions *act;
2243 	struct spd_attribute *attr;
2244 	spdsock_t *ss = (spdsock_t *)q->q_ptr;
2245 	ipsec_stack_t *ipss = ss->spdsock_spds->spds_netstack->netstack_ipsec;
2246 
2247 	mutex_enter(&ipss->ipsec_alg_lock);
2248 	/*
2249 	 * The SPD client expects to receive separate entries for
2250 	 * AH authentication and ESP authentication supported algorithms.
2251 	 *
2252 	 * Don't return the "any" algorithms, if defined, as no
2253 	 * kernel policies can be set for these algorithms.
2254 	 */
2255 	algcount = 2 * ipss->ipsec_nalgs[IPSEC_ALG_AUTH] +
2256 	    ipss->ipsec_nalgs[IPSEC_ALG_ENCR];
2257 
2258 	if (ipss->ipsec_alglists[IPSEC_ALG_AUTH][SADB_AALG_NONE] != NULL)
2259 		algcount--;
2260 	if (ipss->ipsec_alglists[IPSEC_ALG_ENCR][SADB_EALG_NONE] != NULL)
2261 		algcount--;
2262 
2263 	/*
2264 	 * For each algorithm, we encode:
2265 	 * ALG / MINBITS / MAXBITS / DEFBITS / INCRBITS / {END, NEXT}
2266 	 */
2267 
2268 	size = sizeof (spd_msg_t) + sizeof (struct spd_ext_actions) +
2269 	    ATTRPERALG * sizeof (struct spd_attribute) * algcount;
2270 
2271 	ASSERT(ALIGNED64(size));
2272 
2273 	m = allocb(size, BPRI_HI);
2274 	if (m == NULL) {
2275 		mutex_exit(&ipss->ipsec_alg_lock);
2276 		spdsock_error(q, mp, ENOMEM, 0);
2277 		return;
2278 	}
2279 
2280 	m->b_wptr = m->b_rptr + size;
2281 	cur = m->b_rptr;
2282 
2283 	msg = (spd_msg_t *)cur;
2284 	bcopy(mp->b_rptr, cur, sizeof (*msg));
2285 
2286 	msg->spd_msg_len = SPD_8TO64(size);
2287 	msg->spd_msg_errno = 0;
2288 	msg->spd_msg_diagnostic = 0;
2289 
2290 	cur += sizeof (*msg);
2291 
2292 	act = (struct spd_ext_actions *)cur;
2293 	cur += sizeof (*act);
2294 
2295 	act->spd_actions_len = SPD_8TO64(size - sizeof (spd_msg_t));
2296 	act->spd_actions_exttype = SPD_EXT_ACTION;
2297 	act->spd_actions_count = algcount;
2298 	act->spd_actions_reserved = 0;
2299 
2300 	attr = (struct spd_attribute *)cur;
2301 
2302 #define	EMIT(tag, value) {					\
2303 		attr->spd_attr_tag = (tag); 			\
2304 		attr->spd_attr_value = (value); 		\
2305 		attr++;			  			\
2306 	}
2307 
2308 	/*
2309 	 * If you change the number of EMIT's here, change
2310 	 * ATTRPERALG above to match
2311 	 */
2312 #define	EMITALGATTRS(_type) {					\
2313 		EMIT(algattr[_type], algid); 		/* 1 */	\
2314 		EMIT(minbitsattr[_type], minbits);	/* 2 */	\
2315 		EMIT(maxbitsattr[_type], maxbits);	/* 3 */	\
2316 		EMIT(defbitsattr[_type], defbits);	/* 4 */	\
2317 		EMIT(incrbitsattr[_type], incr);	/* 5 */	\
2318 		EMIT(SPD_ATTR_NEXT, 0);			/* 6 */	\
2319 	}
2320 
2321 	for (algtype = 0; algtype < IPSEC_NALGTYPES; algtype++) {
2322 		for (algidx = 0; algidx < ipss->ipsec_nalgs[algtype];
2323 		    algidx++) {
2324 			int algid = ipss->ipsec_sortlist[algtype][algidx];
2325 			ipsec_alginfo_t *alg =
2326 			    ipss->ipsec_alglists[algtype][algid];
2327 			uint_t minbits = alg->alg_minbits;
2328 			uint_t maxbits = alg->alg_maxbits;
2329 			uint_t defbits = alg->alg_default_bits;
2330 			uint_t incr = alg->alg_increment;
2331 
2332 			if (algtype == IPSEC_ALG_AUTH) {
2333 				if (algid == SADB_AALG_NONE)
2334 					continue;
2335 				EMITALGATTRS(SPDSOCK_AH_AUTH);
2336 				EMITALGATTRS(SPDSOCK_ESP_AUTH);
2337 			} else {
2338 				if (algid == SADB_EALG_NONE)
2339 					continue;
2340 				ASSERT(algtype == IPSEC_ALG_ENCR);
2341 				EMITALGATTRS(SPDSOCK_ESP_ENCR);
2342 			}
2343 		}
2344 	}
2345 
2346 	mutex_exit(&ipss->ipsec_alg_lock);
2347 
2348 #undef EMITALGATTRS
2349 #undef EMIT
2350 #undef ATTRPERALG
2351 
2352 	attr--;
2353 	attr->spd_attr_tag = SPD_ATTR_END;
2354 
2355 	freemsg(mp);
2356 	qreply(q, m);
2357 }
2358 
2359 /*
2360  * Process a SPD_DUMPALGS request.
2361  */
2362 
2363 #define	ATTRPERALG	7	/* fixed attributes per algs */
2364 
2365 void
2366 spdsock_dumpalgs(queue_t *q, mblk_t *mp)
2367 {
2368 	uint_t algtype;
2369 	uint_t algidx;
2370 	uint_t size;
2371 	mblk_t *m;
2372 	uint8_t *cur;
2373 	spd_msg_t *msg;
2374 	struct spd_ext_actions *act;
2375 	struct spd_attribute *attr;
2376 	ipsec_alginfo_t *alg;
2377 	uint_t algid;
2378 	uint_t i;
2379 	uint_t alg_size;
2380 	spdsock_t *ss = (spdsock_t *)q->q_ptr;
2381 	ipsec_stack_t *ipss = ss->spdsock_spds->spds_netstack->netstack_ipsec;
2382 
2383 	mutex_enter(&ipss->ipsec_alg_lock);
2384 
2385 	/*
2386 	 * For each algorithm, we encode:
2387 	 * ALG / MINBITS / MAXBITS / DEFBITS / INCRBITS / {END, NEXT}
2388 	 *
2389 	 * ALG_ID / ALG_PROTO / ALG_INCRBITS / ALG_NKEYSIZES / ALG_KEYSIZE*
2390 	 * ALG_NBLOCKSIZES / ALG_BLOCKSIZE* / ALG_MECHNAME / {END, NEXT}
2391 	 */
2392 
2393 	/*
2394 	 * Compute the size of the SPD message.
2395 	 */
2396 	size = sizeof (spd_msg_t) + sizeof (struct spd_ext_actions);
2397 
2398 	for (algtype = 0; algtype < IPSEC_NALGTYPES; algtype++) {
2399 		for (algidx = 0; algidx < ipss->ipsec_nalgs[algtype];
2400 		    algidx++) {
2401 			algid = ipss->ipsec_sortlist[algtype][algidx];
2402 			alg = ipss->ipsec_alglists[algtype][algid];
2403 			alg_size = sizeof (struct spd_attribute) *
2404 			    (ATTRPERALG + alg->alg_nkey_sizes +
2405 			    alg->alg_nblock_sizes) + CRYPTO_MAX_MECH_NAME;
2406 			size += alg_size;
2407 		}
2408 	}
2409 
2410 	ASSERT(ALIGNED64(size));
2411 
2412 	m = allocb(size, BPRI_HI);
2413 	if (m == NULL) {
2414 		mutex_exit(&ipss->ipsec_alg_lock);
2415 		spdsock_error(q, mp, ENOMEM, 0);
2416 		return;
2417 	}
2418 
2419 	m->b_wptr = m->b_rptr + size;
2420 	cur = m->b_rptr;
2421 
2422 	msg = (spd_msg_t *)cur;
2423 	bcopy(mp->b_rptr, cur, sizeof (*msg));
2424 
2425 	msg->spd_msg_len = SPD_8TO64(size);
2426 	msg->spd_msg_errno = 0;
2427 	msg->spd_msg_type = SPD_ALGLIST;
2428 
2429 	msg->spd_msg_diagnostic = 0;
2430 
2431 	cur += sizeof (*msg);
2432 
2433 	act = (struct spd_ext_actions *)cur;
2434 	cur += sizeof (*act);
2435 
2436 	act->spd_actions_len = SPD_8TO64(size - sizeof (spd_msg_t));
2437 	act->spd_actions_exttype = SPD_EXT_ACTION;
2438 	act->spd_actions_count = ipss->ipsec_nalgs[IPSEC_ALG_AUTH] +
2439 	    ipss->ipsec_nalgs[IPSEC_ALG_ENCR];
2440 	act->spd_actions_reserved = 0;
2441 
2442 	/*
2443 	 * If there aren't any algorithms registered, return an empty message.
2444 	 * spdsock_get_ext() knows how to deal with this.
2445 	 */
2446 	if (act->spd_actions_count == 0) {
2447 		act->spd_actions_len = 0;
2448 		mutex_exit(&ipss->ipsec_alg_lock);
2449 		goto error;
2450 	}
2451 
2452 	attr = (struct spd_attribute *)cur;
2453 
2454 #define	EMIT(tag, value) {					\
2455 		attr->spd_attr_tag = (tag); 			\
2456 		attr->spd_attr_value = (value); 		\
2457 		attr++;			  			\
2458 	}
2459 
2460 	for (algtype = 0; algtype < IPSEC_NALGTYPES; algtype++) {
2461 		for (algidx = 0; algidx < ipss->ipsec_nalgs[algtype];
2462 		    algidx++) {
2463 
2464 			algid = ipss->ipsec_sortlist[algtype][algidx];
2465 			alg = ipss->ipsec_alglists[algtype][algid];
2466 
2467 			/*
2468 			 * If you change the number of EMIT's here, change
2469 			 * ATTRPERALG above to match
2470 			 */
2471 			EMIT(SPD_ATTR_ALG_ID, algid);
2472 			EMIT(SPD_ATTR_ALG_PROTO, algproto[algtype]);
2473 			EMIT(SPD_ATTR_ALG_INCRBITS, alg->alg_increment);
2474 
2475 			EMIT(SPD_ATTR_ALG_NKEYSIZES, alg->alg_nkey_sizes);
2476 			for (i = 0; i < alg->alg_nkey_sizes; i++)
2477 				EMIT(SPD_ATTR_ALG_KEYSIZE,
2478 				    alg->alg_key_sizes[i]);
2479 
2480 			EMIT(SPD_ATTR_ALG_NBLOCKSIZES, alg->alg_nblock_sizes);
2481 			for (i = 0; i < alg->alg_nblock_sizes; i++)
2482 				EMIT(SPD_ATTR_ALG_BLOCKSIZE,
2483 				    alg->alg_block_sizes[i]);
2484 
2485 			EMIT(SPD_ATTR_ALG_MECHNAME, CRYPTO_MAX_MECH_NAME);
2486 			bcopy(alg->alg_mech_name, attr, CRYPTO_MAX_MECH_NAME);
2487 			attr = (struct spd_attribute *)((char *)attr +
2488 			    CRYPTO_MAX_MECH_NAME);
2489 
2490 			EMIT(SPD_ATTR_NEXT, 0);
2491 		}
2492 	}
2493 
2494 	mutex_exit(&ipss->ipsec_alg_lock);
2495 
2496 #undef EMITALGATTRS
2497 #undef EMIT
2498 #undef ATTRPERALG
2499 
2500 	attr--;
2501 	attr->spd_attr_tag = SPD_ATTR_END;
2502 
2503 error:
2504 	freemsg(mp);
2505 	qreply(q, m);
2506 }
2507 
2508 /*
2509  * Do the actual work of processing an SPD_UPDATEALGS request. Can
2510  * be invoked either once IPsec is loaded on a cached request, or
2511  * when a request is received while IPsec is loaded.
2512  */
2513 static void
2514 spdsock_do_updatealg(spd_ext_t *extv[], int *diag, spd_stack_t *spds)
2515 {
2516 	struct spd_ext_actions *actp;
2517 	struct spd_attribute *attr, *endattr;
2518 	uint64_t *start, *end;
2519 	ipsec_alginfo_t *alg = NULL;
2520 	ipsec_algtype_t alg_type = 0;
2521 	boolean_t skip_alg = B_TRUE, doing_proto = B_FALSE;
2522 	uint_t i, cur_key, cur_block, algid;
2523 
2524 	*diag = -1;
2525 	ASSERT(MUTEX_HELD(&spds->spds_alg_lock));
2526 
2527 	/* parse the message, building the list of algorithms */
2528 
2529 	actp = (struct spd_ext_actions *)extv[SPD_EXT_ACTION];
2530 	if (actp == NULL) {
2531 		*diag = SPD_DIAGNOSTIC_NO_ACTION_EXT;
2532 		return;
2533 	}
2534 
2535 	start = (uint64_t *)actp;
2536 	end = (start + actp->spd_actions_len);
2537 	endattr = (struct spd_attribute *)end;
2538 	attr = (struct spd_attribute *)&actp[1];
2539 
2540 	bzero(spds->spds_algs, IPSEC_NALGTYPES * IPSEC_MAX_ALGS *
2541 	    sizeof (ipsec_alginfo_t *));
2542 
2543 	alg = kmem_zalloc(sizeof (*alg), KM_SLEEP);
2544 
2545 #define	ALG_KEY_SIZES(a)   (((a)->alg_nkey_sizes + 1) * sizeof (uint16_t))
2546 #define	ALG_BLOCK_SIZES(a) (((a)->alg_nblock_sizes + 1) * sizeof (uint16_t))
2547 
2548 	while (attr < endattr) {
2549 		switch (attr->spd_attr_tag) {
2550 		case SPD_ATTR_NOP:
2551 		case SPD_ATTR_EMPTY:
2552 			break;
2553 		case SPD_ATTR_END:
2554 			attr = endattr;
2555 			/* FALLTHRU */
2556 		case SPD_ATTR_NEXT:
2557 			if (doing_proto) {
2558 				doing_proto = B_FALSE;
2559 				break;
2560 			}
2561 			if (skip_alg) {
2562 				ipsec_alg_free(alg);
2563 			} else {
2564 				ipsec_alg_free(
2565 				    spds->spds_algs[alg_type][alg->alg_id]);
2566 				spds->spds_algs[alg_type][alg->alg_id] =
2567 				    alg;
2568 			}
2569 			alg = kmem_zalloc(sizeof (*alg), KM_SLEEP);
2570 			break;
2571 
2572 		case SPD_ATTR_ALG_ID:
2573 			if (attr->spd_attr_value >= IPSEC_MAX_ALGS) {
2574 				ss1dbg(spds, ("spdsock_do_updatealg: "
2575 				    "invalid alg id %d\n",
2576 				    attr->spd_attr_value));
2577 				*diag = SPD_DIAGNOSTIC_ALG_ID_RANGE;
2578 				goto bail;
2579 			}
2580 			alg->alg_id = attr->spd_attr_value;
2581 			break;
2582 
2583 		case SPD_ATTR_ALG_PROTO:
2584 			/* find the alg type */
2585 			for (i = 0; i < NALGPROTOS; i++)
2586 				if (algproto[i] == attr->spd_attr_value)
2587 					break;
2588 			skip_alg = (i == NALGPROTOS);
2589 			if (!skip_alg)
2590 				alg_type = i;
2591 			break;
2592 
2593 		case SPD_ATTR_ALG_INCRBITS:
2594 			alg->alg_increment = attr->spd_attr_value;
2595 			break;
2596 
2597 		case SPD_ATTR_ALG_NKEYSIZES:
2598 			if (alg->alg_key_sizes != NULL) {
2599 				kmem_free(alg->alg_key_sizes,
2600 				    ALG_KEY_SIZES(alg));
2601 			}
2602 			alg->alg_nkey_sizes = attr->spd_attr_value;
2603 			/*
2604 			 * Allocate room for the trailing zero key size
2605 			 * value as well.
2606 			 */
2607 			alg->alg_key_sizes = kmem_zalloc(ALG_KEY_SIZES(alg),
2608 			    KM_SLEEP);
2609 			cur_key = 0;
2610 			break;
2611 
2612 		case SPD_ATTR_ALG_KEYSIZE:
2613 			if (alg->alg_key_sizes == NULL ||
2614 			    cur_key >= alg->alg_nkey_sizes) {
2615 				ss1dbg(spds, ("spdsock_do_updatealg: "
2616 				    "too many key sizes\n"));
2617 				*diag = SPD_DIAGNOSTIC_ALG_NUM_KEY_SIZES;
2618 				goto bail;
2619 			}
2620 			alg->alg_key_sizes[cur_key++] = attr->spd_attr_value;
2621 			break;
2622 
2623 		case SPD_ATTR_ALG_NBLOCKSIZES:
2624 			if (alg->alg_block_sizes != NULL) {
2625 				kmem_free(alg->alg_block_sizes,
2626 				    ALG_BLOCK_SIZES(alg));
2627 			}
2628 			alg->alg_nblock_sizes = attr->spd_attr_value;
2629 			/*
2630 			 * Allocate room for the trailing zero block size
2631 			 * value as well.
2632 			 */
2633 			alg->alg_block_sizes = kmem_zalloc(ALG_BLOCK_SIZES(alg),
2634 			    KM_SLEEP);
2635 			cur_block = 0;
2636 			break;
2637 
2638 		case SPD_ATTR_ALG_BLOCKSIZE:
2639 			if (alg->alg_block_sizes == NULL ||
2640 			    cur_block >= alg->alg_nblock_sizes) {
2641 				ss1dbg(spds, ("spdsock_do_updatealg: "
2642 				    "too many block sizes\n"));
2643 				*diag = SPD_DIAGNOSTIC_ALG_NUM_BLOCK_SIZES;
2644 				goto bail;
2645 			}
2646 			alg->alg_block_sizes[cur_block++] =
2647 			    attr->spd_attr_value;
2648 			break;
2649 
2650 		case SPD_ATTR_ALG_MECHNAME: {
2651 			char *mech_name;
2652 
2653 			if (attr->spd_attr_value > CRYPTO_MAX_MECH_NAME) {
2654 				ss1dbg(spds, ("spdsock_do_updatealg: "
2655 				    "mech name too long\n"));
2656 				*diag = SPD_DIAGNOSTIC_ALG_MECH_NAME_LEN;
2657 				goto bail;
2658 			}
2659 			mech_name = (char *)(attr + 1);
2660 			bcopy(mech_name, alg->alg_mech_name,
2661 			    attr->spd_attr_value);
2662 			alg->alg_mech_name[CRYPTO_MAX_MECH_NAME-1] = '\0';
2663 			attr = (struct spd_attribute *)((char *)attr +
2664 			    attr->spd_attr_value);
2665 			break;
2666 		}
2667 
2668 		case SPD_ATTR_PROTO_ID:
2669 			doing_proto = B_TRUE;
2670 			for (i = 0; i < NALGPROTOS; i++) {
2671 				if (algproto[i] == attr->spd_attr_value) {
2672 					alg_type = i;
2673 					break;
2674 				}
2675 			}
2676 			break;
2677 
2678 		case SPD_ATTR_PROTO_EXEC_MODE:
2679 			if (!doing_proto)
2680 				break;
2681 			for (i = 0; i < NEXECMODES; i++) {
2682 				if (execmodes[i] == attr->spd_attr_value) {
2683 					spds->spds_algs_exec_mode[alg_type] = i;
2684 					break;
2685 				}
2686 			}
2687 			break;
2688 		}
2689 		attr++;
2690 	}
2691 
2692 #undef	ALG_KEY_SIZES
2693 #undef	ALG_BLOCK_SIZES
2694 
2695 	/* update the algorithm tables */
2696 	spdsock_merge_algs(spds);
2697 bail:
2698 	/* cleanup */
2699 	ipsec_alg_free(alg);
2700 	for (alg_type = 0; alg_type < IPSEC_NALGTYPES; alg_type++)
2701 		for (algid = 0; algid < IPSEC_MAX_ALGS; algid++)
2702 		if (spds->spds_algs[alg_type][algid] != NULL)
2703 			ipsec_alg_free(spds->spds_algs[alg_type][algid]);
2704 }
2705 
2706 /*
2707  * Process an SPD_UPDATEALGS request. If IPsec is not loaded, queue
2708  * the request until IPsec loads. If IPsec is loaded, act on it
2709  * immediately.
2710  */
2711 
2712 static void
2713 spdsock_updatealg(queue_t *q, mblk_t *mp, spd_ext_t *extv[])
2714 {
2715 	spdsock_t *ss = (spdsock_t *)q->q_ptr;
2716 	spd_stack_t	*spds = ss->spdsock_spds;
2717 	ipsec_stack_t	*ipss = spds->spds_netstack->netstack_ipsec;
2718 
2719 	if (!ipsec_loaded(ipss)) {
2720 		/*
2721 		 * IPsec is not loaded, save request and return nicely,
2722 		 * the message will be processed once IPsec loads.
2723 		 */
2724 		mblk_t *new_mp;
2725 
2726 		/* last update message wins */
2727 		if ((new_mp = copymsg(mp)) == NULL) {
2728 			spdsock_error(q, mp, ENOMEM, 0);
2729 			return;
2730 		}
2731 		mutex_enter(&spds->spds_alg_lock);
2732 		bcopy(extv, spds->spds_extv_algs,
2733 		    sizeof (spd_ext_t *) * (SPD_EXT_MAX + 1));
2734 		if (spds->spds_mp_algs != NULL)
2735 			freemsg(spds->spds_mp_algs);
2736 		spds->spds_mp_algs = mp;
2737 		spds->spds_algs_pending = B_TRUE;
2738 		mutex_exit(&spds->spds_alg_lock);
2739 		if (audit_active) {
2740 			cred_t *cr;
2741 			pid_t cpid;
2742 
2743 			cr = msg_getcred(mp, &cpid);
2744 			audit_pf_policy(SPD_UPDATEALGS, cr,
2745 			    spds->spds_netstack, NULL, B_TRUE, EAGAIN,
2746 			    cpid);
2747 		}
2748 		spd_echo(q, new_mp);
2749 	} else {
2750 		/*
2751 		 * IPsec is loaded, act on the message immediately.
2752 		 */
2753 		int diag;
2754 
2755 		mutex_enter(&spds->spds_alg_lock);
2756 		spdsock_do_updatealg(extv, &diag, spds);
2757 		mutex_exit(&spds->spds_alg_lock);
2758 		if (diag == -1) {
2759 			spd_echo(q, mp);
2760 			if (audit_active) {
2761 				cred_t *cr;
2762 				pid_t cpid;
2763 
2764 				cr = msg_getcred(mp, &cpid);
2765 				audit_pf_policy(SPD_UPDATEALGS, cr,
2766 				    spds->spds_netstack, NULL, B_TRUE, 0,
2767 				    cpid);
2768 			}
2769 		} else {
2770 			spdsock_diag(q, mp, diag);
2771 			if (audit_active) {
2772 				cred_t *cr;
2773 				pid_t cpid;
2774 
2775 				cr = msg_getcred(mp, &cpid);
2776 				audit_pf_policy(SPD_UPDATEALGS, cr,
2777 				    spds->spds_netstack, NULL, B_TRUE, diag,
2778 				    cpid);
2779 			}
2780 		}
2781 	}
2782 }
2783 
2784 /*
2785  * With a reference-held ill, dig down and find an instance of "tun", and
2786  * assign its tunnel policy pointer, while reference-holding it.  Also,
2787  * release ill's refrence when finished.
2788  *
2789  * We'll be messing with q_next, so be VERY careful.
2790  */
2791 static void
2792 find_tun_and_set_itp(ill_t *ill, ipsec_tun_pol_t *itp)
2793 {
2794 	queue_t *q;
2795 	tun_t *tun;
2796 
2797 	/* Don't bother if this ill is going away. */
2798 	if (ill->ill_flags & ILL_CONDEMNED) {
2799 		ill_refrele(ill);
2800 		return;
2801 	}
2802 
2803 
2804 	q = ill->ill_wq;
2805 	claimstr(q);	/* Lighter-weight than freezestr(). */
2806 
2807 	do {
2808 		/* Use strcmp() because "tun" is bounded. */
2809 		if (strcmp(q->q_qinfo->qi_minfo->mi_idname, "tun") == 0) {
2810 			/* Aha!  Got it. */
2811 			tun = (tun_t *)q->q_ptr;
2812 			if (tun != NULL) {
2813 				mutex_enter(&tun->tun_lock);
2814 				if (tun->tun_itp != itp) {
2815 					ASSERT(tun->tun_itp == NULL);
2816 					ITP_REFHOLD(itp);
2817 					tun->tun_itp = itp;
2818 				}
2819 				mutex_exit(&tun->tun_lock);
2820 				goto release_and_return;
2821 			}
2822 			/*
2823 			 * Else assume this is some other module named "tun"
2824 			 * and move on, hoping we find one that actually has
2825 			 * something in q_ptr.
2826 			 */
2827 		}
2828 		q = q->q_next;
2829 	} while (q != NULL);
2830 
2831 release_and_return:
2832 	releasestr(ill->ill_wq);
2833 	ill_refrele(ill);
2834 }
2835 
2836 /*
2837  * Sort through the mess of polhead options to retrieve an appropriate one.
2838  * Returns NULL if we send an spdsock error.  Returns a valid pointer if we
2839  * found a valid polhead.  Returns ALL_ACTIVE_POLHEADS (aka. -1) or
2840  * ALL_INACTIVE_POLHEADS (aka. -2) if the operation calls for the operation to
2841  * act on ALL policy heads.
2842  */
2843 static ipsec_policy_head_t *
2844 get_appropriate_polhead(queue_t *q, mblk_t *mp, spd_if_t *tunname, int spdid,
2845     int msgtype, ipsec_tun_pol_t **itpp)
2846 {
2847 	ipsec_tun_pol_t *itp;
2848 	ipsec_policy_head_t *iph;
2849 	int errno;
2850 	char *tname;
2851 	boolean_t active;
2852 	spdsock_t *ss = (spdsock_t *)q->q_ptr;
2853 	netstack_t *ns = ss->spdsock_spds->spds_netstack;
2854 	uint64_t gen;	/* Placeholder */
2855 	ill_t *v4, *v6;
2856 
2857 	active = (spdid == SPD_ACTIVE);
2858 	*itpp = NULL;
2859 	if (!active && spdid != SPD_STANDBY) {
2860 		spdsock_diag(q, mp, SPD_DIAGNOSTIC_BAD_SPDID);
2861 		return (NULL);
2862 	}
2863 
2864 	if (tunname != NULL) {
2865 		/* Acting on a tunnel's SPD. */
2866 		tname = (char *)tunname->spd_if_name;
2867 		if (*tname == '\0') {
2868 			/* Handle all-polhead cases here. */
2869 			if (msgtype != SPD_FLUSH && msgtype != SPD_DUMP) {
2870 				spdsock_diag(q, mp,
2871 				    SPD_DIAGNOSTIC_NOT_GLOBAL_OP);
2872 				return (NULL);
2873 			}
2874 			return (active ? ALL_ACTIVE_POLHEADS :
2875 			    ALL_INACTIVE_POLHEADS);
2876 		}
2877 
2878 		itp = get_tunnel_policy(tname, ns);
2879 		if (itp == NULL) {
2880 			if (msgtype != SPD_ADDRULE) {
2881 				/* "Tunnel not found" */
2882 				spdsock_error(q, mp, ENOENT, 0);
2883 				return (NULL);
2884 			}
2885 
2886 			errno = 0;
2887 			itp = create_tunnel_policy(tname, &errno, &gen, ns);
2888 			if (itp == NULL) {
2889 				/*
2890 				 * Something very bad happened, most likely
2891 				 * ENOMEM.  Return an indicator.
2892 				 */
2893 				spdsock_error(q, mp, errno, 0);
2894 				return (NULL);
2895 			}
2896 		}
2897 		/*
2898 		 * Troll the plumbed tunnels and see if we have a
2899 		 * match.  We need to do this always in case we add
2900 		 * policy AFTER plumbing a tunnel.
2901 		 */
2902 		v4 = ill_lookup_on_name(tname, B_FALSE, B_FALSE, NULL,
2903 		    NULL, NULL, &errno, NULL, ns->netstack_ip);
2904 		if (v4 != NULL)
2905 			find_tun_and_set_itp(v4, itp);
2906 		v6 = ill_lookup_on_name(tname, B_FALSE, B_TRUE, NULL,
2907 		    NULL, NULL, &errno, NULL, ns->netstack_ip);
2908 		if (v6 != NULL)
2909 			find_tun_and_set_itp(v6, itp);
2910 		ASSERT(itp != NULL);
2911 		*itpp = itp;
2912 		/* For spdsock dump state, set the polhead's name. */
2913 		if (msgtype == SPD_DUMP) {
2914 			ITP_REFHOLD(itp);
2915 			ss->spdsock_itp = itp;
2916 			ss->spdsock_dump_tunnel = itp->itp_flags &
2917 			    (active ? ITPF_P_TUNNEL : ITPF_I_TUNNEL);
2918 		}
2919 	} else {
2920 		itp = NULL;
2921 		/* For spdsock dump state, indicate it's global policy. */
2922 		if (msgtype == SPD_DUMP)
2923 			ss->spdsock_itp = NULL;
2924 	}
2925 
2926 	if (active)
2927 		iph = (itp == NULL) ? ipsec_system_policy(ns) : itp->itp_policy;
2928 	else
2929 		iph = (itp == NULL) ? ipsec_inactive_policy(ns) :
2930 		    itp->itp_inactive;
2931 
2932 	ASSERT(iph != NULL);
2933 	if (itp != NULL) {
2934 		IPPH_REFHOLD(iph);
2935 	}
2936 
2937 	return (iph);
2938 }
2939 
2940 static void
2941 spdsock_parse(queue_t *q, mblk_t *mp)
2942 {
2943 	spd_msg_t *spmsg;
2944 	spd_ext_t *extv[SPD_EXT_MAX + 1];
2945 	uint_t msgsize;
2946 	ipsec_policy_head_t *iph;
2947 	ipsec_tun_pol_t *itp;
2948 	spd_if_t *tunname;
2949 	spdsock_t *ss = (spdsock_t *)q->q_ptr;
2950 	spd_stack_t *spds = ss->spdsock_spds;
2951 	netstack_t *ns = spds->spds_netstack;
2952 	ipsec_stack_t *ipss = ns->netstack_ipsec;
2953 
2954 	/* Make sure nothing's below me. */
2955 	ASSERT(WR(q)->q_next == NULL);
2956 
2957 	spmsg = (spd_msg_t *)mp->b_rptr;
2958 
2959 	msgsize = SPD_64TO8(spmsg->spd_msg_len);
2960 
2961 	if (msgdsize(mp) != msgsize) {
2962 		/*
2963 		 * Message len incorrect w.r.t. actual size.  Send an error
2964 		 * (EMSGSIZE).	It may be necessary to massage things a
2965 		 * bit.	 For example, if the spd_msg_type is hosed,
2966 		 * I need to set it to SPD_RESERVED to get delivery to
2967 		 * do the right thing.	Then again, maybe just letting
2968 		 * the error delivery do the right thing.
2969 		 */
2970 		ss2dbg(spds,
2971 		    ("mblk (%lu) and base (%d) message sizes don't jibe.\n",
2972 		    msgdsize(mp), msgsize));
2973 		spdsock_error(q, mp, EMSGSIZE, SPD_DIAGNOSTIC_NONE);
2974 		return;
2975 	}
2976 
2977 	if (msgsize > (uint_t)(mp->b_wptr - mp->b_rptr)) {
2978 		/* Get all message into one mblk. */
2979 		if (pullupmsg(mp, -1) == 0) {
2980 			/*
2981 			 * Something screwy happened.
2982 			 */
2983 			ss3dbg(spds, ("spdsock_parse: pullupmsg() failed.\n"));
2984 			return;
2985 		} else {
2986 			spmsg = (spd_msg_t *)mp->b_rptr;
2987 		}
2988 	}
2989 
2990 	switch (spdsock_get_ext(extv, spmsg, msgsize)) {
2991 	case KGE_DUP:
2992 		/* Handle duplicate extension. */
2993 		ss1dbg(spds, ("Got duplicate extension of type %d.\n",
2994 		    extv[0]->spd_ext_type));
2995 		spdsock_diag(q, mp, dup_ext_diag[extv[0]->spd_ext_type]);
2996 		return;
2997 	case KGE_UNK:
2998 		/* Handle unknown extension. */
2999 		ss1dbg(spds, ("Got unknown extension of type %d.\n",
3000 		    extv[0]->spd_ext_type));
3001 		spdsock_diag(q, mp, SPD_DIAGNOSTIC_UNKNOWN_EXT);
3002 		return;
3003 	case KGE_LEN:
3004 		/* Length error. */
3005 		ss1dbg(spds, ("Length %d on extension type %d overrun or 0.\n",
3006 		    extv[0]->spd_ext_len, extv[0]->spd_ext_type));
3007 		spdsock_diag(q, mp, SPD_DIAGNOSTIC_BAD_EXTLEN);
3008 		return;
3009 	case KGE_CHK:
3010 		/* Reality check failed. */
3011 		ss1dbg(spds, ("Reality check failed on extension type %d.\n",
3012 		    extv[0]->spd_ext_type));
3013 		spdsock_diag(q, mp, bad_ext_diag[extv[0]->spd_ext_type]);
3014 		return;
3015 	default:
3016 		/* Default case is no errors. */
3017 		break;
3018 	}
3019 
3020 	/*
3021 	 * Special-case SPD_UPDATEALGS so as not to load IPsec.
3022 	 */
3023 	if (!ipsec_loaded(ipss) && spmsg->spd_msg_type != SPD_UPDATEALGS) {
3024 		spdsock_t *ss = (spdsock_t *)q->q_ptr;
3025 
3026 		ASSERT(ss != NULL);
3027 		ipsec_loader_loadnow(ipss);
3028 		ss->spdsock_timeout_arg = mp;
3029 		ss->spdsock_timeout = qtimeout(q, spdsock_loadcheck,
3030 		    q, LOADCHECK_INTERVAL);
3031 		return;
3032 	}
3033 
3034 	/* First check for messages that need no polheads at all. */
3035 	switch (spmsg->spd_msg_type) {
3036 	case SPD_UPDATEALGS:
3037 		spdsock_updatealg(q, mp, extv);
3038 		return;
3039 	case SPD_ALGLIST:
3040 		spdsock_alglist(q, mp);
3041 		return;
3042 	case SPD_DUMPALGS:
3043 		spdsock_dumpalgs(q, mp);
3044 		return;
3045 	}
3046 
3047 	/*
3048 	 * Then check for ones that need both primary/secondary polheads,
3049 	 * finding the appropriate tunnel policy if need be.
3050 	 */
3051 	tunname = (spd_if_t *)extv[SPD_EXT_TUN_NAME];
3052 	switch (spmsg->spd_msg_type) {
3053 	case SPD_FLIP:
3054 		spdsock_flip(q, mp, tunname);
3055 		return;
3056 	case SPD_CLONE:
3057 		spdsock_clone(q, mp, tunname);
3058 		return;
3059 	}
3060 
3061 	/*
3062 	 * Finally, find ones that operate on exactly one polhead, or
3063 	 * "all polheads" of a given type (active/inactive).
3064 	 */
3065 	iph = get_appropriate_polhead(q, mp, tunname, spmsg->spd_msg_spdid,
3066 	    spmsg->spd_msg_type, &itp);
3067 	if (iph == NULL)
3068 		return;
3069 
3070 	/* All-polheads-ready operations. */
3071 	switch (spmsg->spd_msg_type) {
3072 	case SPD_FLUSH:
3073 		if (itp != NULL) {
3074 			mutex_enter(&itp->itp_lock);
3075 			if (spmsg->spd_msg_spdid == SPD_ACTIVE)
3076 				itp->itp_flags &= ~ITPF_PFLAGS;
3077 			else
3078 				itp->itp_flags &= ~ITPF_IFLAGS;
3079 			mutex_exit(&itp->itp_lock);
3080 			ITP_REFRELE(itp, ns);
3081 		}
3082 		spdsock_flush(q, iph, itp, mp);
3083 		return;
3084 	case SPD_DUMP:
3085 		if (itp != NULL)
3086 			ITP_REFRELE(itp, ns);
3087 		spdsock_dump(q, iph, mp);
3088 		return;
3089 	}
3090 
3091 	if (iph == ALL_ACTIVE_POLHEADS || iph == ALL_INACTIVE_POLHEADS) {
3092 		spdsock_diag(q, mp, SPD_DIAGNOSTIC_NOT_GLOBAL_OP);
3093 		return;
3094 	}
3095 
3096 	/* Single-polhead-only operations. */
3097 	switch (spmsg->spd_msg_type) {
3098 	case SPD_ADDRULE:
3099 		spdsock_addrule(q, iph, mp, extv, itp);
3100 		break;
3101 	case SPD_DELETERULE:
3102 		spdsock_deleterule(q, iph, mp, extv, itp);
3103 		break;
3104 	case SPD_LOOKUP:
3105 		spdsock_lookup(q, iph, mp, extv, itp);
3106 		break;
3107 	default:
3108 		spdsock_diag(q, mp, SPD_DIAGNOSTIC_BAD_MSG_TYPE);
3109 		break;
3110 	}
3111 
3112 	IPPH_REFRELE(iph, ns);
3113 	if (itp != NULL)
3114 		ITP_REFRELE(itp, ns);
3115 }
3116 
3117 /*
3118  * If an algorithm mapping was received before IPsec was loaded, process it.
3119  * Called from the IPsec loader.
3120  */
3121 void
3122 spdsock_update_pending_algs(netstack_t *ns)
3123 {
3124 	spd_stack_t *spds = ns->netstack_spdsock;
3125 
3126 	mutex_enter(&spds->spds_alg_lock);
3127 	if (spds->spds_algs_pending) {
3128 		int diag;
3129 
3130 		spdsock_do_updatealg(spds->spds_extv_algs, &diag,
3131 		    spds);
3132 		spds->spds_algs_pending = B_FALSE;
3133 	}
3134 	mutex_exit(&spds->spds_alg_lock);
3135 }
3136 
3137 static void
3138 spdsock_loadcheck(void *arg)
3139 {
3140 	queue_t *q = (queue_t *)arg;
3141 	spdsock_t *ss = (spdsock_t *)q->q_ptr;
3142 	mblk_t *mp;
3143 	ipsec_stack_t *ipss = ss->spdsock_spds->spds_netstack->netstack_ipsec;
3144 
3145 	ASSERT(ss != NULL);
3146 
3147 	ss->spdsock_timeout = 0;
3148 	mp = ss->spdsock_timeout_arg;
3149 	ASSERT(mp != NULL);
3150 	ss->spdsock_timeout_arg = NULL;
3151 	if (ipsec_failed(ipss))
3152 		spdsock_error(q, mp, EPROTONOSUPPORT, 0);
3153 	else
3154 		spdsock_parse(q, mp);
3155 }
3156 
3157 /*
3158  * Copy relevant state bits.
3159  */
3160 static void
3161 spdsock_copy_info(struct T_info_ack *tap, spdsock_t *ss)
3162 {
3163 	*tap = spdsock_g_t_info_ack;
3164 	tap->CURRENT_state = ss->spdsock_state;
3165 	tap->OPT_size = spdsock_max_optsize;
3166 }
3167 
3168 /*
3169  * This routine responds to T_CAPABILITY_REQ messages.  It is called by
3170  * spdsock_wput.  Much of the T_CAPABILITY_ACK information is copied from
3171  * spdsock_g_t_info_ack.  The current state of the stream is copied from
3172  * spdsock_state.
3173  */
3174 static void
3175 spdsock_capability_req(queue_t *q, mblk_t *mp)
3176 {
3177 	spdsock_t *ss = (spdsock_t *)q->q_ptr;
3178 	t_uscalar_t cap_bits1;
3179 	struct T_capability_ack	*tcap;
3180 
3181 	cap_bits1 = ((struct T_capability_req *)mp->b_rptr)->CAP_bits1;
3182 
3183 	mp = tpi_ack_alloc(mp, sizeof (struct T_capability_ack),
3184 	    mp->b_datap->db_type, T_CAPABILITY_ACK);
3185 	if (mp == NULL)
3186 		return;
3187 
3188 	tcap = (struct T_capability_ack *)mp->b_rptr;
3189 	tcap->CAP_bits1 = 0;
3190 
3191 	if (cap_bits1 & TC1_INFO) {
3192 		spdsock_copy_info(&tcap->INFO_ack, ss);
3193 		tcap->CAP_bits1 |= TC1_INFO;
3194 	}
3195 
3196 	qreply(q, mp);
3197 }
3198 
3199 /*
3200  * This routine responds to T_INFO_REQ messages. It is called by
3201  * spdsock_wput_other.
3202  * Most of the T_INFO_ACK information is copied from spdsock_g_t_info_ack.
3203  * The current state of the stream is copied from spdsock_state.
3204  */
3205 static void
3206 spdsock_info_req(q, mp)
3207 	queue_t	*q;
3208 	mblk_t	*mp;
3209 {
3210 	mp = tpi_ack_alloc(mp, sizeof (struct T_info_ack), M_PCPROTO,
3211 	    T_INFO_ACK);
3212 	if (mp == NULL)
3213 		return;
3214 	spdsock_copy_info((struct T_info_ack *)mp->b_rptr,
3215 	    (spdsock_t *)q->q_ptr);
3216 	qreply(q, mp);
3217 }
3218 
3219 /*
3220  * spdsock_err_ack. This routine creates a
3221  * T_ERROR_ACK message and passes it
3222  * upstream.
3223  */
3224 static void
3225 spdsock_err_ack(q, mp, t_error, sys_error)
3226 	queue_t	*q;
3227 	mblk_t	*mp;
3228 	int	t_error;
3229 	int	sys_error;
3230 {
3231 	if ((mp = mi_tpi_err_ack_alloc(mp, t_error, sys_error)) != NULL)
3232 		qreply(q, mp);
3233 }
3234 
3235 /*
3236  * This routine retrieves the current status of socket options.
3237  * It returns the size of the option retrieved.
3238  */
3239 /* ARGSUSED */
3240 int
3241 spdsock_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
3242 {
3243 	int *i1 = (int *)ptr;
3244 
3245 	switch (level) {
3246 	case SOL_SOCKET:
3247 		switch (name) {
3248 		case SO_TYPE:
3249 			*i1 = SOCK_RAW;
3250 			break;
3251 		/*
3252 		 * The following two items can be manipulated,
3253 		 * but changing them should do nothing.
3254 		 */
3255 		case SO_SNDBUF:
3256 			*i1 = (int)q->q_hiwat;
3257 			break;
3258 		case SO_RCVBUF:
3259 			*i1 = (int)(RD(q)->q_hiwat);
3260 			break;
3261 		}
3262 		break;
3263 	default:
3264 		return (0);
3265 	}
3266 	return (sizeof (int));
3267 }
3268 
3269 /*
3270  * This routine sets socket options.
3271  */
3272 /* ARGSUSED */
3273 int
3274 spdsock_opt_set(queue_t *q, uint_t mgmt_flags, int level, int name,
3275     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
3276     void *thisdg_attrs, cred_t *cr, mblk_t *mblk)
3277 {
3278 	int *i1 = (int *)invalp;
3279 	spdsock_t *ss = (spdsock_t *)q->q_ptr;
3280 	spd_stack_t	*spds = ss->spdsock_spds;
3281 
3282 	switch (level) {
3283 	case SOL_SOCKET:
3284 		switch (name) {
3285 		case SO_SNDBUF:
3286 			if (*i1 > spds->spds_max_buf)
3287 				return (ENOBUFS);
3288 			q->q_hiwat = *i1;
3289 			break;
3290 		case SO_RCVBUF:
3291 			if (*i1 > spds->spds_max_buf)
3292 				return (ENOBUFS);
3293 			RD(q)->q_hiwat = *i1;
3294 			(void) proto_set_rx_hiwat(RD(q), NULL, *i1);
3295 			break;
3296 		}
3297 		break;
3298 	}
3299 	return (0);
3300 }
3301 
3302 
3303 /*
3304  * Handle STREAMS messages.
3305  */
3306 static void
3307 spdsock_wput_other(queue_t *q, mblk_t *mp)
3308 {
3309 	struct iocblk *iocp;
3310 	int error;
3311 	spdsock_t *ss = (spdsock_t *)q->q_ptr;
3312 	spd_stack_t	*spds = ss->spdsock_spds;
3313 	cred_t		*cr;
3314 
3315 	switch (mp->b_datap->db_type) {
3316 	case M_PROTO:
3317 	case M_PCPROTO:
3318 		if ((mp->b_wptr - mp->b_rptr) < sizeof (long)) {
3319 			ss3dbg(spds, (
3320 			    "spdsock_wput_other: Not big enough M_PROTO\n"));
3321 			freemsg(mp);
3322 			return;
3323 		}
3324 		switch (((union T_primitives *)mp->b_rptr)->type) {
3325 		case T_CAPABILITY_REQ:
3326 			spdsock_capability_req(q, mp);
3327 			break;
3328 		case T_INFO_REQ:
3329 			spdsock_info_req(q, mp);
3330 			break;
3331 		case T_SVR4_OPTMGMT_REQ:
3332 		case T_OPTMGMT_REQ:
3333 			/*
3334 			 * All Solaris components should pass a db_credp
3335 			 * for this TPI message, hence we ASSERT.
3336 			 * But in case there is some other M_PROTO that looks
3337 			 * like a TPI message sent by some other kernel
3338 			 * component, we check and return an error.
3339 			 */
3340 			cr = msg_getcred(mp, NULL);
3341 			ASSERT(cr != NULL);
3342 			if (cr == NULL) {
3343 				spdsock_err_ack(q, mp, TSYSERR, EINVAL);
3344 				return;
3345 			}
3346 			if (((union T_primitives *)mp->b_rptr)->type ==
3347 			    T_SVR4_OPTMGMT_REQ) {
3348 				(void) svr4_optcom_req(q, mp, cr,
3349 				    &spdsock_opt_obj, B_FALSE);
3350 			} else {
3351 				(void) tpi_optcom_req(q, mp, cr,
3352 				    &spdsock_opt_obj, B_FALSE);
3353 			}
3354 			break;
3355 		case T_DATA_REQ:
3356 		case T_EXDATA_REQ:
3357 		case T_ORDREL_REQ:
3358 			/* Illegal for spdsock. */
3359 			freemsg(mp);
3360 			(void) putnextctl1(RD(q), M_ERROR, EPROTO);
3361 			break;
3362 		default:
3363 			/* Not supported by spdsock. */
3364 			spdsock_err_ack(q, mp, TNOTSUPPORT, 0);
3365 			break;
3366 		}
3367 		return;
3368 	case M_IOCTL:
3369 		iocp = (struct iocblk *)mp->b_rptr;
3370 		error = EINVAL;
3371 
3372 		switch (iocp->ioc_cmd) {
3373 		case ND_SET:
3374 		case ND_GET:
3375 			if (nd_getset(q, spds->spds_g_nd, mp)) {
3376 				qreply(q, mp);
3377 				return;
3378 			} else
3379 				error = ENOENT;
3380 			/* FALLTHRU */
3381 		default:
3382 			miocnak(q, mp, 0, error);
3383 			return;
3384 		}
3385 	case M_FLUSH:
3386 		if (*mp->b_rptr & FLUSHW) {
3387 			flushq(q, FLUSHALL);
3388 			*mp->b_rptr &= ~FLUSHW;
3389 		}
3390 		if (*mp->b_rptr & FLUSHR) {
3391 			qreply(q, mp);
3392 			return;
3393 		}
3394 		/* Else FALLTHRU */
3395 	}
3396 
3397 	/* If fell through, just black-hole the message. */
3398 	freemsg(mp);
3399 }
3400 
3401 static void
3402 spdsock_wput(queue_t *q, mblk_t *mp)
3403 {
3404 	uint8_t *rptr = mp->b_rptr;
3405 	mblk_t *mp1;
3406 	spdsock_t *ss = (spdsock_t *)q->q_ptr;
3407 	spd_stack_t	*spds = ss->spdsock_spds;
3408 
3409 	/*
3410 	 * If we're dumping, defer processing other messages until the
3411 	 * dump completes.
3412 	 */
3413 	if (ss->spdsock_dump_req != NULL) {
3414 		if (!putq(q, mp))
3415 			freemsg(mp);
3416 		return;
3417 	}
3418 
3419 	switch (mp->b_datap->db_type) {
3420 	case M_DATA:
3421 		/*
3422 		 * Silently discard.
3423 		 */
3424 		ss2dbg(spds, ("raw M_DATA in spdsock.\n"));
3425 		freemsg(mp);
3426 		return;
3427 	case M_PROTO:
3428 	case M_PCPROTO:
3429 		if ((mp->b_wptr - rptr) >= sizeof (struct T_data_req)) {
3430 			if (((union T_primitives *)rptr)->type == T_DATA_REQ) {
3431 				if ((mp1 = mp->b_cont) == NULL) {
3432 					/* No data after T_DATA_REQ. */
3433 					ss2dbg(spds,
3434 					    ("No data after DATA_REQ.\n"));
3435 					freemsg(mp);
3436 					return;
3437 				}
3438 				freeb(mp);
3439 				mp = mp1;
3440 				ss2dbg(spds, ("T_DATA_REQ\n"));
3441 				break;	/* Out of switch. */
3442 			}
3443 		}
3444 		/* FALLTHRU */
3445 	default:
3446 		ss3dbg(spds, ("In default wput case (%d %d).\n",
3447 		    mp->b_datap->db_type, ((union T_primitives *)rptr)->type));
3448 		spdsock_wput_other(q, mp);
3449 		return;
3450 	}
3451 
3452 	/* I now have a PF_POLICY message in an M_DATA block. */
3453 	spdsock_parse(q, mp);
3454 }
3455 
3456 /*
3457  * Device open procedure, called when new queue pair created.
3458  * We are passed the read-side queue.
3459  */
3460 /* ARGSUSED */
3461 static int
3462 spdsock_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
3463 {
3464 	spdsock_t *ss;
3465 	queue_t *oq = OTHERQ(q);
3466 	minor_t ssminor;
3467 	netstack_t *ns;
3468 	spd_stack_t *spds;
3469 
3470 	if (secpolicy_ip_config(credp, B_FALSE) != 0)
3471 		return (EPERM);
3472 
3473 	if (q->q_ptr != NULL)
3474 		return (0);  /* Re-open of an already open instance. */
3475 
3476 	if (sflag & MODOPEN)
3477 		return (EINVAL);
3478 
3479 	ns = netstack_find_by_cred(credp);
3480 	ASSERT(ns != NULL);
3481 	spds = ns->netstack_spdsock;
3482 	ASSERT(spds != NULL);
3483 
3484 	ss2dbg(spds, ("Made it into PF_POLICY socket open.\n"));
3485 
3486 	ssminor = (minor_t)(uintptr_t)vmem_alloc(spdsock_vmem, 1, VM_NOSLEEP);
3487 	if (ssminor == 0) {
3488 		netstack_rele(spds->spds_netstack);
3489 		return (ENOMEM);
3490 	}
3491 	ss = kmem_zalloc(sizeof (spdsock_t), KM_NOSLEEP);
3492 	if (ss == NULL) {
3493 		vmem_free(spdsock_vmem, (void *)(uintptr_t)ssminor, 1);
3494 		netstack_rele(spds->spds_netstack);
3495 		return (ENOMEM);
3496 	}
3497 
3498 	ss->spdsock_minor = ssminor;
3499 	ss->spdsock_state = TS_UNBND;
3500 	ss->spdsock_dump_req = NULL;
3501 
3502 	ss->spdsock_spds = spds;
3503 
3504 	q->q_ptr = ss;
3505 	oq->q_ptr = ss;
3506 
3507 	q->q_hiwat = spds->spds_recv_hiwat;
3508 
3509 	oq->q_hiwat = spds->spds_xmit_hiwat;
3510 	oq->q_lowat = spds->spds_xmit_lowat;
3511 
3512 	qprocson(q);
3513 	(void) proto_set_rx_hiwat(q, NULL, spds->spds_recv_hiwat);
3514 
3515 	*devp = makedevice(getmajor(*devp), ss->spdsock_minor);
3516 	return (0);
3517 }
3518 
3519 /*
3520  * Read-side service procedure, invoked when we get back-enabled
3521  * when buffer space becomes available.
3522  *
3523  * Dump another chunk if we were dumping before; when we finish, kick
3524  * the write-side queue in case it's waiting for read queue space.
3525  */
3526 void
3527 spdsock_rsrv(queue_t *q)
3528 {
3529 	spdsock_t *ss = q->q_ptr;
3530 
3531 	if (ss->spdsock_dump_req != NULL)
3532 		spdsock_dump_some(q, ss);
3533 
3534 	if (ss->spdsock_dump_req == NULL)
3535 		qenable(OTHERQ(q));
3536 }
3537 
3538 /*
3539  * Write-side service procedure, invoked when we defer processing
3540  * if another message is received while a dump is in progress.
3541  */
3542 void
3543 spdsock_wsrv(queue_t *q)
3544 {
3545 	spdsock_t *ss = q->q_ptr;
3546 	mblk_t *mp;
3547 	ipsec_stack_t *ipss = ss->spdsock_spds->spds_netstack->netstack_ipsec;
3548 
3549 	if (ss->spdsock_dump_req != NULL) {
3550 		qenable(OTHERQ(q));
3551 		return;
3552 	}
3553 
3554 	while ((mp = getq(q)) != NULL) {
3555 		if (ipsec_loaded(ipss)) {
3556 			spdsock_wput(q, mp);
3557 			if (ss->spdsock_dump_req != NULL)
3558 				return;
3559 		} else if (!ipsec_failed(ipss)) {
3560 			(void) putq(q, mp);
3561 		} else {
3562 			spdsock_error(q, mp, EPFNOSUPPORT, 0);
3563 		}
3564 	}
3565 }
3566 
3567 static int
3568 spdsock_close(queue_t *q)
3569 {
3570 	spdsock_t *ss = q->q_ptr;
3571 	spd_stack_t	*spds = ss->spdsock_spds;
3572 
3573 	qprocsoff(q);
3574 
3575 	/* Safe assumption. */
3576 	ASSERT(ss != NULL);
3577 
3578 	if (ss->spdsock_timeout != 0)
3579 		(void) quntimeout(q, ss->spdsock_timeout);
3580 
3581 	ss3dbg(spds, ("Driver close, PF_POLICY socket is going away.\n"));
3582 
3583 	vmem_free(spdsock_vmem, (void *)(uintptr_t)ss->spdsock_minor, 1);
3584 	netstack_rele(ss->spdsock_spds->spds_netstack);
3585 
3586 	kmem_free(ss, sizeof (spdsock_t));
3587 	return (0);
3588 }
3589 
3590 /*
3591  * Merge the IPsec algorithms tables with the received algorithm information.
3592  */
3593 void
3594 spdsock_merge_algs(spd_stack_t *spds)
3595 {
3596 	ipsec_alginfo_t *alg, *oalg;
3597 	ipsec_algtype_t algtype;
3598 	uint_t algidx, algid, nalgs;
3599 	crypto_mech_name_t *mechs;
3600 	uint_t mech_count, mech_idx;
3601 	netstack_t	*ns = spds->spds_netstack;
3602 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
3603 
3604 	ASSERT(MUTEX_HELD(&spds->spds_alg_lock));
3605 
3606 	/*
3607 	 * Get the list of supported mechanisms from the crypto framework.
3608 	 * If a mechanism is supported by KCF, resolve its mechanism
3609 	 * id and mark it as being valid. This operation must be done
3610 	 * without holding alg_lock, since it can cause a provider
3611 	 * module to be loaded and the provider notification callback to
3612 	 * be invoked.
3613 	 */
3614 	mechs = crypto_get_mech_list(&mech_count, KM_SLEEP);
3615 	for (algtype = 0; algtype < IPSEC_NALGTYPES; algtype++) {
3616 		for (algid = 0; algid < IPSEC_MAX_ALGS; algid++) {
3617 			int algflags = 0;
3618 			crypto_mech_type_t mt = CRYPTO_MECHANISM_INVALID;
3619 
3620 			alg = spds->spds_algs[algtype][algid];
3621 			if (alg == NULL)
3622 				continue;
3623 
3624 			/*
3625 			 * The NULL encryption algorithm is a special
3626 			 * case because there are no mechanisms, yet
3627 			 * the algorithm is still valid.
3628 			 */
3629 			if (alg->alg_id == SADB_EALG_NULL) {
3630 				alg->alg_mech_type = CRYPTO_MECHANISM_INVALID;
3631 				alg->alg_flags = ALG_FLAG_VALID;
3632 				continue;
3633 			}
3634 
3635 			for (mech_idx = 0; mech_idx < mech_count; mech_idx++) {
3636 				if (strncmp(alg->alg_mech_name, mechs[mech_idx],
3637 				    CRYPTO_MAX_MECH_NAME) == 0) {
3638 					mt = crypto_mech2id(alg->alg_mech_name);
3639 					ASSERT(mt != CRYPTO_MECHANISM_INVALID);
3640 					algflags = ALG_FLAG_VALID;
3641 					break;
3642 				}
3643 			}
3644 			alg->alg_mech_type = mt;
3645 			alg->alg_flags = algflags;
3646 		}
3647 	}
3648 
3649 	mutex_enter(&ipss->ipsec_alg_lock);
3650 
3651 	/*
3652 	 * For each algorithm currently defined, check if it is
3653 	 * present in the new tables created from the SPD_UPDATEALGS
3654 	 * message received from user-space.
3655 	 * Delete the algorithm entries that are currently defined
3656 	 * but not part of the new tables.
3657 	 */
3658 	for (algtype = 0; algtype < IPSEC_NALGTYPES; algtype++) {
3659 		nalgs = ipss->ipsec_nalgs[algtype];
3660 		for (algidx = 0; algidx < nalgs; algidx++) {
3661 			algid = ipss->ipsec_sortlist[algtype][algidx];
3662 			if (spds->spds_algs[algtype][algid] == NULL)
3663 				ipsec_alg_unreg(algtype, algid, ns);
3664 		}
3665 	}
3666 
3667 	/*
3668 	 * For each algorithm we just received, check if it is
3669 	 * present in the currently defined tables. If it is, swap
3670 	 * the entry with the one we just allocated.
3671 	 * If the new algorithm is not in the current tables,
3672 	 * add it.
3673 	 */
3674 	for (algtype = 0; algtype < IPSEC_NALGTYPES; algtype++) {
3675 		for (algid = 0; algid < IPSEC_MAX_ALGS; algid++) {
3676 			alg = spds->spds_algs[algtype][algid];
3677 			if (alg == NULL)
3678 				continue;
3679 
3680 			if ((oalg = ipss->ipsec_alglists[algtype][algid]) ==
3681 			    NULL) {
3682 				/*
3683 				 * New algorithm, add it to the algorithm
3684 				 * table.
3685 				 */
3686 				ipsec_alg_reg(algtype, alg, ns);
3687 			} else {
3688 				/*
3689 				 * Algorithm is already in the table. Swap
3690 				 * the existing entry with the new one.
3691 				 */
3692 				ipsec_alg_fix_min_max(alg, algtype, ns);
3693 				ipss->ipsec_alglists[algtype][algid] = alg;
3694 				ipsec_alg_free(oalg);
3695 			}
3696 			spds->spds_algs[algtype][algid] = NULL;
3697 		}
3698 	}
3699 
3700 	for (algtype = 0; algtype < IPSEC_NALGTYPES; algtype++) {
3701 		ipss->ipsec_algs_exec_mode[algtype] =
3702 		    spds->spds_algs_exec_mode[algtype];
3703 	}
3704 
3705 	mutex_exit(&ipss->ipsec_alg_lock);
3706 
3707 	crypto_free_mech_list(mechs, mech_count);
3708 
3709 	ipsecah_algs_changed(ns);
3710 	ipsecesp_algs_changed(ns);
3711 }
3712