Home | History | Annotate | Download | only in ip
      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 2008 Sun Microsystems, Inc.  All rights reserved.
     23  * Use is subject to license terms.
     24  */
     25 
     26 #pragma ident	"%Z%%M%	%I%	%E% SMI"
     27 
     28 #include <sys/param.h>
     29 #include <sys/types.h>
     30 #include <sys/stream.h>
     31 #include <sys/strsubr.h>
     32 #include <sys/strsun.h>
     33 #include <sys/stropts.h>
     34 #include <sys/zone.h>
     35 #include <sys/vnode.h>
     36 #include <sys/sysmacros.h>
     37 #define	_SUN_TPI_VERSION 2
     38 #include <sys/tihdr.h>
     39 #include <sys/ddi.h>
     40 #include <sys/sunddi.h>
     41 #include <sys/mkdev.h>
     42 #include <sys/debug.h>
     43 #include <sys/kmem.h>
     44 #include <sys/cmn_err.h>
     45 #include <sys/suntpi.h>
     46 #include <sys/policy.h>
     47 
     48 #include <sys/socket.h>
     49 #include <netinet/in.h>
     50 #include <net/pfkeyv2.h>
     51 #include <net/pfpolicy.h>
     52 
     53 #include <inet/common.h>
     54 #include <netinet/ip6.h>
     55 #include <inet/ip.h>
     56 #include <inet/ip6.h>
     57 #include <inet/mi.h>
     58 #include <inet/nd.h>
     59 #include <inet/ip_if.h>
     60 #include <inet/tun.h>
     61 #include <inet/optcom.h>
     62 #include <inet/ipsec_info.h>
     63 #include <inet/ipsec_impl.h>
     64 #include <inet/spdsock.h>
     65 #include <inet/sadb.h>
     66 
     67 #include <sys/isa_defs.h>
     68 
     69 #include <c2/audit.h>
     70 
     71 /*
     72  * This is a transport provider for the PF_POLICY IPsec policy
     73  * management socket, which provides a management interface into the
     74  * SPD, allowing policy rules to be added, deleted, and queried.
     75  *
     76  * This effectively replaces the old private SIOC*IPSECONFIG ioctls
     77  * with an extensible interface which will hopefully be public some
     78  * day.
     79  *
     80  * See <net/pfpolicy.h> for more details on the protocol.
     81  *
     82  * We link against drv/ip and call directly into it to manipulate the
     83  * SPD; see ipsec_impl.h for the policy data structures and spd.c for
     84  * the code which maintains them.
     85  *
     86  * The MT model of this is QPAIR with the addition of some explicit
     87  * locking to protect system-wide policy data structures.
     88  */
     89 
     90 static vmem_t *spdsock_vmem;		/* for minor numbers. */
     91 
     92 #define	ALIGNED64(x) IS_P2ALIGNED((x), sizeof (uint64_t))
     93 
     94 /* Default structure copied into T_INFO_ACK messages (from rts.c...) */
     95 static struct T_info_ack spdsock_g_t_info_ack = {
     96 	T_INFO_ACK,
     97 	T_INFINITE,	/* TSDU_size. Maximum size messages. */
     98 	T_INVALID,	/* ETSDU_size. No expedited data. */
     99 	T_INVALID,	/* CDATA_size. No connect data. */
    100 	T_INVALID,	/* DDATA_size. No disconnect data. */
    101 	0,		/* ADDR_size. */
    102 	0,		/* OPT_size. No user-settable options */
    103 	64 * 1024,	/* TIDU_size. spdsock allows maximum size messages. */
    104 	T_COTS,		/* SERV_type. spdsock supports connection oriented. */
    105 	TS_UNBND,	/* CURRENT_state. This is set from spdsock_state. */
    106 	(XPG4_1)	/* Provider flags */
    107 };
    108 
    109 /* Named Dispatch Parameter Management Structure */
    110 typedef struct spdsockparam_s {
    111 	uint_t	spdsock_param_min;
    112 	uint_t	spdsock_param_max;
    113 	uint_t	spdsock_param_value;
    114 	char *spdsock_param_name;
    115 } spdsockparam_t;
    116 
    117 /*
    118  * Table of NDD variables supported by spdsock. These are loaded into
    119  * spdsock_g_nd in spdsock_init_nd.
    120  * All of these are alterable, within the min/max values given, at run time.
    121  */
    122 static	spdsockparam_t	lcl_param_arr[] = {
    123 	/* min	max	value	name */
    124 	{ 4096, 65536,	8192,	"spdsock_xmit_hiwat"},
    125 	{ 0,	65536,	1024,	"spdsock_xmit_lowat"},
    126 	{ 4096, 65536,	8192,	"spdsock_recv_hiwat"},
    127 	{ 65536, 1024*1024*1024, 256*1024,	"spdsock_max_buf"},
    128 	{ 0,	3,	0,	"spdsock_debug"},
    129 };
    130 #define	spds_xmit_hiwat	spds_params[0].spdsock_param_value
    131 #define	spds_xmit_lowat	spds_params[1].spdsock_param_value
    132 #define	spds_recv_hiwat	spds_params[2].spdsock_param_value
    133 #define	spds_max_buf	spds_params[3].spdsock_param_value
    134 #define	spds_debug		spds_params[4].spdsock_param_value
    135 
    136 #define	ss0dbg(a)	printf a
    137 /* NOTE:  != 0 instead of > 0 so lint doesn't complain. */
    138 #define	ss1dbg(spds, a)	if (spds->spds_debug != 0) printf a
    139 #define	ss2dbg(spds, a)	if (spds->spds_debug > 1) printf a
    140 #define	ss3dbg(spds, a)	if (spds->spds_debug > 2) printf a
    141 
    142 #define	RESET_SPDSOCK_DUMP_POLHEAD(ss, iph) { \
    143 	ASSERT(RW_READ_HELD(&(iph)->iph_lock)); \
    144 	(ss)->spdsock_dump_head = (iph); \
    145 	(ss)->spdsock_dump_gen = (iph)->iph_gen; \
    146 	(ss)->spdsock_dump_cur_type = 0; \
    147 	(ss)->spdsock_dump_cur_af = IPSEC_AF_V4; \
    148 	(ss)->spdsock_dump_cur_rule = NULL; \
    149 	(ss)->spdsock_dump_count = 0; \
    150 	(ss)->spdsock_dump_cur_chain = 0; \
    151 }
    152 
    153 static int spdsock_close(queue_t *);
    154 static int spdsock_open(queue_t *, dev_t *, int, int, cred_t *);
    155 static void spdsock_wput(queue_t *, mblk_t *);
    156 static void spdsock_wsrv(queue_t *);
    157 static void spdsock_rsrv(queue_t *);
    158 static void *spdsock_stack_init(netstackid_t stackid, netstack_t *ns);
    159 static void spdsock_stack_fini(netstackid_t stackid, void *arg);
    160 static void spdsock_loadcheck(void *);
    161 static void spdsock_merge_algs(spd_stack_t *);
    162 static void spdsock_flush_one(ipsec_policy_head_t *, netstack_t *);
    163 static mblk_t *spdsock_dump_next_record(spdsock_t *);
    164 
    165 static struct module_info info = {
    166 	5138, "spdsock", 1, INFPSZ, 512, 128
    167 };
    168 
    169 static struct qinit rinit = {
    170 	NULL, (pfi_t)spdsock_rsrv, spdsock_open, spdsock_close,
    171 	NULL, &info
    172 };
    173 
    174 static struct qinit winit = {
    175 	(pfi_t)spdsock_wput, (pfi_t)spdsock_wsrv, NULL, NULL, NULL, &info
    176 };
    177 
    178 struct streamtab spdsockinfo = {
    179 	&rinit, &winit
    180 };
    181 
    182 /* mapping from alg type to protocol number, as per RFC 2407 */
    183 static const uint_t algproto[] = {
    184 	PROTO_IPSEC_AH,
    185 	PROTO_IPSEC_ESP,
    186 };
    187 
    188 #define	NALGPROTOS	(sizeof (algproto) / sizeof (algproto[0]))
    189 
    190 /* mapping from kernel exec mode to spdsock exec mode */
    191 static const uint_t execmodes[] = {
    192 	SPD_ALG_EXEC_MODE_SYNC,
    193 	SPD_ALG_EXEC_MODE_ASYNC
    194 };
    195 
    196 #define	NEXECMODES	(sizeof (execmodes) / sizeof (execmodes[0]))
    197 
    198 #define	ALL_ACTIVE_POLHEADS ((ipsec_policy_head_t *)-1)
    199 #define	ALL_INACTIVE_POLHEADS ((ipsec_policy_head_t *)-2)
    200 
    201 #define	ITP_NAME(itp) (itp != NULL ? itp->itp_name : NULL)
    202 
    203 /* ARGSUSED */
    204 static int
    205 spdsock_param_get(q, mp, cp, cr)
    206 	queue_t	*q;
    207 	mblk_t	*mp;
    208 	caddr_t	cp;
    209 	cred_t *cr;
    210 {
    211 	spdsockparam_t	*spdsockpa = (spdsockparam_t *)cp;
    212 	uint_t value;
    213 	spdsock_t *ss = (spdsock_t *)q->q_ptr;
    214 	spd_stack_t	*spds = ss->spdsock_spds;
    215 
    216 	mutex_enter(&spds->spds_param_lock);
    217 	value = spdsockpa->spdsock_param_value;
    218 	mutex_exit(&spds->spds_param_lock);
    219 
    220 	(void) mi_mpprintf(mp, "%u", value);
    221 	return (0);
    222 }
    223 
    224 /* This routine sets an NDD variable in a spdsockparam_t structure. */
    225 /* ARGSUSED */
    226 static int
    227 spdsock_param_set(q, mp, value, cp, cr)
    228 	queue_t	*q;
    229 	mblk_t	*mp;
    230 	char *value;
    231 	caddr_t	cp;
    232 	cred_t *cr;
    233 {
    234 	ulong_t	new_value;
    235 	spdsockparam_t	*spdsockpa = (spdsockparam_t *)cp;
    236 	spdsock_t *ss = (spdsock_t *)q->q_ptr;
    237 	spd_stack_t	*spds = ss->spdsock_spds;
    238 
    239 	/* Convert the value from a string into a long integer. */
    240 	if (ddi_strtoul(value, NULL, 10, &new_value) != 0)
    241 		return (EINVAL);
    242 
    243 	mutex_enter(&spds->spds_param_lock);
    244 	/*
    245 	 * Fail the request if the new value does not lie within the
    246 	 * required bounds.
    247 	 */
    248 	if (new_value < spdsockpa->spdsock_param_min ||
    249 	    new_value > spdsockpa->spdsock_param_max) {
    250 		mutex_exit(&spds->spds_param_lock);
    251 		return (EINVAL);
    252 	}
    253 
    254 	/* Set the new value */
    255 	spdsockpa->spdsock_param_value = new_value;
    256 	mutex_exit(&spds->spds_param_lock);
    257 
    258 	return (0);
    259 }
    260 
    261 /*
    262  * Initialize at module load time
    263  */
    264 boolean_t
    265 spdsock_ddi_init(void)
    266 {
    267 	spdsock_max_optsize = optcom_max_optsize(
    268 	    spdsock_opt_obj.odb_opt_des_arr, spdsock_opt_obj.odb_opt_arr_cnt);
    269 
    270 	spdsock_vmem = vmem_create("spdsock", (void *)1, MAXMIN, 1,
    271 	    NULL, NULL, NULL, 1, VM_SLEEP | VMC_IDENTIFIER);
    272 
    273 	/*
    274 	 * We want to be informed each time a stack is created or
    275 	 * destroyed in the kernel, so we can maintain the
    276 	 * set of spd_stack_t's.
    277 	 */
    278 	netstack_register(NS_SPDSOCK, spdsock_stack_init, NULL,
    279 	    spdsock_stack_fini);
    280 
    281 	return (B_TRUE);
    282 }
    283 
    284 /*
    285  * Walk through the param array specified registering each element with the
    286  * named dispatch handler.
    287  */
    288 static boolean_t
    289 spdsock_param_register(IDP *ndp, spdsockparam_t *ssp, int cnt)
    290 {
    291 	for (; cnt-- > 0; ssp++) {
    292 		if (ssp->spdsock_param_name != NULL &&
    293 		    ssp->spdsock_param_name[0]) {
    294 			if (!nd_load(ndp,
    295 			    ssp->spdsock_param_name,
    296 			    spdsock_param_get, spdsock_param_set,
    297 			    (caddr_t)ssp)) {
    298 				nd_free(ndp);
    299 				return (B_FALSE);
    300 			}
    301 		}
    302 	}
    303 	return (B_TRUE);
    304 }
    305 
    306 /*
    307  * Initialize for each stack instance
    308  */
    309 /* ARGSUSED */
    310 static void *
    311 spdsock_stack_init(netstackid_t stackid, netstack_t *ns)
    312 {
    313 	spd_stack_t	*spds;
    314 	spdsockparam_t	*ssp;
    315 
    316 	spds = (spd_stack_t *)kmem_zalloc(sizeof (*spds), KM_SLEEP);
    317 	spds->spds_netstack = ns;
    318 
    319 	ASSERT(spds->spds_g_nd == NULL);
    320 
    321 	ssp = (spdsockparam_t *)kmem_alloc(sizeof (lcl_param_arr), KM_SLEEP);
    322 	spds->spds_params = ssp;
    323 	bcopy(lcl_param_arr, ssp, sizeof (lcl_param_arr));
    324 
    325 	(void) spdsock_param_register(&spds->spds_g_nd, ssp,
    326 	    A_CNT(lcl_param_arr));
    327 
    328 	mutex_init(&spds->spds_param_lock, NULL, MUTEX_DEFAULT, NULL);
    329 	mutex_init(&spds->spds_alg_lock, NULL, MUTEX_DEFAULT, NULL);
    330 
    331 	return (spds);
    332 }
    333 
    334 void
    335 spdsock_ddi_destroy(void)
    336 {
    337 	vmem_destroy(spdsock_vmem);
    338 
    339 	netstack_unregister(NS_SPDSOCK);
    340 }
    341 
    342 /* ARGSUSED */
    343 static void
    344 spdsock_stack_fini(netstackid_t stackid, void *arg)
    345 {
    346 	spd_stack_t *spds = (spd_stack_t *)arg;
    347 
    348 	freemsg(spds->spds_mp_algs);
    349 	mutex_destroy(&spds->spds_param_lock);
    350 	mutex_destroy(&spds->spds_alg_lock);
    351 	nd_free(&spds->spds_g_nd);
    352 	kmem_free(spds->spds_params, sizeof (lcl_param_arr));
    353 	spds->spds_params = NULL;
    354 
    355 	kmem_free(spds, sizeof (*spds));
    356 }
    357 
    358 /*
    359  * NOTE: large quantities of this should be shared with keysock.
    360  * Would be nice to combine some of this into a common module, but
    361  * not possible given time pressures.
    362  */
    363 
    364 /*
    365  * High-level reality checking of extensions.
    366  */
    367 /* ARGSUSED */ /* XXX */
    368 static boolean_t
    369 ext_check(spd_ext_t *ext)
    370 {
    371 	spd_if_t *tunname = (spd_if_t *)ext;
    372 	int i;
    373 	char *idstr;
    374 
    375 	if (ext->spd_ext_type == SPD_EXT_TUN_NAME) {
    376 		/* (NOTE:  Modified from SADB_EXT_IDENTITY..) */
    377 
    378 		/*
    379 		 * Make sure the strings in these identities are
    380 		 * null-terminated.  Let's "proactively" null-terminate the
    381 		 * string at the last byte if it's not terminated sooner.
    382 		 */
    383 		i = SPD_64TO8(tunname->spd_if_len) - sizeof (spd_if_t);
    384 		idstr = (char *)(tunname + 1);
    385 		while (*idstr != '\0' && i > 0) {
    386 			i--;
    387 			idstr++;
    388 		}
    389 		if (i == 0) {
    390 			/*
    391 			 * I.e., if the bozo user didn't NULL-terminate the
    392 			 * string...
    393 			 */
    394 			idstr--;
    395 			*idstr = '\0';
    396 		}
    397 	}
    398 	return (B_TRUE);	/* For now... */
    399 }
    400 
    401 
    402 
    403 /* Return values for spdsock_get_ext(). */
    404 #define	KGE_OK	0
    405 #define	KGE_DUP	1
    406 #define	KGE_UNK	2
    407 #define	KGE_LEN	3
    408 #define	KGE_CHK	4
    409 
    410 /*
    411  * Parse basic extension headers and return in the passed-in pointer vector.
    412  * Return values include:
    413  *
    414  *	KGE_OK	Everything's nice and parsed out.
    415  *		If there are no extensions, place NULL in extv[0].
    416  *	KGE_DUP	There is a duplicate extension.
    417  *		First instance in appropriate bin.  First duplicate in
    418  *		extv[0].
    419  *	KGE_UNK	Unknown extension type encountered.  extv[0] contains
    420  *		unknown header.
    421  *	KGE_LEN	Extension length error.
    422  *	KGE_CHK	High-level reality check failed on specific extension.
    423  *
    424  * My apologies for some of the pointer arithmetic in here.  I'm thinking
    425  * like an assembly programmer, yet trying to make the compiler happy.
    426  */
    427 static int
    428 spdsock_get_ext(spd_ext_t *extv[], spd_msg_t *basehdr, uint_t msgsize)
    429 {
    430 	bzero(extv, sizeof (spd_ext_t *) * (SPD_EXT_MAX + 1));
    431 
    432 	/* Use extv[0] as the "current working pointer". */
    433 
    434 	extv[0] = (spd_ext_t *)(basehdr + 1);
    435 
    436 	while (extv[0] < (spd_ext_t *)(((uint8_t *)basehdr) + msgsize)) {
    437 		/* Check for unknown headers. */
    438 		if (extv[0]->spd_ext_type == 0 ||
    439 		    extv[0]->spd_ext_type > SPD_EXT_MAX)
    440 			return (KGE_UNK);
    441 
    442 		/*
    443 		 * Check length.  Use uint64_t because extlen is in units
    444 		 * of 64-bit words.  If length goes beyond the msgsize,
    445 		 * return an error.  (Zero length also qualifies here.)
    446 		 */
    447 		if (extv[0]->spd_ext_len == 0 ||
    448 		    (void *)((uint64_t *)extv[0] + extv[0]->spd_ext_len) >
    449 		    (void *)((uint8_t *)basehdr + msgsize))
    450 			return (KGE_LEN);
    451 
    452 		/* Check for redundant headers. */
    453 		if (extv[extv[0]->spd_ext_type] != NULL)
    454 			return (KGE_DUP);
    455 
    456 		/*
    457 		 * Reality check the extension if possible at the spdsock
    458 		 * level.
    459 		 */
    460 		if (!ext_check(extv[0]))
    461 			return (KGE_CHK);
    462 
    463 		/* If I make it here, assign the appropriate bin. */
    464 		extv[extv[0]->spd_ext_type] = extv[0];
    465 
    466 		/* Advance pointer (See above for uint64_t ptr reasoning.) */
    467 		extv[0] = (spd_ext_t *)
    468 		    ((uint64_t *)extv[0] + extv[0]->spd_ext_len);
    469 	}
    470 
    471 	/* Everything's cool. */
    472 
    473 	/*
    474 	 * If extv[0] == NULL, then there are no extension headers in this
    475 	 * message.  Ensure that this is the case.
    476 	 */
    477 	if (extv[0] == (spd_ext_t *)(basehdr + 1))
    478 		extv[0] = NULL;
    479 
    480 	return (KGE_OK);
    481 }
    482 
    483 static const int bad_ext_diag[] = {
    484 	SPD_DIAGNOSTIC_MALFORMED_LCLPORT,
    485 	SPD_DIAGNOSTIC_MALFORMED_REMPORT,
    486 	SPD_DIAGNOSTIC_MALFORMED_PROTO,
    487 	SPD_DIAGNOSTIC_MALFORMED_LCLADDR,
    488 	SPD_DIAGNOSTIC_MALFORMED_REMADDR,
    489 	SPD_DIAGNOSTIC_MALFORMED_ACTION,
    490 	SPD_DIAGNOSTIC_MALFORMED_RULE,
    491 	SPD_DIAGNOSTIC_MALFORMED_RULESET,
    492 	SPD_DIAGNOSTIC_MALFORMED_ICMP_TYPECODE
    493 };
    494 
    495 static const int dup_ext_diag[] = {
    496 	SPD_DIAGNOSTIC_DUPLICATE_LCLPORT,
    497 	SPD_DIAGNOSTIC_DUPLICATE_REMPORT,
    498 	SPD_DIAGNOSTIC_DUPLICATE_PROTO,
    499 	SPD_DIAGNOSTIC_DUPLICATE_LCLADDR,
    500 	SPD_DIAGNOSTIC_DUPLICATE_REMADDR,
    501 	SPD_DIAGNOSTIC_DUPLICATE_ACTION,
    502 	SPD_DIAGNOSTIC_DUPLICATE_RULE,
    503 	SPD_DIAGNOSTIC_DUPLICATE_RULESET,
    504 	SPD_DIAGNOSTIC_DUPLICATE_ICMP_TYPECODE
    505 };
    506 
    507 /*
    508  * Transmit a PF_POLICY error message to the instance either pointed to
    509  * by ks, the instance with serial number serial, or more, depending.
    510  *
    511  * The faulty message (or a reasonable facsimile thereof) is in mp.
    512  * This function will free mp or recycle it for delivery, thereby causing
    513  * the stream head to free it.
    514  */
    515 static void
    516 spdsock_error(queue_t *q, mblk_t *mp, int error, int diagnostic)
    517 {
    518 	spd_msg_t *spmsg = (spd_msg_t *)mp->b_rptr;
    519 
    520 	ASSERT(mp->b_datap->db_type == M_DATA);
    521 
    522 	if (spmsg->spd_msg_type < SPD_MIN ||
    523 	    spmsg->spd_msg_type > SPD_MAX)
    524 		spmsg->spd_msg_type = SPD_RESERVED;
    525 
    526 	/*
    527 	 * Strip out extension headers.
    528 	 */
    529 	ASSERT(mp->b_rptr + sizeof (*spmsg) <= mp->b_datap->db_lim);
    530 	mp->b_wptr = mp->b_rptr + sizeof (*spmsg);
    531 	spmsg->spd_msg_len = SPD_8TO64(sizeof (spd_msg_t));
    532 	spmsg->spd_msg_errno = (uint8_t)error;
    533 	spmsg->spd_msg_diagnostic = (uint16_t)diagnostic;
    534 
    535 	qreply(q, mp);
    536 }
    537 
    538 static void
    539 spdsock_diag(queue_t *q, mblk_t *mp, int diagnostic)
    540 {
    541 	spdsock_error(q, mp, EINVAL, diagnostic);
    542 }
    543 
    544 static void
    545 spd_echo(queue_t *q, mblk_t *mp)
    546 {
    547 	qreply(q, mp);
    548 }
    549 
    550 /*
    551  * Do NOT consume a reference to itp.
    552  */
    553 /*ARGSUSED*/
    554 static void
    555 spdsock_flush_node(ipsec_tun_pol_t *itp, void *cookie, netstack_t *ns)
    556 {
    557 	boolean_t active = (boolean_t)cookie;
    558 	ipsec_policy_head_t *iph;
    559 
    560 	iph = active ? itp->itp_policy : itp->itp_inactive;
    561 	IPPH_REFHOLD(iph);
    562 	mutex_enter(&itp->itp_lock);
    563 	spdsock_flush_one(iph, ns);
    564 	if (active)
    565 		itp->itp_flags &= ~ITPF_PFLAGS;
    566 	else
    567 		itp->itp_flags &= ~ITPF_IFLAGS;
    568 	mutex_exit(&itp->itp_lock);
    569 }
    570 
    571 /*
    572  * Clear out one polhead.
    573  */
    574 static void
    575 spdsock_flush_one(ipsec_policy_head_t *iph, netstack_t *ns)
    576 {
    577 	rw_enter(&iph->iph_lock, RW_WRITER);
    578 	ipsec_polhead_flush(iph, ns);
    579 	rw_exit(&iph->iph_lock);
    580 	IPPH_REFRELE(iph, ns);
    581 }
    582 
    583 static void
    584 spdsock_flush(queue_t *q, ipsec_policy_head_t *iph, ipsec_tun_pol_t *itp,
    585     mblk_t *mp)
    586 {
    587 	boolean_t active;
    588 	spdsock_t *ss = (spdsock_t *)q->q_ptr;
    589 	netstack_t *ns = ss->spdsock_spds->spds_netstack;
    590 
    591 	if (iph != ALL_ACTIVE_POLHEADS && iph != ALL_INACTIVE_POLHEADS) {
    592 		spdsock_flush_one(iph, ns);
    593 		if (audit_active) {
    594 			spd_msg_t *spmsg = (spd_msg_t *)mp->b_rptr;
    595 
    596 			active = (spmsg->spd_msg_spdid == SPD_ACTIVE);
    597 			audit_pf_policy(SPD_FLUSH, DB_CRED(mp), ns,
    598 			    ITP_NAME(itp), active, 0, DB_CPID(mp));
    599 		}
    600 	} else {
    601 		active = (iph == ALL_ACTIVE_POLHEADS);
    602 
    603 		/* First flush the global policy. */
    604 		spdsock_flush_one(active ? ipsec_system_policy(ns) :
    605 		    ipsec_inactive_policy(ns), ns);
    606 		if (audit_active) {
    607 			audit_pf_policy(SPD_FLUSH, DB_CRED(mp), ns, NULL,
    608 			    active, 0, DB_CPID(mp));
    609 		}
    610 		/* Then flush every tunnel's appropriate one. */
    611 		itp_walk(spdsock_flush_node, (void *)active, ns);
    612 		if (audit_active)
    613 			audit_pf_policy(SPD_FLUSH, DB_CRED(mp), ns,
    614 			    "all tunnels", active, 0, DB_CPID(mp));
    615 	}
    616 
    617 	spd_echo(q, mp);
    618 }
    619 
    620 static boolean_t
    621 spdsock_ext_to_sel(spd_ext_t **extv, ipsec_selkey_t *sel, int *diag)
    622 {
    623 	bzero(sel, sizeof (*sel));
    624 
    625 	if (extv[SPD_EXT_PROTO] != NULL) {
    626 		struct spd_proto *pr =
    627 		    (struct spd_proto *)extv[SPD_EXT_PROTO];
    628 		sel->ipsl_proto = pr->spd_proto_number;
    629 		sel->ipsl_valid |= IPSL_PROTOCOL;
    630 	}
    631 	if (extv[SPD_EXT_LCLPORT] != NULL) {
    632 		struct spd_portrange *pr =
    633 		    (struct spd_portrange *)extv[SPD_EXT_LCLPORT];
    634 		sel->ipsl_lport = pr->spd_ports_minport;
    635 		sel->ipsl_valid |= IPSL_LOCAL_PORT;
    636 	}
    637 	if (extv[SPD_EXT_REMPORT] != NULL) {
    638 		struct spd_portrange *pr =
    639 		    (struct spd_portrange *)extv[SPD_EXT_REMPORT];
    640 		sel->ipsl_rport = pr->spd_ports_minport;
    641 		sel->ipsl_valid |= IPSL_REMOTE_PORT;
    642 	}
    643 
    644 	if (extv[SPD_EXT_ICMP_TYPECODE] != NULL) {
    645 		struct spd_typecode *tc=
    646 		    (struct spd_typecode *)extv[SPD_EXT_ICMP_TYPECODE];
    647 
    648 		sel->ipsl_valid |= IPSL_ICMP_TYPE;
    649 		sel->ipsl_icmp_type = tc->spd_typecode_type;
    650 		if (tc->spd_typecode_type_end < tc->spd_typecode_type)
    651 			sel->ipsl_icmp_type_end = tc->spd_typecode_type;
    652 		else
    653 			sel->ipsl_icmp_type_end = tc->spd_typecode_type_end;
    654 
    655 		if (tc->spd_typecode_code != 255) {
    656 			sel->ipsl_valid |= IPSL_ICMP_CODE;
    657 			sel->ipsl_icmp_code = tc->spd_typecode_code;
    658 			if (tc->spd_typecode_code_end < tc->spd_typecode_code)
    659 				sel->ipsl_icmp_code_end = tc->spd_typecode_code;
    660 			else
    661 				sel->ipsl_icmp_code_end =
    662 				    tc->spd_typecode_code_end;
    663 		}
    664 	}
    665 #define	ADDR2SEL(sel, extv, field, pfield, extn, bit)			      \
    666 	if ((extv)[(extn)] != NULL) {					      \
    667 		uint_t addrlen;						      \
    668 		struct spd_address *ap = 				      \
    669 			(struct spd_address *)((extv)[(extn)]); 	      \
    670 		addrlen = (ap->spd_address_af == AF_INET6) ? 		      \
    671 			IPV6_ADDR_LEN : IP_ADDR_LEN;			      \
    672 		if (SPD_64TO8(ap->spd_address_len) < 			      \
    673 			(addrlen + sizeof (*ap))) {			      \
    674 			*diag = SPD_DIAGNOSTIC_BAD_ADDR_LEN;		      \
    675 			return (B_FALSE);				      \
    676 		}							      \
    677 		bcopy((ap+1), &((sel)->field), addrlen);		      \
    678 		(sel)->pfield = ap->spd_address_prefixlen;		      \
    679 		(sel)->ipsl_valid |= (bit);				      \
    680 		(sel)->ipsl_valid |= (ap->spd_address_af == AF_INET6) ?	      \
    681 			IPSL_IPV6 : IPSL_IPV4;				      \
    682 	}
    683 
    684 	ADDR2SEL(sel, extv, ipsl_local, ipsl_local_pfxlen,
    685 	    SPD_EXT_LCLADDR, IPSL_LOCAL_ADDR);
    686 	ADDR2SEL(sel, extv, ipsl_remote, ipsl_remote_pfxlen,
    687 	    SPD_EXT_REMADDR, IPSL_REMOTE_ADDR);
    688 
    689 	if ((sel->ipsl_valid & (IPSL_IPV6|IPSL_IPV4)) ==
    690 	    (IPSL_IPV6|IPSL_IPV4)) {
    691 		*diag = SPD_DIAGNOSTIC_MIXED_AF;
    692 		return (B_FALSE);
    693 	}
    694 
    695 #undef ADDR2SEL
    696 
    697 	return (B_TRUE);
    698 }
    699 
    700 static boolean_t
    701 spd_convert_type(uint32_t type, ipsec_act_t *act)
    702 {
    703 	switch (type) {
    704 	case SPD_ACTTYPE_DROP:
    705 		act->ipa_type = IPSEC_ACT_DISCARD;
    706 		return (B_TRUE);
    707 
    708 	case SPD_ACTTYPE_PASS:
    709 		act->ipa_type = IPSEC_ACT_CLEAR;
    710 		return (B_TRUE);
    711 
    712 	case SPD_ACTTYPE_IPSEC:
    713 		act->ipa_type = IPSEC_ACT_APPLY;
    714 		return (B_TRUE);
    715 	}
    716 	return (B_FALSE);
    717 }
    718 
    719 static boolean_t
    720 spd_convert_flags(uint32_t flags, ipsec_act_t *act)
    721 {
    722 	/*
    723 	 * Note use of !! for boolean canonicalization.
    724 	 */
    725 	act->ipa_apply.ipp_use_ah = !!(flags & SPD_APPLY_AH);
    726 	act->ipa_apply.ipp_use_esp = !!(flags & SPD_APPLY_ESP);
    727 	act->ipa_apply.ipp_use_espa = !!(flags & SPD_APPLY_ESPA);
    728 	act->ipa_apply.ipp_use_se = !!(flags & SPD_APPLY_SE);
    729 	act->ipa_apply.ipp_use_unique = !!(flags & SPD_APPLY_UNIQUE);
    730 	return (B_TRUE);
    731 }
    732 
    733 static void
    734 spdsock_reset_act(ipsec_act_t *act)
    735 {
    736 	bzero(act, sizeof (*act));
    737 	act->ipa_apply.ipp_espe_maxbits = IPSEC_MAX_KEYBITS;
    738 	act->ipa_apply.ipp_espa_maxbits = IPSEC_MAX_KEYBITS;
    739 	act->ipa_apply.ipp_ah_maxbits = IPSEC_MAX_KEYBITS;
    740 }
    741 
    742 /*
    743  * Sanity check action against reality, and shrink-wrap key sizes..
    744  */
    745 static boolean_t
    746 spdsock_check_action(ipsec_act_t *act, boolean_t tunnel_polhead, int *diag,
    747     spd_stack_t *spds)
    748 {
    749 	if (tunnel_polhead && act->ipa_apply.ipp_use_unique) {
    750 		*diag = SPD_DIAGNOSTIC_ADD_INCON_FLAGS;
    751 		return (B_FALSE);
    752 	}
    753 	if ((act->ipa_type != IPSEC_ACT_APPLY) &&
    754 	    (act->ipa_apply.ipp_use_ah ||
    755 	    act->ipa_apply.ipp_use_esp ||
    756 	    act->ipa_apply.ipp_use_espa ||
    757 	    act->ipa_apply.ipp_use_se ||
    758 	    act->ipa_apply.ipp_use_unique)) {
    759 		*diag = SPD_DIAGNOSTIC_ADD_INCON_FLAGS;
    760 		return (B_FALSE);
    761 	}
    762 	if ((act->ipa_type == IPSEC_ACT_APPLY) &&
    763 	    !act->ipa_apply.ipp_use_ah &&
    764 	    !act->ipa_apply.ipp_use_esp) {
    765 		*diag = SPD_DIAGNOSTIC_ADD_INCON_FLAGS;
    766 		return (B_FALSE);
    767 	}
    768 	return (ipsec_check_action(act, diag, spds->spds_netstack));
    769 }
    770 
    771 /*
    772  * We may be short a few error checks here..
    773  */
    774 static boolean_t
    775 spdsock_ext_to_actvec(spd_ext_t **extv, ipsec_act_t **actpp, uint_t *nactp,
    776     int *diag, spd_stack_t *spds)
    777 {
    778 	struct spd_ext_actions *sactp =
    779 	    (struct spd_ext_actions *)extv[SPD_EXT_ACTION];
    780 	ipsec_act_t act, *actp, *endactp;
    781 	struct spd_attribute *attrp, *endattrp;
    782 	uint64_t *endp;
    783 	int nact;
    784 	boolean_t tunnel_polhead;
    785 
    786 	tunnel_polhead = (extv[SPD_EXT_TUN_NAME] != NULL &&
    787 	    (((struct spd_rule *)extv[SPD_EXT_RULE])->spd_rule_flags &
    788 	    SPD_RULE_FLAG_TUNNEL));
    789 
    790 	*actpp = NULL;
    791 	*nactp = 0;
    792 
    793 	if (sactp == NULL) {
    794 		*diag = SPD_DIAGNOSTIC_NO_ACTION_EXT;
    795 		return (B_FALSE);
    796 	}
    797 
    798 	/*
    799 	 * Parse the "action" extension and convert into an action chain.
    800 	 */
    801 
    802 	nact = sactp->spd_actions_count;
    803 
    804 	endp = (uint64_t *)sactp;
    805 	endp += sactp->spd_actions_len;
    806 	endattrp = (struct spd_attribute *)endp;
    807 
    808 	actp = kmem_alloc(sizeof (*actp) * nact, KM_NOSLEEP);
    809 	if (actp == NULL) {
    810 		*diag = SPD_DIAGNOSTIC_ADD_NO_MEM;
    811 		return (B_FALSE);
    812 	}
    813 	*actpp = actp;
    814 	*nactp = nact;
    815 	endactp = actp + nact;
    816 
    817 	spdsock_reset_act(&act);
    818 	attrp = (struct spd_attribute *)(&sactp[1]);
    819 
    820 	for (; attrp < endattrp; attrp++) {
    821 		switch (attrp->spd_attr_tag) {
    822 		case SPD_ATTR_NOP:
    823 			break;
    824 
    825 		case SPD_ATTR_EMPTY:
    826 			spdsock_reset_act(&act);
    827 			break;
    828 
    829 		case SPD_ATTR_END:
    830 			attrp = endattrp;
    831 			/* FALLTHRU */
    832 		case SPD_ATTR_NEXT:
    833 			if (actp >= endactp) {
    834 				*diag = SPD_DIAGNOSTIC_ADD_WRONG_ACT_COUNT;
    835 				goto fail;
    836 			}
    837 			if (!spdsock_check_action(&act, tunnel_polhead,
    838 			    diag, spds))
    839 				goto fail;
    840 			*actp++ = act;
    841 			spdsock_reset_act(&act);
    842 			break;
    843 
    844 		case SPD_ATTR_TYPE:
    845 			if (!spd_convert_type(attrp->spd_attr_value, &act)) {
    846 				*diag = SPD_DIAGNOSTIC_ADD_BAD_TYPE;
    847 				goto fail;
    848 			}
    849 			break;
    850 
    851 		case SPD_ATTR_FLAGS:
    852 			if (!tunnel_polhead && extv[SPD_EXT_TUN_NAME] != NULL) {
    853 				/*
    854 				 * Set "sa unique" for transport-mode
    855 				 * tunnels whether we want to or not.
    856 				 */
    857 				attrp->spd_attr_value |= SPD_APPLY_UNIQUE;
    858 			}
    859 			if (!spd_convert_flags(attrp->spd_attr_value, &act)) {
    860 				*diag = SPD_DIAGNOSTIC_ADD_BAD_FLAGS;
    861 				goto fail;
    862 			}
    863 			break;
    864 
    865 		case SPD_ATTR_AH_AUTH:
    866 			if (attrp->spd_attr_value == 0) {
    867 				*diag = SPD_DIAGNOSTIC_UNSUPP_AH_ALG;
    868 				goto fail;
    869 			}
    870 			act.ipa_apply.ipp_auth_alg = attrp->spd_attr_value;
    871 			break;
    872 
    873 		case SPD_ATTR_ESP_ENCR:
    874 			if (attrp->spd_attr_value == 0) {
    875 				*diag = SPD_DIAGNOSTIC_UNSUPP_ESP_ENCR_ALG;
    876 				goto fail;
    877 			}
    878 			act.ipa_apply.ipp_encr_alg = attrp->spd_attr_value;
    879 			break;
    880 
    881 		case SPD_ATTR_ESP_AUTH:
    882 			if (attrp->spd_attr_value == 0) {
    883 				*diag = SPD_DIAGNOSTIC_UNSUPP_ESP_AUTH_ALG;
    884 				goto fail;
    885 			}
    886 			act.ipa_apply.ipp_esp_auth_alg = attrp->spd_attr_value;
    887 			break;
    888 
    889 		case SPD_ATTR_ENCR_MINBITS:
    890 			act.ipa_apply.ipp_espe_minbits = attrp->spd_attr_value;
    891 			break;
    892 
    893 		case SPD_ATTR_ENCR_MAXBITS:
    894 			act.ipa_apply.ipp_espe_maxbits = attrp->spd_attr_value;
    895 			break;
    896 
    897 		case SPD_ATTR_AH_MINBITS:
    898 			act.ipa_apply.ipp_ah_minbits = attrp->spd_attr_value;
    899 			break;
    900 
    901 		case SPD_ATTR_AH_MAXBITS:
    902 			act.ipa_apply.ipp_ah_maxbits = attrp->spd_attr_value;
    903 			break;
    904 
    905 		case SPD_ATTR_ESPA_MINBITS:
    906 			act.ipa_apply.ipp_espa_minbits = attrp->spd_attr_value;
    907 			break;
    908 
    909 		case SPD_ATTR_ESPA_MAXBITS:
    910 			act.ipa_apply.ipp_espa_maxbits = attrp->spd_attr_value;
    911 			break;
    912 
    913 		case SPD_ATTR_LIFE_SOFT_TIME:
    914 		case SPD_ATTR_LIFE_HARD_TIME:
    915 		case SPD_ATTR_LIFE_SOFT_BYTES:
    916 		case SPD_ATTR_LIFE_HARD_BYTES:
    917 			break;
    918 
    919 		case SPD_ATTR_KM_PROTO:
    920 			act.ipa_apply.ipp_km_proto = attrp->spd_attr_value;
    921 			break;
    922 
    923 		case SPD_ATTR_KM_COOKIE:
    924 			act.ipa_apply.ipp_km_cookie = attrp->spd_attr_value;
    925 			break;
    926 
    927 		case SPD_ATTR_REPLAY_DEPTH:
    928 			act.ipa_apply.ipp_replay_depth = attrp->spd_attr_value;
    929 			break;
    930 		}
    931 	}
    932 	if (actp != endactp) {
    933 		*diag = SPD_DIAGNOSTIC_ADD_WRONG_ACT_COUNT;
    934 		goto fail;
    935 	}
    936 
    937 	return (B_TRUE);
    938 fail:
    939 	ipsec_actvec_free(*actpp, nact);
    940 	*actpp = NULL;
    941 	return (B_FALSE);
    942 }
    943 
    944 typedef struct
    945 {
    946 	ipsec_policy_t *pol;
    947 	int dir;
    948 } tmprule_t;
    949 
    950 static int
    951 mkrule(ipsec_policy_head_t *iph, struct spd_rule *rule,
    952     ipsec_selkey_t *sel, ipsec_act_t *actp, int nact, uint_t dir, uint_t af,
    953     tmprule_t **rp, uint64_t *index, spd_stack_t *spds)
    954 {
    955 	ipsec_policy_t *pol;
    956 
    957 	sel->ipsl_valid &= ~(IPSL_IPV6|IPSL_IPV4);
    958 	sel->ipsl_valid |= af;
    959 
    960 	pol = ipsec_policy_create(sel, actp, nact, rule->spd_rule_priority,
    961 	    index, spds->spds_netstack);
    962 	if (pol == NULL)
    963 		return (ENOMEM);
    964 
    965 	(*rp)->pol = pol;
    966 	(*rp)->dir = dir;
    967 	(*rp)++;
    968 
    969 	if (!ipsec_check_policy(iph, pol, dir))
    970 		return (EEXIST);
    971 
    972 	rule->spd_rule_index = pol->ipsp_index;
    973 	return (0);
    974 }
    975 
    976 static int
    977 mkrulepair(ipsec_policy_head_t *iph, struct spd_rule *rule,
    978     ipsec_selkey_t *sel, ipsec_act_t *actp, int nact, uint_t dir, uint_t afs,
    979     tmprule_t **rp, uint64_t *index, spd_stack_t *spds)
    980 {
    981 	int error;
    982 
    983 	if (afs & IPSL_IPV4) {
    984 		error = mkrule(iph, rule, sel, actp, nact, dir, IPSL_IPV4, rp,
    985 		    index, spds);
    986 		if (error != 0)
    987 			return (error);
    988 	}
    989 	if (afs & IPSL_IPV6) {
    990 		error = mkrule(iph, rule, sel, actp, nact, dir, IPSL_IPV6, rp,
    991 		    index, spds);
    992 		if (error != 0)
    993 			return (error);
    994 	}
    995 	return (0);
    996 }
    997 
    998 
    999 static void
   1000 spdsock_addrule(queue_t *q, ipsec_policy_head_t *iph, mblk_t *mp,
   1001     spd_ext_t **extv, ipsec_tun_pol_t *itp)
   1002 {
   1003 	ipsec_selkey_t sel;
   1004 	ipsec_act_t *actp;
   1005 	uint_t nact;
   1006 	int diag = 0, error, afs;
   1007 	struct spd_rule *rule = (struct spd_rule *)extv[SPD_EXT_RULE];
   1008 	tmprule_t rules[4], *rulep = &rules[0];
   1009 	boolean_t tunnel_mode, empty_itp,