xref: /illumos-gate/usr/src/uts/common/inet/ip/ipsecesp.c (revision c8adf4ed602b64b642af339be8bf25d13fd1563f)
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/types.h>
29 #include <sys/stream.h>
30 #include <sys/stropts.h>
31 #include <sys/errno.h>
32 #include <sys/strlog.h>
33 #include <sys/tihdr.h>
34 #include <sys/socket.h>
35 #include <sys/ddi.h>
36 #include <sys/sunddi.h>
37 #include <sys/kmem.h>
38 #include <sys/zone.h>
39 #include <sys/sysmacros.h>
40 #include <sys/cmn_err.h>
41 #include <sys/vtrace.h>
42 #include <sys/debug.h>
43 #include <sys/atomic.h>
44 #include <sys/strsun.h>
45 #include <sys/random.h>
46 #include <netinet/in.h>
47 #include <net/if.h>
48 #include <netinet/ip6.h>
49 #include <net/pfkeyv2.h>
50 
51 #include <inet/common.h>
52 #include <inet/mi.h>
53 #include <inet/nd.h>
54 #include <inet/ip.h>
55 #include <inet/ip_impl.h>
56 #include <inet/ip6.h>
57 #include <inet/sadb.h>
58 #include <inet/ipsec_info.h>
59 #include <inet/ipsec_impl.h>
60 #include <inet/ipsecesp.h>
61 #include <inet/ipdrop.h>
62 #include <inet/tcp.h>
63 #include <sys/kstat.h>
64 #include <sys/policy.h>
65 #include <sys/strsun.h>
66 #include <inet/udp_impl.h>
67 #include <sys/taskq.h>
68 #include <sys/note.h>
69 
70 #include <sys/iphada.h>
71 
72 /*
73  * Table of ND variables supported by ipsecesp. These are loaded into
74  * ipsecesp_g_nd in ipsecesp_init_nd.
75  * All of these are alterable, within the min/max values given, at run time.
76  */
77 static	ipsecespparam_t	lcl_param_arr[] = {
78 	/* min	max			value	name */
79 	{ 0,	3,			0,	"ipsecesp_debug"},
80 	{ 125,	32000, SADB_AGE_INTERVAL_DEFAULT, "ipsecesp_age_interval"},
81 	{ 1,	10,			1,	"ipsecesp_reap_delay"},
82 	{ 1,	SADB_MAX_REPLAY,	64,	"ipsecesp_replay_size"},
83 	{ 1,	300,			15,	"ipsecesp_acquire_timeout"},
84 	{ 1,	1800,			90,	"ipsecesp_larval_timeout"},
85 	/* Default lifetime values for ACQUIRE messages. */
86 	{ 0,	0xffffffffU,	0,	"ipsecesp_default_soft_bytes"},
87 	{ 0,	0xffffffffU,	0,	"ipsecesp_default_hard_bytes"},
88 	{ 0,	0xffffffffU,	24000,	"ipsecesp_default_soft_addtime"},
89 	{ 0,	0xffffffffU,	28800,	"ipsecesp_default_hard_addtime"},
90 	{ 0,	0xffffffffU,	0,	"ipsecesp_default_soft_usetime"},
91 	{ 0,	0xffffffffU,	0,	"ipsecesp_default_hard_usetime"},
92 	{ 0,	1,		0,	"ipsecesp_log_unknown_spi"},
93 	{ 0,	2,		1,	"ipsecesp_padding_check"},
94 	{ 0,	600,		20,	"ipsecesp_nat_keepalive_interval"},
95 };
96 #define	ipsecesp_debug	ipsecesp_params[0].ipsecesp_param_value
97 #define	ipsecesp_age_interval ipsecesp_params[1].ipsecesp_param_value
98 #define	ipsecesp_age_int_max	ipsecesp_params[1].ipsecesp_param_max
99 #define	ipsecesp_reap_delay	ipsecesp_params[2].ipsecesp_param_value
100 #define	ipsecesp_replay_size	ipsecesp_params[3].ipsecesp_param_value
101 #define	ipsecesp_acquire_timeout	\
102 	ipsecesp_params[4].ipsecesp_param_value
103 #define	ipsecesp_larval_timeout	\
104 	ipsecesp_params[5].ipsecesp_param_value
105 #define	ipsecesp_default_soft_bytes	\
106 	ipsecesp_params[6].ipsecesp_param_value
107 #define	ipsecesp_default_hard_bytes	\
108 	ipsecesp_params[7].ipsecesp_param_value
109 #define	ipsecesp_default_soft_addtime	\
110 	ipsecesp_params[8].ipsecesp_param_value
111 #define	ipsecesp_default_hard_addtime	\
112 	ipsecesp_params[9].ipsecesp_param_value
113 #define	ipsecesp_default_soft_usetime	\
114 	ipsecesp_params[10].ipsecesp_param_value
115 #define	ipsecesp_default_hard_usetime	\
116 	ipsecesp_params[11].ipsecesp_param_value
117 #define	ipsecesp_log_unknown_spi	\
118 	ipsecesp_params[12].ipsecesp_param_value
119 #define	ipsecesp_padding_check	\
120 	ipsecesp_params[13].ipsecesp_param_value
121 /* For ipsecesp_nat_keepalive_interval, see ipsecesp.h. */
122 
123 #define	esp0dbg(a)	printf a
124 /* NOTE:  != 0 instead of > 0 so lint doesn't complain. */
125 #define	esp1dbg(espstack, a)	if (espstack->ipsecesp_debug != 0) printf a
126 #define	esp2dbg(espstack, a)	if (espstack->ipsecesp_debug > 1) printf a
127 #define	esp3dbg(espstack, a)	if (espstack->ipsecesp_debug > 2) printf a
128 
129 static int ipsecesp_open(queue_t *, dev_t *, int, int, cred_t *);
130 static int ipsecesp_close(queue_t *);
131 static void ipsecesp_rput(queue_t *, mblk_t *);
132 static void ipsecesp_wput(queue_t *, mblk_t *);
133 static void	*ipsecesp_stack_init(netstackid_t stackid, netstack_t *ns);
134 static void	ipsecesp_stack_fini(netstackid_t stackid, void *arg);
135 static void esp_send_acquire(ipsacq_t *, mblk_t *, netstack_t *);
136 
137 static void esp_prepare_udp(netstack_t *, mblk_t *, ipha_t *);
138 static ipsec_status_t esp_outbound_accelerated(mblk_t *, uint_t);
139 static ipsec_status_t esp_inbound_accelerated(mblk_t *, mblk_t *,
140     boolean_t, ipsa_t *);
141 
142 static boolean_t esp_register_out(uint32_t, uint32_t, uint_t,
143     ipsecesp_stack_t *);
144 static boolean_t esp_strip_header(mblk_t *, boolean_t, uint32_t,
145     kstat_named_t **, ipsecesp_stack_t *);
146 static ipsec_status_t esp_submit_req_inbound(mblk_t *, ipsa_t *, uint_t);
147 static ipsec_status_t esp_submit_req_outbound(mblk_t *, ipsa_t *, uchar_t *,
148     uint_t);
149 /* Setable in /etc/system */
150 uint32_t esp_hash_size = IPSEC_DEFAULT_HASH_SIZE;
151 
152 static struct module_info info = {
153 	5137, "ipsecesp", 0, INFPSZ, 65536, 1024
154 };
155 
156 static struct qinit rinit = {
157 	(pfi_t)ipsecesp_rput, NULL, ipsecesp_open, ipsecesp_close, NULL, &info,
158 	NULL
159 };
160 
161 static struct qinit winit = {
162 	(pfi_t)ipsecesp_wput, NULL, ipsecesp_open, ipsecesp_close, NULL, &info,
163 	NULL
164 };
165 
166 struct streamtab ipsecespinfo = {
167 	&rinit, &winit, NULL, NULL
168 };
169 
170 static taskq_t *esp_taskq;
171 
172 /*
173  * OTOH, this one is set at open/close, and I'm D_MTQPAIR for now.
174  *
175  * Question:	Do I need this, given that all instance's esps->esps_wq point
176  *		to IP?
177  *
178  * Answer:	Yes, because I need to know which queue is BOUND to
179  *		IPPROTO_ESP
180  */
181 
182 /*
183  * Stats.  This may eventually become a full-blown SNMP MIB once that spec
184  * stabilizes.
185  */
186 
187 typedef struct esp_kstats_s {
188 	kstat_named_t esp_stat_num_aalgs;
189 	kstat_named_t esp_stat_good_auth;
190 	kstat_named_t esp_stat_bad_auth;
191 	kstat_named_t esp_stat_bad_padding;
192 	kstat_named_t esp_stat_replay_failures;
193 	kstat_named_t esp_stat_replay_early_failures;
194 	kstat_named_t esp_stat_keysock_in;
195 	kstat_named_t esp_stat_out_requests;
196 	kstat_named_t esp_stat_acquire_requests;
197 	kstat_named_t esp_stat_bytes_expired;
198 	kstat_named_t esp_stat_out_discards;
199 	kstat_named_t esp_stat_in_accelerated;
200 	kstat_named_t esp_stat_out_accelerated;
201 	kstat_named_t esp_stat_noaccel;
202 	kstat_named_t esp_stat_crypto_sync;
203 	kstat_named_t esp_stat_crypto_async;
204 	kstat_named_t esp_stat_crypto_failures;
205 	kstat_named_t esp_stat_num_ealgs;
206 	kstat_named_t esp_stat_bad_decrypt;
207 	kstat_named_t esp_stat_sa_port_renumbers;
208 } esp_kstats_t;
209 
210 /*
211  * espstack->esp_kstats is equal to espstack->esp_ksp->ks_data if
212  * kstat_create_netstack for espstack->esp_ksp succeeds, but when it
213  * fails, it will be NULL. Note this is done for all stack instances,
214  * so it *could* fail. hence a non-NULL checking is done for
215  * ESP_BUMP_STAT and ESP_DEBUMP_STAT
216  */
217 #define	ESP_BUMP_STAT(espstack, x)					\
218 do {									\
219 	if (espstack->esp_kstats != NULL)				\
220 		(espstack->esp_kstats->esp_stat_ ## x).value.ui64++;	\
221 _NOTE(CONSTCOND)							\
222 } while (0)
223 
224 #define	ESP_DEBUMP_STAT(espstack, x)					\
225 do {									\
226 	if (espstack->esp_kstats != NULL)				\
227 		(espstack->esp_kstats->esp_stat_ ## x).value.ui64--;	\
228 _NOTE(CONSTCOND)							\
229 } while (0)
230 
231 static int	esp_kstat_update(kstat_t *, int);
232 
233 static boolean_t
234 esp_kstat_init(ipsecesp_stack_t *espstack, netstackid_t stackid)
235 {
236 	espstack->esp_ksp = kstat_create_netstack("ipsecesp", 0, "esp_stat",
237 	    "net", KSTAT_TYPE_NAMED,
238 	    sizeof (esp_kstats_t) / sizeof (kstat_named_t),
239 	    KSTAT_FLAG_PERSISTENT, stackid);
240 
241 	if (espstack->esp_ksp == NULL || espstack->esp_ksp->ks_data == NULL)
242 		return (B_FALSE);
243 
244 	espstack->esp_kstats = espstack->esp_ksp->ks_data;
245 
246 	espstack->esp_ksp->ks_update = esp_kstat_update;
247 	espstack->esp_ksp->ks_private = (void *)(uintptr_t)stackid;
248 
249 #define	K64 KSTAT_DATA_UINT64
250 #define	KI(x) kstat_named_init(&(espstack->esp_kstats->esp_stat_##x), #x, K64)
251 
252 	KI(num_aalgs);
253 	KI(num_ealgs);
254 	KI(good_auth);
255 	KI(bad_auth);
256 	KI(bad_padding);
257 	KI(replay_failures);
258 	KI(replay_early_failures);
259 	KI(keysock_in);
260 	KI(out_requests);
261 	KI(acquire_requests);
262 	KI(bytes_expired);
263 	KI(out_discards);
264 	KI(in_accelerated);
265 	KI(out_accelerated);
266 	KI(noaccel);
267 	KI(crypto_sync);
268 	KI(crypto_async);
269 	KI(crypto_failures);
270 	KI(bad_decrypt);
271 	KI(sa_port_renumbers);
272 
273 #undef KI
274 #undef K64
275 
276 	kstat_install(espstack->esp_ksp);
277 
278 	return (B_TRUE);
279 }
280 
281 static int
282 esp_kstat_update(kstat_t *kp, int rw)
283 {
284 	esp_kstats_t *ekp;
285 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
286 	netstack_t	*ns;
287 	ipsec_stack_t	*ipss;
288 
289 	if ((kp == NULL) || (kp->ks_data == NULL))
290 		return (EIO);
291 
292 	if (rw == KSTAT_WRITE)
293 		return (EACCES);
294 
295 	ns = netstack_find_by_stackid(stackid);
296 	if (ns == NULL)
297 		return (-1);
298 	ipss = ns->netstack_ipsec;
299 	if (ipss == NULL) {
300 		netstack_rele(ns);
301 		return (-1);
302 	}
303 	ekp = (esp_kstats_t *)kp->ks_data;
304 
305 	mutex_enter(&ipss->ipsec_alg_lock);
306 	ekp->esp_stat_num_aalgs.value.ui64 =
307 	    ipss->ipsec_nalgs[IPSEC_ALG_AUTH];
308 	ekp->esp_stat_num_ealgs.value.ui64 =
309 	    ipss->ipsec_nalgs[IPSEC_ALG_ENCR];
310 	mutex_exit(&ipss->ipsec_alg_lock);
311 
312 	netstack_rele(ns);
313 	return (0);
314 }
315 
316 #ifdef DEBUG
317 /*
318  * Debug routine, useful to see pre-encryption data.
319  */
320 static char *
321 dump_msg(mblk_t *mp)
322 {
323 	char tmp_str[3], tmp_line[256];
324 
325 	while (mp != NULL) {
326 		unsigned char *ptr;
327 
328 		printf("mblk address 0x%p, length %ld, db_ref %d "
329 		    "type %d, base 0x%p, lim 0x%p\n",
330 		    (void *) mp, (long)(mp->b_wptr - mp->b_rptr),
331 		    mp->b_datap->db_ref, mp->b_datap->db_type,
332 		    (void *)mp->b_datap->db_base, (void *)mp->b_datap->db_lim);
333 		ptr = mp->b_rptr;
334 
335 		tmp_line[0] = '\0';
336 		while (ptr < mp->b_wptr) {
337 			uint_t diff;
338 
339 			diff = (ptr - mp->b_rptr);
340 			if (!(diff & 0x1f)) {
341 				if (strlen(tmp_line) > 0) {
342 					printf("bytes: %s\n", tmp_line);
343 					tmp_line[0] = '\0';
344 				}
345 			}
346 			if (!(diff & 0x3))
347 				(void) strcat(tmp_line, " ");
348 			(void) sprintf(tmp_str, "%02x", *ptr);
349 			(void) strcat(tmp_line, tmp_str);
350 			ptr++;
351 		}
352 		if (strlen(tmp_line) > 0)
353 			printf("bytes: %s\n", tmp_line);
354 
355 		mp = mp->b_cont;
356 	}
357 
358 	return ("\n");
359 }
360 
361 #else /* DEBUG */
362 static char *
363 dump_msg(mblk_t *mp)
364 {
365 	printf("Find value of mp %p.\n", mp);
366 	return ("\n");
367 }
368 #endif /* DEBUG */
369 
370 /*
371  * Don't have to lock age_interval, as only one thread will access it at
372  * a time, because I control the one function that does with timeout().
373  */
374 static void
375 esp_ager(void *arg)
376 {
377 	ipsecesp_stack_t *espstack = (ipsecesp_stack_t *)arg;
378 	netstack_t	*ns = espstack->ipsecesp_netstack;
379 	hrtime_t begin = gethrtime();
380 
381 	sadb_ager(&espstack->esp_sadb.s_v4, espstack->esp_pfkey_q,
382 	    espstack->esp_sadb.s_ip_q, espstack->ipsecesp_reap_delay, ns);
383 	sadb_ager(&espstack->esp_sadb.s_v6, espstack->esp_pfkey_q,
384 	    espstack->esp_sadb.s_ip_q, espstack->ipsecesp_reap_delay, ns);
385 
386 	espstack->esp_event = sadb_retimeout(begin, espstack->esp_pfkey_q,
387 	    esp_ager, espstack,
388 	    &espstack->ipsecesp_age_interval, espstack->ipsecesp_age_int_max,
389 	    info.mi_idnum);
390 }
391 
392 /*
393  * Get an ESP NDD parameter.
394  */
395 /* ARGSUSED */
396 static int
397 ipsecesp_param_get(q, mp, cp, cr)
398 	queue_t	*q;
399 	mblk_t	*mp;
400 	caddr_t	cp;
401 	cred_t *cr;
402 {
403 	ipsecespparam_t	*ipsecesppa = (ipsecespparam_t *)cp;
404 	uint_t value;
405 	ipsecesp_stack_t	*espstack = (ipsecesp_stack_t *)q->q_ptr;
406 
407 	mutex_enter(&espstack->ipsecesp_param_lock);
408 	value = ipsecesppa->ipsecesp_param_value;
409 	mutex_exit(&espstack->ipsecesp_param_lock);
410 
411 	(void) mi_mpprintf(mp, "%u", value);
412 	return (0);
413 }
414 
415 /*
416  * This routine sets an NDD variable in a ipsecespparam_t structure.
417  */
418 /* ARGSUSED */
419 static int
420 ipsecesp_param_set(q, mp, value, cp, cr)
421 	queue_t	*q;
422 	mblk_t	*mp;
423 	char	*value;
424 	caddr_t	cp;
425 	cred_t *cr;
426 {
427 	ulong_t	new_value;
428 	ipsecespparam_t	*ipsecesppa = (ipsecespparam_t *)cp;
429 	ipsecesp_stack_t	*espstack = (ipsecesp_stack_t *)q->q_ptr;
430 
431 	/*
432 	 * Fail the request if the new value does not lie within the
433 	 * required bounds.
434 	 */
435 	if (ddi_strtoul(value, NULL, 10, &new_value) != 0 ||
436 	    new_value < ipsecesppa->ipsecesp_param_min ||
437 	    new_value > ipsecesppa->ipsecesp_param_max) {
438 		return (EINVAL);
439 	}
440 
441 	/* Set the new value */
442 	mutex_enter(&espstack->ipsecesp_param_lock);
443 	ipsecesppa->ipsecesp_param_value = new_value;
444 	mutex_exit(&espstack->ipsecesp_param_lock);
445 	return (0);
446 }
447 
448 /*
449  * Using lifetime NDD variables, fill in an extended combination's
450  * lifetime information.
451  */
452 void
453 ipsecesp_fill_defs(sadb_x_ecomb_t *ecomb, netstack_t *ns)
454 {
455 	ipsecesp_stack_t	*espstack = ns->netstack_ipsecesp;
456 
457 	ecomb->sadb_x_ecomb_soft_bytes = espstack->ipsecesp_default_soft_bytes;
458 	ecomb->sadb_x_ecomb_hard_bytes = espstack->ipsecesp_default_hard_bytes;
459 	ecomb->sadb_x_ecomb_soft_addtime =
460 	    espstack->ipsecesp_default_soft_addtime;
461 	ecomb->sadb_x_ecomb_hard_addtime =
462 	    espstack->ipsecesp_default_hard_addtime;
463 	ecomb->sadb_x_ecomb_soft_usetime =
464 	    espstack->ipsecesp_default_soft_usetime;
465 	ecomb->sadb_x_ecomb_hard_usetime =
466 	    espstack->ipsecesp_default_hard_usetime;
467 }
468 
469 /*
470  * Initialize things for ESP at module load time.
471  */
472 boolean_t
473 ipsecesp_ddi_init(void)
474 {
475 	esp_taskq = taskq_create("esp_taskq", 1, minclsyspri,
476 	    IPSEC_TASKQ_MIN, IPSEC_TASKQ_MAX, 0);
477 
478 	/*
479 	 * We want to be informed each time a stack is created or
480 	 * destroyed in the kernel, so we can maintain the
481 	 * set of ipsecesp_stack_t's.
482 	 */
483 	netstack_register(NS_IPSECESP, ipsecesp_stack_init, NULL,
484 	    ipsecesp_stack_fini);
485 
486 	return (B_TRUE);
487 }
488 
489 /*
490  * Walk through the param array specified registering each element with the
491  * named dispatch handler.
492  */
493 static boolean_t
494 ipsecesp_param_register(IDP *ndp, ipsecespparam_t *espp, int cnt)
495 {
496 	for (; cnt-- > 0; espp++) {
497 		if (espp->ipsecesp_param_name != NULL &&
498 		    espp->ipsecesp_param_name[0]) {
499 			if (!nd_load(ndp,
500 			    espp->ipsecesp_param_name,
501 			    ipsecesp_param_get, ipsecesp_param_set,
502 			    (caddr_t)espp)) {
503 				nd_free(ndp);
504 				return (B_FALSE);
505 			}
506 		}
507 	}
508 	return (B_TRUE);
509 }
510 /*
511  * Initialize things for ESP for each stack instance
512  */
513 static void *
514 ipsecesp_stack_init(netstackid_t stackid, netstack_t *ns)
515 {
516 	ipsecesp_stack_t	*espstack;
517 	ipsecespparam_t		*espp;
518 
519 	espstack = (ipsecesp_stack_t *)kmem_zalloc(sizeof (*espstack),
520 	    KM_SLEEP);
521 	espstack->ipsecesp_netstack = ns;
522 
523 	espp = (ipsecespparam_t *)kmem_alloc(sizeof (lcl_param_arr), KM_SLEEP);
524 	espstack->ipsecesp_params = espp;
525 	bcopy(lcl_param_arr, espp, sizeof (lcl_param_arr));
526 
527 	(void) ipsecesp_param_register(&espstack->ipsecesp_g_nd, espp,
528 	    A_CNT(lcl_param_arr));
529 
530 	(void) esp_kstat_init(espstack, stackid);
531 
532 	espstack->esp_sadb.s_acquire_timeout =
533 	    &espstack->ipsecesp_acquire_timeout;
534 	espstack->esp_sadb.s_acqfn = esp_send_acquire;
535 	sadbp_init("ESP", &espstack->esp_sadb, SADB_SATYPE_ESP, esp_hash_size,
536 	    espstack->ipsecesp_netstack);
537 
538 	mutex_init(&espstack->ipsecesp_param_lock, NULL, MUTEX_DEFAULT, 0);
539 
540 	ip_drop_register(&espstack->esp_dropper, "IPsec ESP");
541 	return (espstack);
542 }
543 
544 /*
545  * Destroy things for ESP at module unload time.
546  */
547 void
548 ipsecesp_ddi_destroy(void)
549 {
550 	netstack_unregister(NS_IPSECESP);
551 	taskq_destroy(esp_taskq);
552 }
553 
554 /*
555  * Destroy things for ESP for one stack instance
556  */
557 static void
558 ipsecesp_stack_fini(netstackid_t stackid, void *arg)
559 {
560 	ipsecesp_stack_t *espstack = (ipsecesp_stack_t *)arg;
561 
562 	if (espstack->esp_pfkey_q != NULL) {
563 		(void) quntimeout(espstack->esp_pfkey_q, espstack->esp_event);
564 	}
565 	espstack->esp_sadb.s_acqfn = NULL;
566 	espstack->esp_sadb.s_acquire_timeout = NULL;
567 	sadbp_destroy(&espstack->esp_sadb, espstack->ipsecesp_netstack);
568 	ip_drop_unregister(&espstack->esp_dropper);
569 	mutex_destroy(&espstack->ipsecesp_param_lock);
570 	nd_free(&espstack->ipsecesp_g_nd);
571 
572 	kmem_free(espstack->ipsecesp_params, sizeof (lcl_param_arr));
573 	espstack->ipsecesp_params = NULL;
574 	kstat_delete_netstack(espstack->esp_ksp, stackid);
575 	espstack->esp_ksp = NULL;
576 	espstack->esp_kstats = NULL;
577 	kmem_free(espstack, sizeof (*espstack));
578 }
579 
580 /*
581  * ESP module open routine.
582  */
583 /* ARGSUSED */
584 static int
585 ipsecesp_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
586 {
587 	netstack_t		*ns;
588 	ipsecesp_stack_t	*espstack;
589 
590 	if (secpolicy_ip_config(credp, B_FALSE) != 0) {
591 		esp0dbg(("Non-privileged user trying to open ipsecesp.\n"));
592 		return (EPERM);
593 	}
594 
595 	if (q->q_ptr != NULL)
596 		return (0);  /* Re-open of an already open instance. */
597 
598 	if (sflag != MODOPEN)
599 		return (EINVAL);
600 
601 	ns = netstack_find_by_cred(credp);
602 	ASSERT(ns != NULL);
603 	espstack = ns->netstack_ipsecesp;
604 	ASSERT(espstack != NULL);
605 
606 	/*
607 	 * ASSUMPTIONS (because I'm MT_OCEXCL):
608 	 *
609 	 *	* I'm being pushed on top of IP for all my opens (incl. #1).
610 	 *	* Only ipsecesp_open() can write into esp_sadb.s_ip_q.
611 	 *	* Because of this, I can check lazily for esp_sadb.s_ip_q.
612 	 *
613 	 *  If these assumptions are wrong, I'm in BIG trouble...
614 	 */
615 
616 	q->q_ptr = espstack;
617 	WR(q)->q_ptr = q->q_ptr;
618 
619 	if (espstack->esp_sadb.s_ip_q == NULL) {
620 		struct T_unbind_req *tur;
621 
622 		espstack->esp_sadb.s_ip_q = WR(q);
623 		/* Allocate an unbind... */
624 		espstack->esp_ip_unbind = allocb(sizeof (struct T_unbind_req),
625 		    BPRI_HI);
626 
627 		/*
628 		 * Send down T_BIND_REQ to bind IPPROTO_ESP.
629 		 * Handle the ACK here in ESP.
630 		 */
631 		qprocson(q);
632 		if (espstack->esp_ip_unbind == NULL ||
633 		    !sadb_t_bind_req(espstack->esp_sadb.s_ip_q, IPPROTO_ESP)) {
634 			if (espstack->esp_ip_unbind != NULL) {
635 				freeb(espstack->esp_ip_unbind);
636 				espstack->esp_ip_unbind = NULL;
637 			}
638 			q->q_ptr = NULL;
639 			netstack_rele(espstack->ipsecesp_netstack);
640 			return (ENOMEM);
641 		}
642 
643 		espstack->esp_ip_unbind->b_datap->db_type = M_PROTO;
644 		tur = (struct T_unbind_req *)espstack->esp_ip_unbind->b_rptr;
645 		tur->PRIM_type = T_UNBIND_REQ;
646 	} else {
647 		qprocson(q);
648 	}
649 
650 	/*
651 	 * For now, there's not much I can do.  I'll be getting a message
652 	 * passed down to me from keysock (in my wput), and a T_BIND_ACK
653 	 * up from IP (in my rput).
654 	 */
655 
656 	return (0);
657 }
658 
659 /*
660  * ESP module close routine.
661  */
662 static int
663 ipsecesp_close(queue_t *q)
664 {
665 	ipsecesp_stack_t	*espstack = (ipsecesp_stack_t *)q->q_ptr;
666 
667 	/*
668 	 * If esp_sadb.s_ip_q is attached to this instance, send a
669 	 * T_UNBIND_REQ to IP for the instance before doing
670 	 * a qprocsoff().
671 	 */
672 	if (WR(q) == espstack->esp_sadb.s_ip_q &&
673 	    espstack->esp_ip_unbind != NULL) {
674 		putnext(WR(q), espstack->esp_ip_unbind);
675 		espstack->esp_ip_unbind = NULL;
676 	}
677 
678 	/*
679 	 * Clean up q_ptr, if needed.
680 	 */
681 	qprocsoff(q);
682 
683 	/* Keysock queue check is safe, because of OCEXCL perimeter. */
684 
685 	if (q == espstack->esp_pfkey_q) {
686 		esp1dbg(espstack,
687 		    ("ipsecesp_close:  Ummm... keysock is closing ESP.\n"));
688 		espstack->esp_pfkey_q = NULL;
689 		/* Detach qtimeouts. */
690 		(void) quntimeout(q, espstack->esp_event);
691 	}
692 
693 	if (WR(q) == espstack->esp_sadb.s_ip_q) {
694 		/*
695 		 * If the esp_sadb.s_ip_q is attached to this instance, find
696 		 * another.  The OCEXCL outer perimeter helps us here.
697 		 */
698 		espstack->esp_sadb.s_ip_q = NULL;
699 
700 		/*
701 		 * Find a replacement queue for esp_sadb.s_ip_q.
702 		 */
703 		if (espstack->esp_pfkey_q != NULL &&
704 		    espstack->esp_pfkey_q != RD(q)) {
705 			/*
706 			 * See if we can use the pfkey_q.
707 			 */
708 			espstack->esp_sadb.s_ip_q = WR(espstack->esp_pfkey_q);
709 		}
710 
711 		if (espstack->esp_sadb.s_ip_q == NULL ||
712 		    !sadb_t_bind_req(espstack->esp_sadb.s_ip_q, IPPROTO_ESP)) {
713 			esp1dbg(espstack, ("ipsecesp: Can't reassign ip_q.\n"));
714 			espstack->esp_sadb.s_ip_q = NULL;
715 		} else {
716 			espstack->esp_ip_unbind =
717 			    allocb(sizeof (struct T_unbind_req), BPRI_HI);
718 
719 			if (espstack->esp_ip_unbind != NULL) {
720 				struct T_unbind_req *tur;
721 
722 				espstack->esp_ip_unbind->b_datap->db_type =
723 				    M_PROTO;
724 				tur = (struct T_unbind_req *)
725 				    espstack->esp_ip_unbind->b_rptr;
726 				tur->PRIM_type = T_UNBIND_REQ;
727 			}
728 			/* If it's NULL, I can't do much here. */
729 		}
730 	}
731 
732 	netstack_rele(espstack->ipsecesp_netstack);
733 	return (0);
734 }
735 
736 /*
737  * Add a number of bytes to what the SA has protected so far.  Return
738  * B_TRUE if the SA can still protect that many bytes.
739  *
740  * Caller must REFRELE the passed-in assoc.  This function must REFRELE
741  * any obtained peer SA.
742  */
743 static boolean_t
744 esp_age_bytes(ipsa_t *assoc, uint64_t bytes, boolean_t inbound)
745 {
746 	ipsa_t *inassoc, *outassoc;
747 	isaf_t *bucket;
748 	boolean_t inrc, outrc, isv6;
749 	sadb_t *sp;
750 	int outhash;
751 	netstack_t		*ns = assoc->ipsa_netstack;
752 	ipsecesp_stack_t	*espstack = ns->netstack_ipsecesp;
753 
754 	/* No peer?  No problem! */
755 	if (!assoc->ipsa_haspeer) {
756 		return (sadb_age_bytes(espstack->esp_pfkey_q, assoc, bytes,
757 		    B_TRUE));
758 	}
759 
760 	/*
761 	 * Otherwise, we want to grab both the original assoc and its peer.
762 	 * There might be a race for this, but if it's a real race, two
763 	 * expire messages may occur.  We limit this by only sending the
764 	 * expire message on one of the peers, we'll pick the inbound
765 	 * arbitrarily.
766 	 *
767 	 * If we need tight synchronization on the peer SA, then we need to
768 	 * reconsider.
769 	 */
770 
771 	/* Use address length to select IPv6/IPv4 */
772 	isv6 = (assoc->ipsa_addrfam == AF_INET6);
773 	sp = isv6 ? &espstack->esp_sadb.s_v6 : &espstack->esp_sadb.s_v4;
774 
775 	if (inbound) {
776 		inassoc = assoc;
777 		if (isv6) {
778 			outhash = OUTBOUND_HASH_V6(sp, *((in6_addr_t *)
779 			    &inassoc->ipsa_dstaddr));
780 		} else {
781 			outhash = OUTBOUND_HASH_V4(sp, *((ipaddr_t *)
782 			    &inassoc->ipsa_dstaddr));
783 		}
784 		bucket = &sp->sdb_of[outhash];
785 		mutex_enter(&bucket->isaf_lock);
786 		outassoc = ipsec_getassocbyspi(bucket, inassoc->ipsa_spi,
787 		    inassoc->ipsa_srcaddr, inassoc->ipsa_dstaddr,
788 		    inassoc->ipsa_addrfam);
789 		mutex_exit(&bucket->isaf_lock);
790 		if (outassoc == NULL) {
791 			/* Q: Do we wish to set haspeer == B_FALSE? */
792 			esp0dbg(("esp_age_bytes: "
793 			    "can't find peer for inbound.\n"));
794 			return (sadb_age_bytes(espstack->esp_pfkey_q, inassoc,
795 			    bytes, B_TRUE));
796 		}
797 	} else {
798 		outassoc = assoc;
799 		bucket = INBOUND_BUCKET(sp, outassoc->ipsa_spi);
800 		mutex_enter(&bucket->isaf_lock);
801 		inassoc = ipsec_getassocbyspi(bucket, outassoc->ipsa_spi,
802 		    outassoc->ipsa_srcaddr, outassoc->ipsa_dstaddr,
803 		    outassoc->ipsa_addrfam);
804 		mutex_exit(&bucket->isaf_lock);
805 		if (inassoc == NULL) {
806 			/* Q: Do we wish to set haspeer == B_FALSE? */
807 			esp0dbg(("esp_age_bytes: "
808 			    "can't find peer for outbound.\n"));
809 			return (sadb_age_bytes(espstack->esp_pfkey_q, outassoc,
810 			    bytes, B_TRUE));
811 		}
812 	}
813 
814 	inrc = sadb_age_bytes(espstack->esp_pfkey_q, inassoc, bytes, B_TRUE);
815 	outrc = sadb_age_bytes(espstack->esp_pfkey_q, outassoc, bytes, B_FALSE);
816 
817 	/*
818 	 * REFRELE any peer SA.
819 	 *
820 	 * Because of the multi-line macro nature of IPSA_REFRELE, keep
821 	 * them in { }.
822 	 */
823 	if (inbound) {
824 		IPSA_REFRELE(outassoc);
825 	} else {
826 		IPSA_REFRELE(inassoc);
827 	}
828 
829 	return (inrc && outrc);
830 }
831 
832 /*
833  * Do incoming NAT-T manipulations for packet.
834  */
835 static ipsec_status_t
836 esp_fix_natt_checksums(mblk_t *data_mp, ipsa_t *assoc)
837 {
838 	ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
839 	tcpha_t *tcph;
840 	udpha_t *udpha;
841 	/* Initialize to our inbound cksum adjustment... */
842 	uint32_t sum = assoc->ipsa_inbound_cksum;
843 
844 	switch (ipha->ipha_protocol) {
845 	case IPPROTO_TCP:
846 		tcph = (tcpha_t *)(data_mp->b_rptr +
847 		    IPH_HDR_LENGTH(ipha));
848 
849 #define	DOWN_SUM(x) (x) = ((x) & 0xFFFF) +	 ((x) >> 16)
850 		sum += ~ntohs(tcph->tha_sum) & 0xFFFF;
851 		DOWN_SUM(sum);
852 		DOWN_SUM(sum);
853 		tcph->tha_sum = ~htons(sum);
854 		break;
855 	case IPPROTO_UDP:
856 		udpha = (udpha_t *)(data_mp->b_rptr + IPH_HDR_LENGTH(ipha));
857 
858 		if (udpha->uha_checksum != 0) {
859 			/* Adujst if the inbound one was not zero. */
860 			sum += ~ntohs(udpha->uha_checksum) & 0xFFFF;
861 			DOWN_SUM(sum);
862 			DOWN_SUM(sum);
863 			udpha->uha_checksum = ~htons(sum);
864 			if (udpha->uha_checksum == 0)
865 				udpha->uha_checksum = 0xFFFF;
866 		}
867 #undef DOWN_SUM
868 		break;
869 	case IPPROTO_IP:
870 		/*
871 		 * This case is only an issue for self-encapsulated
872 		 * packets.  So for now, fall through.
873 		 */
874 		break;
875 	}
876 	return (IPSEC_STATUS_SUCCESS);
877 }
878 
879 
880 /*
881  * Strip ESP header, check padding, and fix IP header.
882  * Returns B_TRUE on success, B_FALSE if an error occured.
883  */
884 static boolean_t
885 esp_strip_header(mblk_t *data_mp, boolean_t isv4, uint32_t ivlen,
886     kstat_named_t **counter, ipsecesp_stack_t *espstack)
887 {
888 	ipha_t *ipha;
889 	ip6_t *ip6h;
890 	uint_t divpoint;
891 	mblk_t *scratch;
892 	uint8_t nexthdr, padlen;
893 	uint8_t lastpad;
894 	ipsec_stack_t	*ipss = espstack->ipsecesp_netstack->netstack_ipsec;
895 	uint8_t *lastbyte;
896 
897 	/*
898 	 * Strip ESP data and fix IP header.
899 	 *
900 	 * XXX In case the beginning of esp_inbound() changes to not do a
901 	 * pullup, this part of the code can remain unchanged.
902 	 */
903 	if (isv4) {
904 		ASSERT((data_mp->b_wptr - data_mp->b_rptr) >= sizeof (ipha_t));
905 		ipha = (ipha_t *)data_mp->b_rptr;
906 		ASSERT((data_mp->b_wptr - data_mp->b_rptr) >= sizeof (esph_t) +
907 		    IPH_HDR_LENGTH(ipha));
908 		divpoint = IPH_HDR_LENGTH(ipha);
909 	} else {
910 		ASSERT((data_mp->b_wptr - data_mp->b_rptr) >= sizeof (ip6_t));
911 		ip6h = (ip6_t *)data_mp->b_rptr;
912 		divpoint = ip_hdr_length_v6(data_mp, ip6h);
913 	}
914 
915 	scratch = data_mp;
916 	while (scratch->b_cont != NULL)
917 		scratch = scratch->b_cont;
918 
919 	ASSERT((scratch->b_wptr - scratch->b_rptr) >= 3);
920 
921 	/*
922 	 * "Next header" and padding length are the last two bytes in the
923 	 * ESP-protected datagram, thus the explicit - 1 and - 2.
924 	 * lastpad is the last byte of the padding, which can be used for
925 	 * a quick check to see if the padding is correct.
926 	 */
927 	lastbyte = scratch->b_wptr - 1;
928 	nexthdr = *lastbyte--;
929 	padlen = *lastbyte--;
930 
931 	if (isv4) {
932 		/* Fix part of the IP header. */
933 		ipha->ipha_protocol = nexthdr;
934 		/*
935 		 * Reality check the padlen.  The explicit - 2 is for the
936 		 * padding length and the next-header bytes.
937 		 */
938 		if (padlen >= ntohs(ipha->ipha_length) - sizeof (ipha_t) - 2 -
939 		    sizeof (esph_t) - ivlen) {
940 			ESP_BUMP_STAT(espstack, bad_decrypt);
941 			ipsec_rl_strlog(espstack->ipsecesp_netstack,
942 			    info.mi_idnum, 0, 0,
943 			    SL_ERROR | SL_WARN,
944 			    "Corrupt ESP packet (padlen too big).\n");
945 			esp1dbg(espstack, ("padlen (%d) is greater than:\n",
946 			    padlen));
947 			esp1dbg(espstack, ("pkt len(%d) - ip hdr - esp "
948 			    "hdr - ivlen(%d) = %d.\n",
949 			    ntohs(ipha->ipha_length), ivlen,
950 			    (int)(ntohs(ipha->ipha_length) - sizeof (ipha_t) -
951 			    2 - sizeof (esph_t) - ivlen)));
952 			*counter = DROPPER(ipss, ipds_esp_bad_padlen);
953 			return (B_FALSE);
954 		}
955 
956 		/*
957 		 * Fix the rest of the header.  The explicit - 2 is for the
958 		 * padding length and the next-header bytes.
959 		 */
960 		ipha->ipha_length = htons(ntohs(ipha->ipha_length) - padlen -
961 		    2 - sizeof (esph_t) - ivlen);
962 		ipha->ipha_hdr_checksum = 0;
963 		ipha->ipha_hdr_checksum = (uint16_t)ip_csum_hdr(ipha);
964 	} else {
965 		if (ip6h->ip6_nxt == IPPROTO_ESP) {
966 			ip6h->ip6_nxt = nexthdr;
967 		} else {
968 			ip6_pkt_t ipp;
969 
970 			bzero(&ipp, sizeof (ipp));
971 			(void) ip_find_hdr_v6(data_mp, ip6h, &ipp, NULL);
972 			if (ipp.ipp_dstopts != NULL) {
973 				ipp.ipp_dstopts->ip6d_nxt = nexthdr;
974 			} else if (ipp.ipp_rthdr != NULL) {
975 				ipp.ipp_rthdr->ip6r_nxt = nexthdr;
976 			} else if (ipp.ipp_hopopts != NULL) {
977 				ipp.ipp_hopopts->ip6h_nxt = nexthdr;
978 			} else {
979 				/* Panic a DEBUG kernel. */
980 				ASSERT(ipp.ipp_hopopts != NULL);
981 				/* Otherwise, pretend it's IP + ESP. */
982 				cmn_err(CE_WARN, "ESP IPv6 headers wrong.\n");
983 				ip6h->ip6_nxt = nexthdr;
984 			}
985 		}
986 
987 		if (padlen >= ntohs(ip6h->ip6_plen) - 2 - sizeof (esph_t) -
988 		    ivlen) {
989 			ESP_BUMP_STAT(espstack, bad_decrypt);
990 			ipsec_rl_strlog(espstack->ipsecesp_netstack,
991 			    info.mi_idnum, 0, 0,
992 			    SL_ERROR | SL_WARN,
993 			    "Corrupt ESP packet (v6 padlen too big).\n");
994 			esp1dbg(espstack, ("padlen (%d) is greater than:\n",
995 			    padlen));
996 			esp1dbg(espstack,
997 			    ("pkt len(%u) - ip hdr - esp hdr - ivlen(%d) = "
998 			    "%u.\n", (unsigned)(ntohs(ip6h->ip6_plen)
999 			    + sizeof (ip6_t)), ivlen,
1000 			    (unsigned)(ntohs(ip6h->ip6_plen) - 2 -
1001 			    sizeof (esph_t) - ivlen)));
1002 			*counter = DROPPER(ipss, ipds_esp_bad_padlen);
1003 			return (B_FALSE);
1004 		}
1005 
1006 
1007 		/*
1008 		 * Fix the rest of the header.  The explicit - 2 is for the
1009 		 * padding length and the next-header bytes.  IPv6 is nice,
1010 		 * because there's no hdr checksum!
1011 		 */
1012 		ip6h->ip6_plen = htons(ntohs(ip6h->ip6_plen) - padlen -
1013 		    2 - sizeof (esph_t) - ivlen);
1014 	}
1015 
1016 	if (espstack->ipsecesp_padding_check > 0 && padlen > 0) {
1017 		/*
1018 		 * Weak padding check: compare last-byte to length, they
1019 		 * should be equal.
1020 		 */
1021 		lastpad = *lastbyte--;
1022 
1023 		if (padlen != lastpad) {
1024 			ipsec_rl_strlog(espstack->ipsecesp_netstack,
1025 			    info.mi_idnum, 0, 0, SL_ERROR | SL_WARN,
1026 			    "Corrupt ESP packet (lastpad != padlen).\n");
1027 			esp1dbg(espstack,
1028 			    ("lastpad (%d) not equal to padlen (%d):\n",
1029 			    lastpad, padlen));
1030 			ESP_BUMP_STAT(espstack, bad_padding);
1031 			*counter = DROPPER(ipss, ipds_esp_bad_padding);
1032 			return (B_FALSE);
1033 		}
1034 
1035 		/*
1036 		 * Strong padding check: Check all pad bytes to see that
1037 		 * they're ascending.  Go backwards using a descending counter
1038 		 * to verify.  padlen == 1 is checked by previous block, so
1039 		 * only bother if we've more than 1 byte of padding.
1040 		 * Consequently, start the check one byte before the location
1041 		 * of "lastpad".
1042 		 */
1043 		if (espstack->ipsecesp_padding_check > 1) {
1044 			/*
1045 			 * This assert may have to become an if and a pullup
1046 			 * if we start accepting multi-dblk mblks. For now,
1047 			 * though, any packet here will have been pulled up in
1048 			 * esp_inbound.
1049 			 */
1050 			ASSERT(MBLKL(scratch) >= lastpad + 3);
1051 
1052 			/*
1053 			 * Use "--lastpad" because we already checked the very
1054 			 * last pad byte previously.
1055 			 */
1056 			while (--lastpad != 0) {
1057 				if (lastpad != *lastbyte) {
1058 					ipsec_rl_strlog(
1059 					    espstack->ipsecesp_netstack,
1060 					    info.mi_idnum, 0, 0,
1061 					    SL_ERROR | SL_WARN, "Corrupt ESP "
1062 					    "packet (bad padding).\n");
1063 					esp1dbg(espstack,
1064 					    ("padding not in correct"
1065 					    " format:\n"));
1066 					ESP_BUMP_STAT(espstack, bad_padding);
1067 					*counter = DROPPER(ipss,
1068 					    ipds_esp_bad_padding);
1069 					return (B_FALSE);
1070 				}
1071 				lastbyte--;
1072 			}
1073 		}
1074 	}
1075 
1076 	/* Trim off the padding. */
1077 	ASSERT(data_mp->b_cont == NULL);
1078 	data_mp->b_wptr -= (padlen + 2);
1079 
1080 	/*
1081 	 * Remove the ESP header.
1082 	 *
1083 	 * The above assertions about data_mp's size will make this work.
1084 	 *
1085 	 * XXX  Question:  If I send up and get back a contiguous mblk,
1086 	 * would it be quicker to bcopy over, or keep doing the dupb stuff?
1087 	 * I go with copying for now.
1088 	 */
1089 
1090 	if (IS_P2ALIGNED(data_mp->b_rptr, sizeof (uint32_t)) &&
1091 	    IS_P2ALIGNED(ivlen, sizeof (uint32_t))) {
1092 		uint8_t *start = data_mp->b_rptr;
1093 		uint32_t *src, *dst;
1094 
1095 		src = (uint32_t *)(start + divpoint);
1096 		dst = (uint32_t *)(start + divpoint + sizeof (esph_t) + ivlen);
1097 
1098 		ASSERT(IS_P2ALIGNED(dst, sizeof (uint32_t)) &&
1099 		    IS_P2ALIGNED(src, sizeof (uint32_t)));
1100 
1101 		do {
1102 			src--;
1103 			dst--;
1104 			*dst = *src;
1105 		} while (src != (uint32_t *)start);
1106 
1107 		data_mp->b_rptr = (uchar_t *)dst;
1108 	} else {
1109 		uint8_t *start = data_mp->b_rptr;
1110 		uint8_t *src, *dst;
1111 
1112 		src = start + divpoint;
1113 		dst = src + sizeof (esph_t) + ivlen;
1114 
1115 		do {
1116 			src--;
1117 			dst--;
1118 			*dst = *src;
1119 		} while (src != start);
1120 
1121 		data_mp->b_rptr = dst;
1122 	}
1123 
1124 	esp2dbg(espstack, ("data_mp after inbound ESP adjustment:\n"));
1125 	esp2dbg(espstack, (dump_msg(data_mp)));
1126 
1127 	return (B_TRUE);
1128 }
1129 
1130 /*
1131  * Updating use times can be tricky business if the ipsa_haspeer flag is
1132  * set.  This function is called once in an SA's lifetime.
1133  *
1134  * Caller has to REFRELE "assoc" which is passed in.  This function has
1135  * to REFRELE any peer SA that is obtained.
1136  */
1137 static void
1138 esp_set_usetime(ipsa_t *assoc, boolean_t inbound)
1139 {
1140 	ipsa_t *inassoc, *outassoc;
1141 	isaf_t *bucket;
1142 	sadb_t *sp;
1143 	int outhash;
1144 	boolean_t isv6;
1145 	netstack_t		*ns = assoc->ipsa_netstack;
1146 	ipsecesp_stack_t	*espstack = ns->netstack_ipsecesp;
1147 
1148 	/* No peer?  No problem! */
1149 	if (!assoc->ipsa_haspeer) {
1150 		sadb_set_usetime(assoc);
1151 		return;
1152 	}
1153 
1154 	/*
1155 	 * Otherwise, we want to grab both the original assoc and its peer.
1156 	 * There might be a race for this, but if it's a real race, the times
1157 	 * will be out-of-synch by at most a second, and since our time
1158 	 * granularity is a second, this won't be a problem.
1159 	 *
1160 	 * If we need tight synchronization on the peer SA, then we need to
1161 	 * reconsider.
1162 	 */
1163 
1164 	/* Use address length to select IPv6/IPv4 */
1165 	isv6 = (assoc->ipsa_addrfam == AF_INET6);
1166 	sp = isv6 ? &espstack->esp_sadb.s_v6 : &espstack->esp_sadb.s_v4;
1167 
1168 	if (inbound) {
1169 		inassoc = assoc;
1170 		if (isv6) {
1171 			outhash = OUTBOUND_HASH_V6(sp, *((in6_addr_t *)
1172 			    &inassoc->ipsa_dstaddr));
1173 		} else {
1174 			outhash = OUTBOUND_HASH_V4(sp, *((ipaddr_t *)
1175 			    &inassoc->ipsa_dstaddr));
1176 		}
1177 		bucket = &sp->sdb_of[outhash];
1178 		mutex_enter(&bucket->isaf_lock);
1179 		outassoc = ipsec_getassocbyspi(bucket, inassoc->ipsa_spi,
1180 		    inassoc->ipsa_srcaddr, inassoc->ipsa_dstaddr,
1181 		    inassoc->ipsa_addrfam);
1182 		mutex_exit(&bucket->isaf_lock);
1183 		if (outassoc == NULL) {
1184 			/* Q: Do we wish to set haspeer == B_FALSE? */
1185 			esp0dbg(("esp_set_usetime: "
1186 			    "can't find peer for inbound.\n"));
1187 			sadb_set_usetime(inassoc);
1188 			return;
1189 		}
1190 	} else {
1191 		outassoc = assoc;
1192 		bucket = INBOUND_BUCKET(sp, outassoc->ipsa_spi);
1193 		mutex_enter(&bucket->isaf_lock);
1194 		inassoc = ipsec_getassocbyspi(bucket, outassoc->ipsa_spi,
1195 		    outassoc->ipsa_srcaddr, outassoc->ipsa_dstaddr,
1196 		    outassoc->ipsa_addrfam);
1197 		mutex_exit(&bucket->isaf_lock);
1198 		if (inassoc == NULL) {
1199 			/* Q: Do we wish to set haspeer == B_FALSE? */
1200 			esp0dbg(("esp_set_usetime: "
1201 			    "can't find peer for outbound.\n"));
1202 			sadb_set_usetime(outassoc);
1203 			return;
1204 		}
1205 	}
1206 
1207 	/* Update usetime on both. */
1208 	sadb_set_usetime(inassoc);
1209 	sadb_set_usetime(outassoc);
1210 
1211 	/*
1212 	 * REFRELE any peer SA.
1213 	 *
1214 	 * Because of the multi-line macro nature of IPSA_REFRELE, keep
1215 	 * them in { }.
1216 	 */
1217 	if (inbound) {
1218 		IPSA_REFRELE(outassoc);
1219 	} else {
1220 		IPSA_REFRELE(inassoc);
1221 	}
1222 }
1223 
1224 /*
1225  * Handle ESP inbound data for IPv4 and IPv6.
1226  * On success returns B_TRUE, on failure returns B_FALSE and frees the
1227  * mblk chain ipsec_in_mp.
1228  */
1229 ipsec_status_t
1230 esp_inbound(mblk_t *ipsec_in_mp, void *arg)
1231 {
1232 	mblk_t *data_mp = ipsec_in_mp->b_cont;
1233 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_in_mp->b_rptr;
1234 	esph_t *esph = (esph_t *)arg;
1235 	ipsa_t *ipsa = ii->ipsec_in_esp_sa;
1236 	netstack_t	*ns = ii->ipsec_in_ns;
1237 	ipsecesp_stack_t *espstack = ns->netstack_ipsecesp;
1238 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
1239 
1240 	/*
1241 	 * We may wish to check replay in-range-only here as an optimization.
1242 	 * Include the reality check of ipsa->ipsa_replay >
1243 	 * ipsa->ipsa_replay_wsize for times when it's the first N packets,
1244 	 * where N == ipsa->ipsa_replay_wsize.
1245 	 *
1246 	 * Another check that may come here later is the "collision" check.
1247 	 * If legitimate packets flow quickly enough, this won't be a problem,
1248 	 * but collisions may cause authentication algorithm crunching to
1249 	 * take place when it doesn't need to.
1250 	 */
1251 	if (!sadb_replay_peek(ipsa, esph->esph_replay)) {
1252 		ESP_BUMP_STAT(espstack, replay_early_failures);
1253 		IP_ESP_BUMP_STAT(ipss, in_discards);
1254 		/*
1255 		 * TODO: Extract inbound interface from the IPSEC_IN
1256 		 * message's ii->ipsec_in_rill_index.
1257 		 */
1258 		ip_drop_packet(ipsec_in_mp, B_TRUE, NULL, NULL,
1259 		    DROPPER(ipss, ipds_esp_early_replay),
1260 		    &espstack->esp_dropper);
1261 		return (IPSEC_STATUS_FAILED);
1262 	}
1263 
1264 	/*
1265 	 * Has this packet already been processed by a hardware
1266 	 * IPsec accelerator?
1267 	 */
1268 	if (ii->ipsec_in_accelerated) {
1269 		ipsec_status_t rv;
1270 		esp3dbg(espstack,
1271 		    ("esp_inbound: pkt processed by ill=%d isv6=%d\n",
1272 		    ii->ipsec_in_ill_index, !ii->ipsec_in_v4));
1273 		rv = esp_inbound_accelerated(ipsec_in_mp,
1274 		    data_mp, ii->ipsec_in_v4, ipsa);
1275 		return (rv);
1276 	}
1277 	ESP_BUMP_STAT(espstack, noaccel);
1278 
1279 	/*
1280 	 * Adjust the IP header's payload length to reflect the removal
1281 	 * of the ICV.
1282 	 */
1283 	if (!ii->ipsec_in_v4) {
1284 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
1285 		ip6h->ip6_plen = htons(ntohs(ip6h->ip6_plen) -
1286 		    ipsa->ipsa_mac_len);
1287 	} else {
1288 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
1289 		ipha->ipha_length = htons(ntohs(ipha->ipha_length) -
1290 		    ipsa->ipsa_mac_len);
1291 	}
1292 
1293 	/* submit the request to the crypto framework */
1294 	return (esp_submit_req_inbound(ipsec_in_mp, ipsa,
1295 	    (uint8_t *)esph - data_mp->b_rptr));
1296 }
1297 
1298 /*
1299  * Perform the really difficult work of inserting the proposed situation.
1300  * Called while holding the algorithm lock.
1301  */
1302 static void
1303 esp_insert_prop(sadb_prop_t *prop, ipsacq_t *acqrec, uint_t combs)
1304 {
1305 	sadb_comb_t *comb = (sadb_comb_t *)(prop + 1);
1306 	ipsec_out_t *io;
1307 	ipsec_action_t *ap;
1308 	ipsec_prot_t *prot;
1309 	netstack_t *ns;
1310 	ipsecesp_stack_t *espstack;
1311 	ipsec_stack_t *ipss;
1312 
1313 	io = (ipsec_out_t *)acqrec->ipsacq_mp->b_rptr;
1314 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
1315 	ns = io->ipsec_out_ns;
1316 	espstack = ns->netstack_ipsecesp;
1317 	ipss = ns->netstack_ipsec;
1318 	ASSERT(MUTEX_HELD(&ipss->ipsec_alg_lock));
1319 
1320 	prop->sadb_prop_exttype = SADB_EXT_PROPOSAL;
1321 	prop->sadb_prop_len = SADB_8TO64(sizeof (sadb_prop_t));
1322 	*(uint32_t *)(&prop->sadb_prop_replay) = 0;	/* Quick zero-out! */
1323 
1324 	prop->sadb_prop_replay = espstack->ipsecesp_replay_size;
1325 
1326 	/*
1327 	 * Based upon algorithm properties, and what-not, prioritize
1328 	 * a proposal.  If the IPSEC_OUT message has an algorithm specified,
1329 	 * use it first and foremost.
1330 	 *
1331 	 * For each action in policy list
1332 	 *   Add combination.  If I've hit limit, return.
1333 	 */
1334 
1335 	for (ap = acqrec->ipsacq_act; ap != NULL;
1336 	    ap = ap->ipa_next) {
1337 		ipsec_alginfo_t *ealg = NULL;
1338 		ipsec_alginfo_t *aalg = NULL;
1339 
1340 		if (ap->ipa_act.ipa_type != IPSEC_POLICY_APPLY)
1341 			continue;
1342 
1343 		prot = &ap->ipa_act.ipa_apply;
1344 
1345 		if (!(prot->ipp_use_esp))
1346 			continue;
1347 
1348 		if (prot->ipp_esp_auth_alg != 0) {
1349 			aalg = ipss->ipsec_alglists[IPSEC_ALG_AUTH]
1350 			    [prot->ipp_esp_auth_alg];
1351 			if (aalg == NULL || !ALG_VALID(aalg))
1352 				continue;
1353 		}
1354 
1355 		ASSERT(prot->ipp_encr_alg > 0);
1356 		ealg = ipss->ipsec_alglists[IPSEC_ALG_ENCR]
1357 		    [prot->ipp_encr_alg];
1358 		if (ealg == NULL || !ALG_VALID(ealg))
1359 			continue;
1360 
1361 		comb->sadb_comb_flags = 0;
1362 		comb->sadb_comb_reserved = 0;
1363 		comb->sadb_comb_encrypt = ealg->alg_id;
1364 		comb->sadb_comb_encrypt_minbits =
1365 		    MAX(prot->ipp_espe_minbits, ealg->alg_ef_minbits);
1366 		comb->sadb_comb_encrypt_maxbits =
1367 		    MIN(prot->ipp_espe_maxbits, ealg->alg_ef_maxbits);
1368 		if (aalg == NULL) {
1369 			comb->sadb_comb_auth = 0;
1370 			comb->sadb_comb_auth_minbits = 0;
1371 			comb->sadb_comb_auth_maxbits = 0;
1372 		} else {
1373 			comb->sadb_comb_auth = aalg->alg_id;
1374 			comb->sadb_comb_auth_minbits =
1375 			    MAX(prot->ipp_espa_minbits, aalg->alg_ef_minbits);
1376 			comb->sadb_comb_auth_maxbits =
1377 			    MIN(prot->ipp_espa_maxbits, aalg->alg_ef_maxbits);
1378 		}
1379 
1380 		/*
1381 		 * The following may be based on algorithm
1382 		 * properties, but in the meantime, we just pick
1383 		 * some good, sensible numbers.  Key mgmt. can
1384 		 * (and perhaps should) be the place to finalize
1385 		 * such decisions.
1386 		 */
1387 
1388 		/*
1389 		 * No limits on allocations, since we really don't
1390 		 * support that concept currently.
1391 		 */
1392 		comb->sadb_comb_soft_allocations = 0;
1393 		comb->sadb_comb_hard_allocations = 0;
1394 
1395 		/*
1396 		 * These may want to come from policy rule..
1397 		 */
1398 		comb->sadb_comb_soft_bytes =
1399 		    espstack->ipsecesp_default_soft_bytes;
1400 		comb->sadb_comb_hard_bytes =
1401 		    espstack->ipsecesp_default_hard_bytes;
1402 		comb->sadb_comb_soft_addtime =
1403 		    espstack->ipsecesp_default_soft_addtime;
1404 		comb->sadb_comb_hard_addtime =
1405 		    espstack->ipsecesp_default_hard_addtime;
1406 		comb->sadb_comb_soft_usetime =
1407 		    espstack->ipsecesp_default_soft_usetime;
1408 		comb->sadb_comb_hard_usetime =
1409 		    espstack->ipsecesp_default_hard_usetime;
1410 
1411 		prop->sadb_prop_len += SADB_8TO64(sizeof (*comb));
1412 		if (--combs == 0)
1413 			break;	/* out of space.. */
1414 		comb++;
1415 	}
1416 }
1417 
1418 /*
1419  * Prepare and actually send the SADB_ACQUIRE message to PF_KEY.
1420  */
1421 static void
1422 esp_send_acquire(ipsacq_t *acqrec, mblk_t *extended, netstack_t *ns)
1423 {
1424 	uint_t combs;
1425 	sadb_msg_t *samsg;
1426 	sadb_prop_t *prop;
1427 	mblk_t *pfkeymp, *msgmp;
1428 	ipsecesp_stack_t *espstack = ns->netstack_ipsecesp;
1429 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
1430 
1431 	ESP_BUMP_STAT(espstack, acquire_requests);
1432 
1433 	if (espstack->esp_pfkey_q == NULL)
1434 		return;
1435 
1436 	/* Set up ACQUIRE. */
1437 	pfkeymp = sadb_setup_acquire(acqrec, SADB_SATYPE_ESP,
1438 	    ns->netstack_ipsec);
1439 	if (pfkeymp == NULL) {
1440 		esp0dbg(("sadb_setup_acquire failed.\n"));
1441 		return;
1442 	}
1443 	ASSERT(MUTEX_HELD(&ipss->ipsec_alg_lock));
1444 	combs = ipss->ipsec_nalgs[IPSEC_ALG_AUTH] *
1445 	    ipss->ipsec_nalgs[IPSEC_ALG_ENCR];
1446 	msgmp = pfkeymp->b_cont;
1447 	samsg = (sadb_msg_t *)(msgmp->b_rptr);
1448 
1449 	/* Insert proposal here. */
1450 
1451 	prop = (sadb_prop_t *)(((uint64_t *)samsg) + samsg->sadb_msg_len);
1452 	esp_insert_prop(prop, acqrec, combs);
1453 	samsg->sadb_msg_len += prop->sadb_prop_len;
1454 	msgmp->b_wptr += SADB_64TO8(samsg->sadb_msg_len);
1455 
1456 	mutex_exit(&ipss->ipsec_alg_lock);
1457 
1458 	/*
1459 	 * Must mutex_exit() before sending PF_KEY message up, in
1460 	 * order to avoid recursive mutex_enter() if there are no registered
1461 	 * listeners.
1462 	 *
1463 	 * Once I've sent the message, I'm cool anyway.
1464 	 */
1465 	mutex_exit(&acqrec->ipsacq_lock);
1466 	if (extended != NULL) {
1467 		putnext(espstack->esp_pfkey_q, extended);
1468 	}
1469 	putnext(espstack->esp_pfkey_q, pfkeymp);
1470 }
1471 
1472 /*
1473  * Handle the SADB_GETSPI message.  Create a larval SA.
1474  */
1475 static void
1476 esp_getspi(mblk_t *mp, keysock_in_t *ksi, ipsecesp_stack_t *espstack)
1477 {
1478 	ipsa_t *newbie, *target;
1479 	isaf_t *outbound, *inbound;
1480 	int rc, diagnostic;
1481 	sadb_sa_t *assoc;
1482 	keysock_out_t *kso;
1483 	uint32_t newspi;
1484 
1485 	/*
1486 	 * Randomly generate a proposed SPI value
1487 	 */
1488 	(void) random_get_pseudo_bytes((uint8_t *)&newspi, sizeof (uint32_t));
1489 	newbie = sadb_getspi(ksi, newspi, &diagnostic,
1490 	    espstack->ipsecesp_netstack);
1491 
1492 	if (newbie == NULL) {
1493 		sadb_pfkey_error(espstack->esp_pfkey_q, mp, ENOMEM, diagnostic,
1494 		    ksi->ks_in_serial);
1495 		return;
1496 	} else if (newbie == (ipsa_t *)-1) {
1497 		sadb_pfkey_error(espstack->esp_pfkey_q, mp, EINVAL, diagnostic,
1498 		    ksi->ks_in_serial);
1499 		return;
1500 	}
1501 
1502 	/*
1503 	 * XXX - We may randomly collide.  We really should recover from this.
1504 	 *	 Unfortunately, that could require spending way-too-much-time
1505 	 *	 in here.  For now, let the user retry.
1506 	 */
1507 
1508 	if (newbie->ipsa_addrfam == AF_INET6) {
1509 		outbound = OUTBOUND_BUCKET_V6(&espstack->esp_sadb.s_v6,
1510 		    *(uint32_t *)(newbie->ipsa_dstaddr));
1511 		inbound = INBOUND_BUCKET(&espstack->esp_sadb.s_v6,
1512 		    newbie->ipsa_spi);
1513 	} else {
1514 		ASSERT(newbie->ipsa_addrfam == AF_INET);
1515 		outbound = OUTBOUND_BUCKET_V4(&espstack->esp_sadb.s_v4,
1516 		    *(uint32_t *)(newbie->ipsa_dstaddr));
1517 		inbound = INBOUND_BUCKET(&espstack->esp_sadb.s_v4,
1518 		    newbie->ipsa_spi);
1519 	}
1520 
1521 	mutex_enter(&outbound->isaf_lock);
1522 	mutex_enter(&inbound->isaf_lock);
1523 
1524 	/*
1525 	 * Check for collisions (i.e. did sadb_getspi() return with something
1526 	 * that already exists?).
1527 	 *
1528 	 * Try outbound first.  Even though SADB_GETSPI is traditionally
1529 	 * for inbound SAs, you never know what a user might do.
1530 	 */
1531 	target = ipsec_getassocbyspi(outbound, newbie->ipsa_spi,
1532 	    newbie->ipsa_srcaddr, newbie->ipsa_dstaddr, newbie->ipsa_addrfam);
1533 	if (target == NULL) {
1534 		target = ipsec_getassocbyspi(inbound, newbie->ipsa_spi,
1535 		    newbie->ipsa_srcaddr, newbie->ipsa_dstaddr,
1536 		    newbie->ipsa_addrfam);
1537 	}
1538 
1539 	/*
1540 	 * I don't have collisions elsewhere!
1541 	 * (Nor will I because I'm still holding inbound/outbound locks.)
1542 	 */
1543 
1544 	if (target != NULL) {
1545 		rc = EEXIST;
1546 		IPSA_REFRELE(target);
1547 	} else {
1548 		/*
1549 		 * sadb_insertassoc() also checks for collisions, so
1550 		 * if there's a colliding entry, rc will be set
1551 		 * to EEXIST.
1552 		 */
1553 		rc = sadb_insertassoc(newbie, inbound);
1554 		newbie->ipsa_hardexpiretime = gethrestime_sec();
1555 		newbie->ipsa_hardexpiretime +=
1556 		    espstack->ipsecesp_larval_timeout;
1557 	}
1558 
1559 	/*
1560 	 * Can exit outbound mutex.  Hold inbound until we're done
1561 	 * with newbie.
1562 	 */
1563 	mutex_exit(&outbound->isaf_lock);
1564 
1565 	if (rc != 0) {
1566 		mutex_exit(&inbound->isaf_lock);
1567 		IPSA_REFRELE(newbie);
1568 		sadb_pfkey_error(espstack->esp_pfkey_q, mp, rc,
1569 		    SADB_X_DIAGNOSTIC_NONE, ksi->ks_in_serial);
1570 		return;
1571 	}
1572 
1573 
1574 	/* Can write here because I'm still holding the bucket lock. */
1575 	newbie->ipsa_type = SADB_SATYPE_ESP;
1576 
1577 	/*
1578 	 * Construct successful return message. We have one thing going
1579 	 * for us in PF_KEY v2.  That's the fact that
1580 	 *	sizeof (sadb_spirange_t) == sizeof (sadb_sa_t)
1581 	 */
1582 	assoc = (sadb_sa_t *)ksi->ks_in_extv[SADB_EXT_SPIRANGE];
1583 	assoc->sadb_sa_exttype = SADB_EXT_SA;
1584 	assoc->sadb_sa_spi = newbie->ipsa_spi;
1585 	*((uint64_t *)(&assoc->sadb_sa_replay)) = 0;
1586 	mutex_exit(&inbound->isaf_lock);
1587 
1588 	/* Convert KEYSOCK_IN to KEYSOCK_OUT. */
1589 	kso = (keysock_out_t *)ksi;
1590 	kso->ks_out_len = sizeof (*kso);
1591 	kso->ks_out_serial = ksi->ks_in_serial;
1592 	kso->ks_out_type = KEYSOCK_OUT;
1593 
1594 	/*
1595 	 * Can safely putnext() to esp_pfkey_q, because this is a turnaround
1596 	 * from the esp_pfkey_q.
1597 	 */
1598 	putnext(espstack->esp_pfkey_q, mp);
1599 }
1600 
1601 /*
1602  * Insert the ESP header into a packet.  Duplicate an mblk, and insert a newly
1603  * allocated mblk with the ESP header in between the two.
1604  */
1605 static boolean_t
1606 esp_insert_esp(mblk_t *mp, mblk_t *esp_mp, uint_t divpoint,
1607     ipsecesp_stack_t *espstack)
1608 {
1609 	mblk_t *split_mp = mp;
1610 	uint_t wheretodiv = divpoint;
1611 
1612 	while ((split_mp->b_wptr - split_mp->b_rptr) < wheretodiv) {
1613 		wheretodiv -= (split_mp->b_wptr - split_mp->b_rptr);
1614 		split_mp = split_mp->b_cont;
1615 		ASSERT(split_mp != NULL);
1616 	}
1617 
1618 	if (split_mp->b_wptr - split_mp->b_rptr != wheretodiv) {
1619 		mblk_t *scratch;
1620 
1621 		/* "scratch" is the 2nd half, split_mp is the first. */
1622 		scratch = dupb(split_mp);
1623 		if (scratch == NULL) {
1624 			esp1dbg(espstack,
1625 			    ("esp_insert_esp: can't allocate scratch.\n"));
1626 			return (B_FALSE);
1627 		}
1628 		/* NOTE:  dupb() doesn't set b_cont appropriately. */
1629 		scratch->b_cont = split_mp->b_cont;
1630 		scratch->b_rptr += wheretodiv;
1631 		split_mp->b_wptr = split_mp->b_rptr + wheretodiv;
1632 		split_mp->b_cont = scratch;
1633 	}
1634 	/*
1635 	 * At this point, split_mp is exactly "wheretodiv" bytes long, and
1636 	 * holds the end of the pre-ESP part of the datagram.
1637 	 */
1638 	esp_mp->b_cont = split_mp->b_cont;
1639 	split_mp->b_cont = esp_mp;
1640 
1641 	return (B_TRUE);
1642 }
1643 
1644 /*
1645  * Section 7 of RFC 3947 says:
1646  *
1647  * 7.  Recovering from the Expiring NAT Mappings
1648  *
1649  *    There are cases where NAT box decides to remove mappings that are still
1650  *    alive (for example, when the keepalive interval is too long, or when the
1651  *    NAT box is rebooted).  To recover from this, ends that are NOT behind
1652  *    NAT SHOULD use the last valid UDP encapsulated IKE or IPsec packet from
1653  *    the other end to determine which IP and port addresses should be used.
1654  *    The host behind dynamic NAT MUST NOT do this, as otherwise it opens a
1655  *    DoS attack possibility because the IP address or port of the other host
1656  *    will not change (it is not behind NAT).
1657  *
1658  *    Keepalives cannot be used for these purposes, as they are not
1659  *    authenticated, but any IKE authenticated IKE packet or ESP packet can be
1660  *    used to detect whether the IP address or the port has changed.
1661  *
1662  * The following function will check an SA and its explicitly-set pair to see
1663  * if the NAT-T remote port matches the received packet (which must have
1664  * passed ESP authentication, see esp_in_done() for the caller context).  If
1665  * there is a mismatch, the SAs are updated.  It is not important if we race
1666  * with a transmitting thread, as if there is a transmitting thread, it will
1667  * merely emit a packet that will most-likely be dropped.
1668  *
1669  * "ports" are ordered src,dst, and assoc is an inbound SA, where src should
1670  * match ipsa_remote_nat_port and dst should match ipsa_local_nat_port.
1671  */
1672 #ifdef _LITTLE_ENDIAN
1673 #define	FIRST_16(x) ((x) & 0xFFFF)
1674 #define	NEXT_16(x) (((x) >> 16) & 0xFFFF)
1675 #else
1676 #define	FIRST_16(x) (((x) >> 16) & 0xFFFF)
1677 #define	NEXT_16(x) ((x) & 0xFFFF)
1678 #endif
1679 static void
1680 esp_port_freshness(uint32_t ports, ipsa_t *assoc)
1681 {
1682 	uint16_t remote = FIRST_16(ports);
1683 	uint16_t local = NEXT_16(ports);
1684 	ipsa_t *outbound_peer;
1685 	isaf_t *bucket;
1686 	ipsecesp_stack_t *espstack = assoc->ipsa_netstack->netstack_ipsecesp;
1687 
1688 	/* We found a conn_t, therefore local != 0. */
1689 	ASSERT(local != 0);
1690 	/* Assume an IPv4 SA. */
1691 	ASSERT(assoc->ipsa_addrfam == AF_INET);
1692 
1693 	/*
1694 	 * On-the-wire rport == 0 means something's very wrong.
1695 	 * An unpaired SA is also useless to us.
1696 	 * If we are behind the NAT, don't bother.
1697 	 * A zero local NAT port defaults to 4500, so check that too.
1698 	 * And, of course, if the ports already match, we don't need to
1699 	 * bother.
1700 	 */
1701 	if (remote == 0 || assoc->ipsa_otherspi == 0 ||
1702 	    (assoc->ipsa_flags & IPSA_F_BEHIND_NAT) ||
1703 	    (assoc->ipsa_remote_nat_port == 0 &&
1704 	    remote == htons(IPPORT_IKE_NATT)) ||
1705 	    remote == assoc->ipsa_remote_nat_port)
1706 		return;
1707 
1708 	/* Try and snag the peer.   NOTE:  Assume IPv4 for now. */
1709 	bucket = OUTBOUND_BUCKET_V4(&(espstack->esp_sadb.s_v4),
1710 	    assoc->ipsa_srcaddr[0]);
1711 	mutex_enter(&bucket->isaf_lock);
1712 	outbound_peer = ipsec_getassocbyspi(bucket, assoc->ipsa_otherspi,
1713 	    assoc->ipsa_dstaddr, assoc->ipsa_srcaddr, AF_INET);
1714 	mutex_exit(&bucket->isaf_lock);
1715 
1716 	/* We probably lost a race to a deleting or expiring thread. */
1717 	if (outbound_peer == NULL)
1718 		return;
1719 
1720 	/*
1721 	 * Hold the mutexes for both SAs so we don't race another inbound
1722 	 * thread.  A lock-entry order shouldn't matter, since all other
1723 	 * per-ipsa locks are individually held-then-released.
1724 	 *
1725 	 * Luckily, this has nothing to do with the remote-NAT address,
1726 	 * so we don't have to re-scribble the cached-checksum differential.
1727 	 */
1728 	mutex_enter(&outbound_peer->ipsa_lock);
1729 	mutex_enter(&assoc->ipsa_lock);
1730 	outbound_peer->ipsa_remote_nat_port = assoc->ipsa_remote_nat_port =
1731 	    remote;
1732 	mutex_exit(&assoc->ipsa_lock);
1733 	mutex_exit(&outbound_peer->ipsa_lock);
1734 	IPSA_REFRELE(outbound_peer);
1735 	ESP_BUMP_STAT(espstack, sa_port_renumbers);
1736 }
1737 
1738 /*
1739  * Finish processing of an inbound ESP packet after processing by the
1740  * crypto framework.
1741  * - Remove the ESP header.
1742  * - Send packet back to IP.
1743  * If authentication was performed on the packet, this function is called
1744  * only if the authentication succeeded.
1745  * On success returns B_TRUE, on failure returns B_FALSE and frees the
1746  * mblk chain ipsec_in_mp.
1747  */
1748 static ipsec_status_t
1749 esp_in_done(mblk_t *ipsec_in_mp)
1750 {
1751 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_in_mp->b_rptr;
1752 	mblk_t *data_mp;
1753 	ipsa_t *assoc;
1754 	uint_t espstart;
1755 	uint32_t ivlen = 0;
1756 	uint_t processed_len;
1757 	esph_t *esph;
1758 	kstat_named_t *counter;
1759 	boolean_t is_natt;
1760 	netstack_t	*ns = ii->ipsec_in_ns;
1761 	ipsecesp_stack_t *espstack = ns->netstack_ipsecesp;
1762 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
1763 
1764 	assoc = ii->ipsec_in_esp_sa;
1765 	ASSERT(assoc != NULL);
1766 
1767 	is_natt = ((assoc->ipsa_flags & IPSA_F_NATT) != 0);
1768 
1769 	/* get the pointer to the ESP header */
1770 	if (assoc->ipsa_encr_alg == SADB_EALG_NULL) {
1771 		/* authentication-only ESP */
1772 		espstart = ii->ipsec_in_crypto_data.cd_offset;
1773 		processed_len = ii->ipsec_in_crypto_data.cd_length;
1774 	} else {
1775 		/* encryption present */
1776 		ivlen = assoc->ipsa_iv_len;
1777 		if (assoc->ipsa_auth_alg == SADB_AALG_NONE) {
1778 			/* encryption-only ESP */
1779 			espstart = ii->ipsec_in_crypto_data.cd_offset -
1780 			    sizeof (esph_t) - assoc->ipsa_iv_len;
1781 			processed_len = ii->ipsec_in_crypto_data.cd_length +
1782 			    ivlen;
1783 		} else {
1784 			/* encryption with authentication */
1785 			espstart = ii->ipsec_in_crypto_dual_data.dd_offset1;
1786 			processed_len = ii->ipsec_in_crypto_dual_data.dd_len2 +
1787 			    ivlen;
1788 		}
1789 	}
1790 
1791 	data_mp = ipsec_in_mp->b_cont;
1792 	esph = (esph_t *)(data_mp->b_rptr + espstart);
1793 
1794 	if (assoc->ipsa_auth_alg != IPSA_AALG_NONE) {
1795 		/* authentication passed if we reach this point */
1796 		ESP_BUMP_STAT(espstack, good_auth);
1797 		data_mp->b_wptr -= assoc->ipsa_mac_len;
1798 
1799 		/*
1800 		 * Check replay window here!
1801 		 * For right now, assume keysock will set the replay window
1802 		 * size to zero for SAs that have an unspecified sender.
1803 		 * This may change...
1804 		 */
1805 
1806 		if (!sadb_replay_check(assoc, esph->esph_replay)) {
1807 			/*
1808 			 * Log the event. As of now we print out an event.
1809 			 * Do not print the replay failure number, or else
1810 			 * syslog cannot collate the error messages.  Printing
1811 			 * the replay number that failed opens a denial-of-
1812 			 * service attack.
1813 			 */
1814 			ipsec_assocfailure(info.mi_idnum, 0, 0,
1815 			    SL_ERROR | SL_WARN,
1816 			    "Replay failed for ESP spi 0x%x, dst %s.\n",
1817 			    assoc->ipsa_spi, assoc->ipsa_dstaddr,
1818 			    assoc->ipsa_addrfam, espstack->ipsecesp_netstack);
1819 			ESP_BUMP_STAT(espstack, replay_failures);
1820 			counter = DROPPER(ipss, ipds_esp_replay);
1821 			goto drop_and_bail;
1822 		}
1823 
1824 		if (is_natt)
1825 			esp_port_freshness(ii->ipsec_in_esp_udp_ports, assoc);
1826 	}
1827 
1828 	esp_set_usetime(assoc, B_TRUE);
1829 
1830 	if (!esp_age_bytes(assoc, processed_len, B_TRUE)) {
1831 		/* The ipsa has hit hard expiration, LOG and AUDIT. */
1832 		ipsec_assocfailure(info.mi_idnum, 0, 0,
1833 		    SL_ERROR | SL_WARN,
1834 		    "ESP association 0x%x, dst %s had bytes expire.\n",
1835 		    assoc->ipsa_spi, assoc->ipsa_dstaddr, assoc->ipsa_addrfam,
1836 		    espstack->ipsecesp_netstack);
1837 		ESP_BUMP_STAT(espstack, bytes_expired);
1838 		counter = DROPPER(ipss, ipds_esp_bytes_expire);
1839 		goto drop_and_bail;
1840 	}
1841 
1842 	/*
1843 	 * Remove ESP header and padding from packet.  I hope the compiler
1844 	 * spews "branch, predict taken" code for this.
1845 	 */
1846 
1847 	if (esp_strip_header(data_mp, ii->ipsec_in_v4, ivlen, &counter,
1848 	    espstack)) {
1849 		if (is_natt)
1850 			return (esp_fix_natt_checksums(data_mp, assoc));
1851 		return (IPSEC_STATUS_SUCCESS);
1852 	}
1853 
1854 	esp1dbg(espstack, ("esp_in_done: esp_strip_header() failed\n"));
1855 drop_and_bail:
1856 	IP_ESP_BUMP_STAT(ipss, in_discards);
1857 	/*
1858 	 * TODO: Extract inbound interface from the IPSEC_IN message's
1859 	 * ii->ipsec_in_rill_index.
1860 	 */
1861 	ip_drop_packet(ipsec_in_mp, B_TRUE, NULL, NULL, counter,
1862 	    &espstack->esp_dropper);
1863 	return (IPSEC_STATUS_FAILED);
1864 }
1865 
1866 /*
1867  * Called upon failing the inbound ICV check. The message passed as
1868  * argument is freed.
1869  */
1870 static void
1871 esp_log_bad_auth(mblk_t *ipsec_in)
1872 {
1873 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_in->b_rptr;
1874 	ipsa_t *assoc = ii->ipsec_in_esp_sa;
1875 	netstack_t	*ns = ii->ipsec_in_ns;
1876 	ipsecesp_stack_t *espstack = ns->netstack_ipsecesp;
1877 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
1878 
1879 	/*
1880 	 * Log the event. Don't print to the console, block
1881 	 * potential denial-of-service attack.
1882 	 */
1883 	ESP_BUMP_STAT(espstack, bad_auth);
1884 
1885 	ipsec_assocfailure(info.mi_idnum, 0, 0, SL_ERROR | SL_WARN,
1886 	    "ESP Authentication failed for spi 0x%x, dst %s.\n",
1887 	    assoc->ipsa_spi, assoc->ipsa_dstaddr, assoc->ipsa_addrfam,
1888 	    espstack->ipsecesp_netstack);
1889 
1890 	IP_ESP_BUMP_STAT(ipss, in_discards);
1891 	/*
1892 	 * TODO: Extract inbound interface from the IPSEC_IN
1893 	 * message's ii->ipsec_in_rill_index.
1894 	 */
1895 	ip_drop_packet(ipsec_in, B_TRUE, NULL, NULL,
1896 	    DROPPER(ipss, ipds_esp_bad_auth),
1897 	    &espstack->esp_dropper);
1898 }
1899 
1900 
1901 /*
1902  * Invoked for outbound packets after ESP processing. If the packet
1903  * also requires AH, performs the AH SA selection and AH processing.
1904  * Returns B_TRUE if the AH processing was not needed or if it was
1905  * performed successfully. Returns B_FALSE and consumes the passed mblk
1906  * if AH processing was required but could not be performed.
1907  */
1908 static boolean_t
1909 esp_do_outbound_ah(mblk_t *ipsec_mp)
1910 {
1911 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
1912 	ipsec_status_t ipsec_rc;
1913 	ipsec_action_t *ap;
1914 
1915 	ap = io->ipsec_out_act;
1916 	if (ap == NULL) {
1917 		ipsec_policy_t *pp = io->ipsec_out_policy;
1918 		ap = pp->ipsp_act;
1919 	}
1920 
1921 	if (!ap->ipa_want_ah)
1922 		return (B_TRUE);
1923 
1924 	ASSERT(io->ipsec_out_ah_done == B_FALSE);
1925 
1926 	if (io->ipsec_out_ah_sa == NULL) {
1927 		if (!ipsec_outbound_sa(ipsec_mp, IPPROTO_AH)) {
1928 			sadb_acquire(ipsec_mp, io, B_TRUE, B_FALSE);
1929 			return (B_FALSE);
1930 		}
1931 	}
1932 	ASSERT(io->ipsec_out_ah_sa != NULL);
1933 
1934 	io->ipsec_out_ah_done = B_TRUE;
1935 	ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
1936 	return (ipsec_rc == IPSEC_STATUS_SUCCESS);
1937 }
1938 
1939 
1940 /*
1941  * Kernel crypto framework callback invoked after completion of async
1942  * crypto requests.
1943  */
1944 static void
1945 esp_kcf_callback(void *arg, int status)
1946 {
1947 	mblk_t *ipsec_mp = (mblk_t *)arg;
1948 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
1949 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
1950 	boolean_t is_inbound = (ii->ipsec_in_type == IPSEC_IN);
1951 	netstackid_t	stackid;
1952 	netstack_t	*ns, *ns_arg;
1953 	ipsecesp_stack_t *espstack;
1954 	ipsec_stack_t	*ipss;
1955 
1956 	ASSERT(ipsec_mp->b_cont != NULL);
1957 
1958 	if (is_inbound) {
1959 		stackid = ii->ipsec_in_stackid;
1960 		ns_arg = ii->ipsec_in_ns;
1961 	} else {
1962 		stackid = io->ipsec_out_stackid;
1963 		ns_arg = io->ipsec_out_ns;
1964 	}
1965 
1966 	/*
1967 	 * Verify that the netstack is still around; could have vanished
1968 	 * while kEf was doing its work.
1969 	 */
1970 	ns = netstack_find_by_stackid(stackid);
1971 	if (ns == NULL || ns != ns_arg) {
1972 		/* Disappeared on us */
1973 		if (ns != NULL)
1974 			netstack_rele(ns);
1975 		freemsg(ipsec_mp);
1976 		return;
1977 	}
1978 
1979 	espstack = ns->netstack_ipsecesp;
1980 	ipss = ns->netstack_ipsec;
1981 
1982 	if (status == CRYPTO_SUCCESS) {
1983 		if (is_inbound) {
1984 			if (esp_in_done(ipsec_mp) != IPSEC_STATUS_SUCCESS) {
1985 				netstack_rele(ns);
1986 				return;
1987 			}
1988 			/* finish IPsec processing */
1989 			ip_fanout_proto_again(ipsec_mp, NULL, NULL, NULL);
1990 		} else {
1991 			/*
1992 			 * If a ICV was computed, it was stored by the
1993 			 * crypto framework at the end of the packet.
1994 			 */
1995 			ipha_t *ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
1996 
1997 			esp_set_usetime(io->ipsec_out_esp_sa, B_FALSE);
1998 			/* NAT-T packet. */
1999 			if (ipha->ipha_protocol == IPPROTO_UDP)
2000 				esp_prepare_udp(ns, ipsec_mp->b_cont, ipha);
2001 
2002 			/* do AH processing if needed */
2003 			if (!esp_do_outbound_ah(ipsec_mp)) {
2004 				netstack_rele(ns);
2005 				return;
2006 			}
2007 			/* finish IPsec processing */
2008 			if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
2009 				ip_wput_ipsec_out(NULL, ipsec_mp, ipha, NULL,
2010 				    NULL);
2011 			} else {
2012 				ip6_t *ip6h = (ip6_t *)ipha;
2013 				ip_wput_ipsec_out_v6(NULL, ipsec_mp, ip6h,
2014 				    NULL, NULL);
2015 			}
2016 		}
2017 
2018 	} else if (status == CRYPTO_INVALID_MAC) {
2019 		esp_log_bad_auth(ipsec_mp);
2020 
2021 	} else {
2022 		esp1dbg(espstack,
2023 		    ("esp_kcf_callback: crypto failed with 0x%x\n",
2024 		    status));
2025 		ESP_BUMP_STAT(espstack, crypto_failures);
2026 		if (is_inbound)
2027 			IP_ESP_BUMP_STAT(ipss, in_discards);
2028 		else
2029 			ESP_BUMP_STAT(espstack, out_discards);
2030 		ip_drop_packet(ipsec_mp, is_inbound, NULL, NULL,
2031 		    DROPPER(ipss, ipds_esp_crypto_failed),
2032 		    &espstack->esp_dropper);
2033 	}
2034 	netstack_rele(ns);
2035 }
2036 
2037 /*
2038  * Invoked on crypto framework failure during inbound and outbound processing.
2039  */
2040 static void
2041 esp_crypto_failed(mblk_t *mp, boolean_t is_inbound, int kef_rc,
2042     ipsecesp_stack_t *espstack)
2043 {
2044 	ipsec_stack_t	*ipss = espstack->ipsecesp_netstack->netstack_ipsec;
2045 
2046 	esp1dbg(espstack, ("crypto failed for %s ESP with 0x%x\n",
2047 	    is_inbound ? "inbound" : "outbound", kef_rc));
2048 	ip_drop_packet(mp, is_inbound, NULL, NULL,
2049 	    DROPPER(ipss, ipds_esp_crypto_failed),
2050 	    &espstack->esp_dropper);
2051 	ESP_BUMP_STAT(espstack, crypto_failures);
2052 	if (is_inbound)
2053 		IP_ESP_BUMP_STAT(ipss, in_discards);
2054 	else
2055 		ESP_BUMP_STAT(espstack, out_discards);
2056 }
2057 
2058 #define	ESP_INIT_CALLREQ(_cr) {						\
2059 	(_cr)->cr_flag = CRYPTO_SKIP_REQID|CRYPTO_RESTRICTED;		\
2060 	(_cr)->cr_callback_arg = ipsec_mp;				\
2061 	(_cr)->cr_callback_func = esp_kcf_callback;			\
2062 }
2063 
2064 #define	ESP_INIT_CRYPTO_MAC(mac, icvlen, icvbuf) {			\
2065 	(mac)->cd_format = CRYPTO_DATA_RAW;				\
2066 	(mac)->cd_offset = 0;						\
2067 	(mac)->cd_length = icvlen;					\
2068 	(mac)->cd_raw.iov_base = (char *)icvbuf;			\
2069 	(mac)->cd_raw.iov_len = icvlen;					\
2070 }
2071 
2072 #define	ESP_INIT_CRYPTO_DATA(data, mp, off, len) {			\
2073 	if (MBLKL(mp) >= (len) + (off)) {				\
2074 		(data)->cd_format = CRYPTO_DATA_RAW;			\
2075 		(data)->cd_raw.iov_base = (char *)(mp)->b_rptr;		\
2076 		(data)->cd_raw.iov_len = MBLKL(mp);			\
2077 		(data)->cd_offset = off;				\
2078 	} else {							\
2079 		(data)->cd_format = CRYPTO_DATA_MBLK;			\
2080 		(data)->cd_mp = mp;			       		\
2081 		(data)->cd_offset = off;				\
2082 	}								\
2083 	(data)->cd_length = len;					\
2084 }
2085 
2086 #define	ESP_INIT_CRYPTO_DUAL_DATA(data, mp, off1, len1, off2, len2) {	\
2087 	(data)->dd_format = CRYPTO_DATA_MBLK;				\
2088 	(data)->dd_mp = mp;						\
2089 	(data)->dd_len1 = len1;						\
2090 	(data)->dd_offset1 = off1;					\
2091 	(data)->dd_len2 = len2;						\
2092 	(data)->dd_offset2 = off2;					\
2093 }
2094 
2095 static ipsec_status_t
2096 esp_submit_req_inbound(mblk_t *ipsec_mp, ipsa_t *assoc, uint_t esph_offset)
2097 {
2098 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
2099 	boolean_t do_auth;
2100 	uint_t auth_offset, msg_len, auth_len;
2101 	crypto_call_req_t call_req;
2102 	mblk_t *esp_mp;
2103 	int kef_rc = CRYPTO_FAILED;
2104 	uint_t icv_len = assoc->ipsa_mac_len;
2105 	crypto_ctx_template_t auth_ctx_tmpl;
2106 	boolean_t do_encr;
2107 	uint_t encr_offset, encr_len;
2108 	uint_t iv_len = assoc->ipsa_iv_len;
2109 	crypto_ctx_template_t encr_ctx_tmpl;
2110 	netstack_t	*ns = ii->ipsec_in_ns;
2111 	ipsecesp_stack_t *espstack = ns->netstack_ipsecesp;
2112 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
2113 
2114 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
2115 
2116 	/*
2117 	 * In case kEF queues and calls back, keep netstackid_t for
2118 	 * verification that the IP instance is still around in
2119 	 * esp_kcf_callback().
2120 	 */
2121 	ii->ipsec_in_stackid = ns->netstack_stackid;
2122 
2123 	do_auth = assoc->ipsa_auth_alg != SADB_AALG_NONE;
2124 	do_encr = assoc->ipsa_encr_alg != SADB_EALG_NULL;
2125 
2126 	/*
2127 	 * An inbound packet is of the form:
2128 	 * IPSEC_IN -> [IP,options,ESP,IV,data,ICV,pad]
2129 	 */
2130 	esp_mp = ipsec_mp->b_cont;
2131 	msg_len = MBLKL(esp_mp);
2132 
2133 	ESP_INIT_CALLREQ(&call_req);
2134 
2135 	if (do_auth) {
2136 		/* force asynchronous processing? */
2137 		if (ipss->ipsec_algs_exec_mode[IPSEC_ALG_AUTH] ==
2138 		    IPSEC_ALGS_EXEC_ASYNC)
2139 			call_req.cr_flag |= CRYPTO_ALWAYS_QUEUE;
2140 
2141 		/* authentication context template */
2142 		IPSEC_CTX_TMPL(assoc, ipsa_authtmpl, IPSEC_ALG_AUTH,
2143 		    auth_ctx_tmpl);
2144 
2145 		/* ICV to be verified */
2146 		ESP_INIT_CRYPTO_MAC(&ii->ipsec_in_crypto_mac,
2147 		    icv_len, esp_mp->b_wptr - icv_len);
2148 
2149 		/* authentication starts at the ESP header */
2150 		auth_offset = esph_offset;
2151 		auth_len = msg_len - auth_offset - icv_len;
2152 		if (!do_encr) {
2153 			/* authentication only */
2154 			/* initialize input data argument */
2155 			ESP_INIT_CRYPTO_DATA(&ii->ipsec_in_crypto_data,
2156 			    esp_mp, auth_offset, auth_len);
2157 
2158 			/* call the crypto framework */
2159 			kef_rc = crypto_mac_verify(&assoc->ipsa_amech,
2160 			    &ii->ipsec_in_crypto_data,
2161 			    &assoc->ipsa_kcfauthkey, auth_ctx_tmpl,
2162 			    &ii->ipsec_in_crypto_mac, &call_req);
2163 		}
2164 	}
2165 
2166 	if (do_encr) {
2167 		/* force asynchronous processing? */
2168 		if (ipss->ipsec_algs_exec_mode[IPSEC_ALG_ENCR] ==
2169 		    IPSEC_ALGS_EXEC_ASYNC)
2170 			call_req.cr_flag |= CRYPTO_ALWAYS_QUEUE;
2171 
2172 		/* encryption template */
2173 		IPSEC_CTX_TMPL(assoc, ipsa_encrtmpl, IPSEC_ALG_ENCR,
2174 		    encr_ctx_tmpl);
2175 
2176 		/* skip IV, since it is passed separately */
2177 		encr_offset = esph_offset + sizeof (esph_t) + iv_len;
2178 		encr_len = msg_len - encr_offset;
2179 
2180 		if (!do_auth) {
2181 			/* decryption only */
2182 			/* initialize input data argument */
2183 			ESP_INIT_CRYPTO_DATA(&ii->ipsec_in_crypto_data,
2184 			    esp_mp, encr_offset, encr_len);
2185 
2186 			/* specify IV */
2187 			ii->ipsec_in_crypto_data.cd_miscdata =
2188 			    (char *)esp_mp->b_rptr + sizeof (esph_t) +
2189 			    esph_offset;
2190 
2191 			/* call the crypto framework */
2192 			kef_rc = crypto_decrypt(&assoc->ipsa_emech,
2193 			    &ii->ipsec_in_crypto_data,
2194 			    &assoc->ipsa_kcfencrkey, encr_ctx_tmpl,
2195 			    NULL, &call_req);
2196 		}
2197 	}
2198 
2199 	if (do_auth && do_encr) {
2200 		/* dual operation */
2201 		/* initialize input data argument */
2202 		ESP_INIT_CRYPTO_DUAL_DATA(&ii->ipsec_in_crypto_dual_data,
2203 		    esp_mp, auth_offset, auth_len,
2204 		    encr_offset, encr_len - icv_len);
2205 
2206 		/* specify IV */
2207 		ii->ipsec_in_crypto_dual_data.dd_miscdata =
2208 		    (char *)esp_mp->b_rptr + sizeof (esph_t) + esph_offset;
2209 
2210 		/* call the framework */
2211 		kef_rc = crypto_mac_verify_decrypt(&assoc->ipsa_amech,
2212 		    &assoc->ipsa_emech, &ii->ipsec_in_crypto_dual_data,
2213 		    &assoc->ipsa_kcfauthkey, &assoc->ipsa_kcfencrkey,
2214 		    auth_ctx_tmpl, encr_ctx_tmpl, &ii->ipsec_in_crypto_mac,
2215 		    NULL, &call_req);
2216 	}
2217 
2218 	switch (kef_rc) {
2219 	case CRYPTO_SUCCESS:
2220 		ESP_BUMP_STAT(espstack, crypto_sync);
2221 		return (esp_in_done(ipsec_mp));
2222 	case CRYPTO_QUEUED:
2223 		/* esp_kcf_callback() will be invoked on completion */
2224 		ESP_BUMP_STAT(espstack, crypto_async);
2225 		return (IPSEC_STATUS_PENDING);
2226 	case CRYPTO_INVALID_MAC:
2227 		ESP_BUMP_STAT(espstack, crypto_sync);
2228 		esp_log_bad_auth(ipsec_mp);
2229 		return (IPSEC_STATUS_FAILED);
2230 	}
2231 
2232 	esp_crypto_failed(ipsec_mp, B_TRUE, kef_rc, espstack);
2233 	return (IPSEC_STATUS_FAILED);
2234 }
2235 
2236 /*
2237  * Compute the IP and UDP checksums -- common code for both keepalives and
2238  * actual ESP-in-UDP packets.  Be flexible with multiple mblks because ESP
2239  * uses mblk-insertion to insert the UDP header.
2240  * TODO - If there is an easy way to prep a packet for HW checksums, make
2241  * it happen here.
2242  */
2243 static void
2244 esp_prepare_udp(netstack_t *ns, mblk_t *mp, ipha_t *ipha)
2245 {
2246 	int offset;
2247 	uint32_t cksum;
2248 	uint16_t *arr;
2249 	mblk_t *udpmp = mp;
2250 	uint_t hlen = IPH_HDR_LENGTH(ipha);
2251 
2252 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
2253 
2254 	ipha->ipha_hdr_checksum = 0;
2255 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
2256 
2257 	if (ns->netstack_udp->us_do_checksum) {
2258 		ASSERT(MBLKL(udpmp) >= sizeof (udpha_t));
2259 		/* arr points to the IP header. */
2260 		arr = (uint16_t *)ipha;
2261 		IP_STAT(ns->netstack_ip, ip_out_sw_cksum);
2262 		IP_STAT_UPDATE(ns->netstack_ip, ip_udp_out_sw_cksum_bytes,
2263 		    ntohs(htons(ipha->ipha_length) - hlen));
2264 		/* arr[6-9] are the IP addresses. */
2265 		cksum = IP_UDP_CSUM_COMP + arr[6] + arr[7] + arr[8] + arr[9] +
2266 		    ntohs(htons(ipha->ipha_length) - hlen);
2267 		cksum = IP_CSUM(mp, hlen, cksum);
2268 		offset = hlen + UDP_CHECKSUM_OFFSET;
2269 		while (offset >= MBLKL(udpmp)) {
2270 			offset -= MBLKL(udpmp);
2271 			udpmp = udpmp->b_cont;
2272 		}
2273 		/* arr points to the UDP header's checksum field. */
2274 		arr = (uint16_t *)(udpmp->b_rptr + offset);
2275 		*arr = cksum;
2276 	}
2277 }
2278 
2279 /*
2280  * Send a one-byte UDP NAT-T keepalive.  Construct an IPSEC_OUT too that'll
2281  * get fed into esp_send_udp/ip_wput_ipsec_out.
2282  */
2283 void
2284 ipsecesp_send_keepalive(ipsa_t *assoc)
2285 {
2286 	mblk_t *mp = NULL, *ipsec_mp = NULL;
2287 	ipha_t *ipha;
2288 	udpha_t *udpha;
2289 	ipsec_out_t *io;
2290 
2291 	ASSERT(!MUTEX_HELD(&assoc->ipsa_lock));
2292 
2293 	mp = allocb(sizeof (ipha_t) + sizeof (udpha_t) + 1, BPRI_HI);
2294 	if (mp == NULL)
2295 		return;
2296 	ipha = (ipha_t *)mp->b_rptr;
2297 	ipha->ipha_version_and_hdr_length = IP_SIMPLE_HDR_VERSION;
2298 	ipha->ipha_type_of_service = 0;
2299 	ipha->ipha_length = htons(sizeof (ipha_t) + sizeof (udpha_t) + 1);
2300 	/* Use the low-16 of the SPI so we have some clue where it came from. */
2301 	ipha->ipha_ident = *(((uint16_t *)(&assoc->ipsa_spi)) + 1);
2302 	ipha->ipha_fragment_offset_and_flags = 0;  /* Too small to fragment! */
2303 	ipha->ipha_ttl = 0xFF;
2304 	ipha->ipha_protocol = IPPROTO_UDP;
2305 	ipha->ipha_hdr_checksum = 0;
2306 	ipha->ipha_src = assoc->ipsa_srcaddr[0];
2307 	ipha->ipha_dst = assoc->ipsa_dstaddr[0];
2308 	udpha = (udpha_t *)(ipha + 1);
2309 	udpha->uha_src_port = (assoc->ipsa_local_nat_port != 0) ?
2310 	    assoc->ipsa_local_nat_port : htons(IPPORT_IKE_NATT);
2311 	udpha->uha_dst_port = (assoc->ipsa_remote_nat_port != 0) ?
2312 	    assoc->ipsa_remote_nat_port : htons(IPPORT_IKE_NATT);
2313 	udpha->uha_length = htons(sizeof (udpha_t) + 1);
2314 	udpha->uha_checksum = 0;
2315 	mp->b_wptr = (uint8_t *)(udpha + 1);
2316 	*(mp->b_wptr++) = 0xFF;
2317 
2318 	ipsec_mp = ipsec_alloc_ipsec_out(assoc->ipsa_netstack);
2319 	if (ipsec_mp == NULL) {
2320 		freeb(mp);
2321 		return;
2322 	}
2323 	ipsec_mp->b_cont = mp;
2324 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
2325 	io->ipsec_out_zoneid =
2326 	    netstackid_to_zoneid(assoc->ipsa_netstack->netstack_stackid);
2327 
2328 	esp_prepare_udp(assoc->ipsa_netstack, mp, ipha);
2329 	ip_wput_ipsec_out(NULL, ipsec_mp, ipha, NULL, NULL);
2330 }
2331 
2332 static ipsec_status_t
2333 esp_submit_req_outbound(mblk_t *ipsec_mp, ipsa_t *assoc, uchar_t *icv_buf,
2334     uint_t payload_len)
2335 {
2336 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
2337 	uint_t auth_len;
2338 	crypto_call_req_t call_req;
2339 	mblk_t *esp_mp;
2340 	int kef_rc = CRYPTO_FAILED;
2341 	uint_t icv_len = assoc->ipsa_mac_len;
2342 	crypto_ctx_template_t auth_ctx_tmpl;
2343 	boolean_t do_auth;
2344 	boolean_t do_encr;
2345 	uint_t iv_len = assoc->ipsa_iv_len;
2346 	crypto_ctx_template_t encr_ctx_tmpl;
2347 	boolean_t is_natt = ((assoc->ipsa_flags & IPSA_F_NATT) != 0);
2348 	size_t esph_offset = (is_natt ? UDPH_SIZE : 0);
2349 	netstack_t	*ns = io->ipsec_out_ns;
2350 	ipsecesp_stack_t *espstack = ns->netstack_ipsecesp;
2351 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
2352 
2353 	esp3dbg(espstack, ("esp_submit_req_outbound:%s",
2354 	    is_natt ? "natt" : "not natt"));
2355 
2356 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
2357 
2358 	/*
2359 	 * In case kEF queues and calls back, keep netstackid_t for
2360 	 * verification that the IP instance is still around in
2361 	 * esp_kcf_callback().
2362 	 */
2363 	io->ipsec_out_stackid = ns->netstack_stackid;
2364 
2365 	do_encr = assoc->ipsa_encr_alg != SADB_EALG_NULL;
2366 	do_auth = assoc->ipsa_auth_alg != SADB_AALG_NONE;
2367 
2368 	/*
2369 	 * Outbound IPsec packets are of the form:
2370 	 * IPSEC_OUT -> [IP,options] -> [ESP,IV] -> [data] -> [pad,ICV]
2371 	 * unless it's NATT, then it's
2372 	 * IPSEC_OUT -> [IP,options] -> [udp][ESP,IV] -> [data] -> [pad,ICV]
2373 	 * Get a pointer to the mblk containing the ESP header.
2374 	 */
2375 	ASSERT(ipsec_mp->b_cont != NULL && ipsec_mp->b_cont->b_cont != NULL);
2376 	esp_mp = ipsec_mp->b_cont->b_cont;
2377 
2378 	ESP_INIT_CALLREQ(&call_req);
2379 
2380 	if (do_auth) {
2381 		/* force asynchronous processing? */
2382 		if (ipss->ipsec_algs_exec_mode[IPSEC_ALG_AUTH] ==
2383 		    IPSEC_ALGS_EXEC_ASYNC)
2384 			call_req.cr_flag |= CRYPTO_ALWAYS_QUEUE;
2385 
2386 		/* authentication context template */
2387 		IPSEC_CTX_TMPL(assoc, ipsa_authtmpl, IPSEC_ALG_AUTH,
2388 		    auth_ctx_tmpl);
2389 
2390 		/* where to store the computed mac */
2391 		ESP_INIT_CRYPTO_MAC(&io->ipsec_out_crypto_mac,
2392 		    icv_len, icv_buf);
2393 
2394 		/* authentication starts at the ESP header */
2395 		auth_len = payload_len + iv_len + sizeof (esph_t);
2396 		if (!do_encr) {
2397 			/* authentication only */
2398 			/* initialize input data argument */
2399 			ESP_INIT_CRYPTO_DATA(&io->ipsec_out_crypto_data,
2400 			    esp_mp, esph_offset, auth_len);
2401 
2402 			/* call the crypto framework */
2403 			kef_rc = crypto_mac(&assoc->ipsa_amech,
2404 			    &io->ipsec_out_crypto_data,
2405 			    &assoc->ipsa_kcfauthkey, auth_ctx_tmpl,
2406 			    &io->ipsec_out_crypto_mac, &call_req);
2407 		}
2408 	}
2409 
2410 	if (do_encr) {
2411 		/* force asynchronous processing? */
2412 		if (ipss->ipsec_algs_exec_mode[IPSEC_ALG_ENCR] ==
2413 		    IPSEC_ALGS_EXEC_ASYNC)
2414 			call_req.cr_flag |= CRYPTO_ALWAYS_QUEUE;
2415 
2416 		/* encryption context template */
2417 		IPSEC_CTX_TMPL(assoc, ipsa_encrtmpl, IPSEC_ALG_ENCR,
2418 		    encr_ctx_tmpl);
2419 
2420 		if (!do_auth) {
2421 			/* encryption only, skip mblk that contains ESP hdr */
2422 			/* initialize input data argument */
2423 			ESP_INIT_CRYPTO_DATA(&io->ipsec_out_crypto_data,
2424 			    esp_mp->b_cont, 0, payload_len);
2425 
2426 			/* specify IV */
2427 			io->ipsec_out_crypto_data.cd_miscdata =
2428 			    (char *)esp_mp->b_rptr + sizeof (esph_t) +
2429 			    esph_offset;
2430 
2431 			/* call the crypto framework */
2432 			kef_rc = crypto_encrypt(&assoc->ipsa_emech,
2433 			    &io->ipsec_out_crypto_data,
2434 			    &assoc->ipsa_kcfencrkey, encr_ctx_tmpl,
2435 			    NULL, &call_req);
2436 		}
2437 	}
2438 
2439 	if (do_auth && do_encr) {
2440 		/*
2441 		 * Encryption and authentication:
2442 		 * Pass the pointer to the mblk chain starting at the ESP
2443 		 * header to the framework. Skip the ESP header mblk
2444 		 * for encryption, which is reflected by an encryption
2445 		 * offset equal to the length of that mblk. Start
2446 		 * the authentication at the ESP header, i.e. use an
2447 		 * authentication offset of zero.
2448 		 */
2449 		ESP_INIT_CRYPTO_DUAL_DATA(&io->ipsec_out_crypto_dual_data,
2450 		    esp_mp, MBLKL(esp_mp), payload_len, esph_offset, auth_len);
2451 
2452 		/* specify IV */
2453 		io->ipsec_out_crypto_dual_data.dd_miscdata =
2454 		    (char *)esp_mp->b_rptr + sizeof (esph_t) + esph_offset;
2455 
2456 		/* call the framework */
2457 		kef_rc = crypto_encrypt_mac(&assoc->ipsa_emech,
2458 		    &assoc->ipsa_amech, NULL,
2459 		    &assoc->ipsa_kcfencrkey, &assoc->ipsa_kcfauthkey,
2460 		    encr_ctx_tmpl, auth_ctx_tmpl,
2461 		    &io->ipsec_out_crypto_dual_data,
2462 		    &io->ipsec_out_crypto_mac, &call_req);
2463 	}
2464 
2465 	switch (kef_rc) {
2466 	case CRYPTO_SUCCESS:
2467 		ESP_BUMP_STAT(espstack, crypto_sync);
2468 		esp_set_usetime(assoc, B_FALSE);
2469 		if (is_natt)
2470 			esp_prepare_udp(ns, ipsec_mp->b_cont,
2471 			    (ipha_t *)ipsec_mp->b_cont->b_rptr);
2472 		return (IPSEC_STATUS_SUCCESS);
2473 	case CRYPTO_QUEUED:
2474 		/* esp_kcf_callback() will be invoked on completion */
2475 		ESP_BUMP_STAT(espstack, crypto_async);
2476 		return (IPSEC_STATUS_PENDING);
2477 	}
2478 
2479 	esp_crypto_failed(ipsec_mp, B_TRUE, kef_rc, espstack);
2480 	return (IPSEC_STATUS_FAILED);
2481 }
2482 
2483 /*
2484  * Handle outbound IPsec processing for IPv4 and IPv6
2485  * On success returns B_TRUE, on failure returns B_FALSE and frees the
2486  * mblk chain ipsec_in_mp.
2487  */
2488 static ipsec_status_t
2489 esp_outbound(mblk_t *mp)
2490 {
2491 	mblk_t *ipsec_out_mp, *data_mp, *espmp, *tailmp;
2492 	ipsec_out_t *io;
2493 	ipha_t *ipha;
2494 	ip6_t *ip6h;
2495 	esph_t *esph;
2496 	uint_t af;
2497 	uint8_t *nhp;
2498 	uintptr_t divpoint, datalen, adj, padlen, i, alloclen;
2499 	uintptr_t esplen = sizeof (esph_t);
2500 	uint8_t protocol;
2501 	ipsa_t *assoc;
2502 	uint_t iv_len, mac_len = 0;
2503 	uchar_t *icv_buf;
2504 	udpha_t *udpha;
2505 	boolean_t is_natt = B_FALSE;
2506 	netstack_t	*ns;
2507 	ipsecesp_stack_t *espstack;
2508 	ipsec_stack_t	*ipss;
2509 
2510 	ipsec_out_mp = mp;
2511 	data_mp = ipsec_out_mp->b_cont;
2512 
2513 	io = (ipsec_out_t *)ipsec_out_mp->b_rptr;
2514 	ns = io->ipsec_out_ns;
2515 	espstack = ns->netstack_ipsecesp;
2516 	ipss = ns->netstack_ipsec;
2517 
2518 	ESP_BUMP_STAT(espstack, out_requests);
2519 
2520 	/*
2521 	 * <sigh> We have to copy the message here, because TCP (for example)
2522 	 * keeps a dupb() of the message lying around for retransmission.
2523 	 * Since ESP changes the whole of the datagram, we have to create our
2524 	 * own copy lest we clobber TCP's data.  Since we have to copy anyway,
2525 	 * we might as well make use of msgpullup() and get the mblk into one
2526 	 * contiguous piece!
2527 	 */
2528 	ipsec_out_mp->b_cont = msgpullup(data_mp, -1);
2529 	if (ipsec_out_mp->b_cont == NULL) {
2530 		esp0dbg(("esp_outbound: msgpullup() failed, "
2531 		    "dropping packet.\n"));
2532 		ipsec_out_mp->b_cont = data_mp;
2533 		/*
2534 		 * TODO:  Find the outbound IRE for this packet and
2535 		 * pass it to ip_drop_packet().
2536 		 */
2537 		ip_drop_packet(ipsec_out_mp, B_FALSE, NULL, NULL,
2538 		    DROPPER(ipss, ipds_esp_nomem),
2539 		    &espstack->esp_dropper);
2540 		return (IPSEC_STATUS_FAILED);
2541 	} else {
2542 		freemsg(data_mp);
2543 		data_mp = ipsec_out_mp->b_cont;
2544 	}
2545 
2546 	/*
2547 	 * Reality check....
2548 	 */
2549 
2550 	ipha = (ipha_t *)data_mp->b_rptr;  /* So we can call esp_acquire(). */
2551 
2552 	if (io->ipsec_out_v4) {
2553 		af = AF_INET;
2554 		divpoint = IPH_HDR_LENGTH(ipha);
2555 		datalen = ntohs(ipha->ipha_length) - divpoint;
2556 		nhp = (uint8_t *)&ipha->ipha_protocol;
2557 	} else {
2558 		ip6_pkt_t ipp;
2559 
2560 		af = AF_INET6;
2561 		ip6h = (ip6_t *)ipha;
2562 		bzero(&ipp, sizeof (ipp));
2563 		divpoint = ip_find_hdr_v6(data_mp, ip6h, &ipp, NULL);
2564 		if (ipp.ipp_dstopts != NULL &&
2565 		    ipp.ipp_dstopts->ip6d_nxt != IPPROTO_ROUTING) {
2566 			/*
2567 			 * Destination options are tricky.  If we get in here,
2568 			 * then we have a terminal header following the
2569 			 * destination options.  We need to adjust backwards
2570 			 * so we insert ESP BEFORE the destination options
2571 			 * bag.  (So that the dstopts get encrypted!)
2572 			 *
2573 			 * Since this is for outbound packets only, we know
2574 			 * that non-terminal destination options only precede
2575 			 * routing headers.
2576 			 */
2577 			divpoint -= ipp.ipp_dstoptslen;
2578 		}
2579 		datalen = ntohs(ip6h->ip6_plen) + sizeof (ip6_t) - divpoint;
2580 
2581 		if (ipp.ipp_rthdr != NULL) {
2582 			nhp = &ipp.ipp_rthdr->ip6r_nxt;
2583 		} else if (ipp.ipp_hopopts != NULL) {
2584 			nhp = &ipp.ipp_hopopts->ip6h_nxt;
2585 		} else {
2586 			ASSERT(divpoint == sizeof (ip6_t));
2587 			/* It's probably IP + ESP. */
2588 			nhp = &ip6h->ip6_nxt;
2589 		}
2590 	}
2591 	assoc = io->ipsec_out_esp_sa;
2592 	ASSERT(assoc != NULL);
2593 
2594 	if (assoc->ipsa_auth_alg != SADB_AALG_NONE)
2595 		mac_len = assoc->ipsa_mac_len;
2596 
2597 	if (assoc->ipsa_flags & IPSA_F_NATT) {
2598 		/* wedge in fake UDP */
2599 		is_natt = B_TRUE;
2600 		esplen += UDPH_SIZE;
2601 	}
2602 
2603 	/*
2604 	 * Set up ESP header and encryption padding for ENCR PI request.
2605 	 */
2606 
2607 	/* Determine the padding length.  Pad to 4-bytes for no-encryption. */
2608 	if (assoc->ipsa_encr_alg != SADB_EALG_NULL) {
2609 		iv_len = assoc->ipsa_iv_len;
2610 
2611 		/*
2612 		 * Include the two additional bytes (hence the - 2) for the
2613 		 * padding length and the next header.  Take this into account
2614 		 * when calculating the actual length of the padding.
2615 		 */
2616 		ASSERT(ISP2(iv_len));
2617 		padlen = ((unsigned)(iv_len - datalen - 2)) & (iv_len - 1);
2618 	} else {
2619 		iv_len = 0;
2620 		padlen = ((unsigned)(sizeof (uint32_t) - datalen - 2)) &
2621 		    (sizeof (uint32_t) - 1);
2622 	}
2623 
2624 	/* Allocate ESP header and IV. */
2625 	esplen += iv_len;
2626 
2627 	/*
2628 	 * Update association byte-count lifetimes.  Don't forget to take
2629 	 * into account the padding length and next-header (hence the + 2).
2630 	 *
2631 	 * Use the amount of data fed into the "encryption algorithm".  This
2632 	 * is the IV, the data length, the padding length, and the final two
2633 	 * bytes (padlen, and next-header).
2634 	 *
2635 	 */
2636 
2637 	if (!esp_age_bytes(assoc, datalen + padlen + iv_len + 2, B_FALSE)) {
2638 		/*
2639 		 * TODO:  Find the outbound IRE for this packet and
2640 		 * pass it to ip_drop_packet().
2641 		 */
2642 		ip_drop_packet(mp, B_FALSE, NULL, NULL,
2643 		    DROPPER(ipss, ipds_esp_bytes_expire),
2644 		    &espstack->esp_dropper);
2645 		return (IPSEC_STATUS_FAILED);
2646 	}
2647 
2648 	espmp = allocb(esplen, BPRI_HI);
2649 	if (espmp == NULL) {
2650 		ESP_BUMP_STAT(espstack, out_discards);
2651 		esp1dbg(espstack, ("esp_outbound: can't allocate espmp.\n"));
2652 		/*
2653 		 * TODO:  Find the outbound IRE for this packet and
2654 		 * pass it to ip_drop_packet().
2655 		 */
2656 		ip_drop_packet(mp, B_FALSE, NULL, NULL,
2657 		    DROPPER(ipss, ipds_esp_nomem),
2658 		    &espstack->esp_dropper);
2659 		return (IPSEC_STATUS_FAILED);
2660 	}
2661 	espmp->b_wptr += esplen;
2662 	esph = (esph_t *)espmp->b_rptr;
2663 
2664 	if (is_natt) {
2665 		esp3dbg(espstack, ("esp_outbound: NATT"));
2666 
2667 		udpha = (udpha_t *)espmp->b_rptr;
2668 		udpha->uha_src_port = (assoc->ipsa_local_nat_port != 0) ?
2669 		    assoc->ipsa_local_nat_port : htons(IPPORT_IKE_NATT);
2670 		udpha->uha_dst_port = (assoc->ipsa_remote_nat_port != 0) ?
2671 		    assoc->ipsa_remote_nat_port : htons(IPPORT_IKE_NATT);
2672 		/*
2673 		 * Set the checksum to 0, so that the esp_prepare_udp() call
2674 		 * can do the right thing.
2675 		 */
2676 		udpha->uha_checksum = 0;
2677 		esph = (esph_t *)(udpha + 1);
2678 	}
2679 
2680 	esph->esph_spi = assoc->ipsa_spi;
2681 
2682 	esph->esph_replay = htonl(atomic_add_32_nv(&assoc->ipsa_replay, 1));
2683 	if (esph->esph_replay == 0 && assoc->ipsa_replay_wsize != 0) {
2684 		/*
2685 		 * XXX We have replay counter wrapping.
2686 		 * We probably want to nuke this SA (and its peer).
2687 		 */
2688 		ipsec_assocfailure(info.mi_idnum, 0, 0,
2689 		    SL_ERROR | SL_CONSOLE | SL_WARN,
2690 		    "Outbound ESP SA (0x%x, %s) has wrapped sequence.\n",
2691 		    esph->esph_spi, assoc->ipsa_dstaddr, af,
2692 		    espstack->ipsecesp_netstack);
2693 
2694 		ESP_BUMP_STAT(espstack, out_discards);
2695 		sadb_replay_delete(assoc);
2696 		/*
2697 		 * TODO:  Find the outbound IRE for this packet and
2698 		 * pass it to ip_drop_packet().
2699 		 */
2700 		ip_drop_packet(mp, B_FALSE, NULL, NULL,
2701 		    DROPPER(ipss, ipds_esp_replay),
2702 		    &espstack->esp_dropper);
2703 		return (IPSEC_STATUS_FAILED);
2704 	}
2705 
2706 	/*
2707 	 * Set the IV to a random quantity.  We do not require the
2708 	 * highest quality random bits, but for best security with CBC
2709 	 * mode ciphers, the value must be unlikely to repeat and also
2710 	 * must not be known in advance to an adversary capable of
2711 	 * influencing the plaintext.
2712 	 */
2713 	(void) random_get_pseudo_bytes((uint8_t *)(esph + 1), iv_len);
2714 
2715 	/* Fix the IP header. */
2716 	alloclen = padlen + 2 + mac_len;
2717 	adj = alloclen + (espmp->b_wptr - espmp->b_rptr);
2718 
2719 	protocol = *nhp;
2720 
2721 	if (io->ipsec_out_v4) {
2722 		ipha->ipha_length = htons(ntohs(ipha->ipha_length) + adj);
2723 		if (is_natt) {
2724 			*nhp = IPPROTO_UDP;
2725 			udpha->uha_length = htons(ntohs(ipha->ipha_length) -
2726 			    IPH_HDR_LENGTH(ipha));
2727 		} else {
2728 			*nhp = IPPROTO_ESP;
2729 		}
2730 		ipha->ipha_hdr_checksum = 0;
2731 		ipha->ipha_hdr_checksum = (uint16_t)ip_csum_hdr(ipha);
2732 	} else {
2733 		ip6h->ip6_plen = htons(ntohs(ip6h->ip6_plen) + adj);
2734 		*nhp = IPPROTO_ESP;
2735 	}
2736 
2737 	/* I've got the two ESP mblks, now insert them. */
2738 
2739 	esp2dbg(espstack, ("data_mp before outbound ESP adjustment:\n"));
2740 	esp2dbg(espstack, (dump_msg(data_mp)));
2741 
2742 	if (!esp_insert_esp(data_mp, espmp, divpoint, espstack)) {
2743 		ESP_BUMP_STAT(espstack, out_discards);
2744 		/* NOTE:  esp_insert_esp() only fails if there's no memory. */
2745 		/*
2746 		 * TODO:  Find the outbound IRE for this packet and
2747 		 * pass it to ip_drop_packet().
2748 		 */
2749 		ip_drop_packet(mp, B_FALSE, NULL, NULL,
2750 		    DROPPER(ipss, ipds_esp_nomem),
2751 		    &espstack->esp_dropper);
2752 		freeb(espmp);
2753 		return (IPSEC_STATUS_FAILED);
2754 	}
2755 
2756 	/* Append padding (and leave room for ICV). */
2757 	for (tailmp = data_mp; tailmp->b_cont != NULL; tailmp = tailmp->b_cont)
2758 		;
2759 	if (tailmp->b_wptr + alloclen > tailmp->b_datap->db_lim) {
2760 		tailmp->b_cont = allocb(alloclen, BPRI_HI);
2761 		if (tailmp->b_cont == NULL) {
2762 			ESP_BUMP_STAT(espstack, out_discards);
2763 			esp0dbg(("esp_outbound:  Can't allocate tailmp.\n"));
2764 			/*
2765 			 * TODO:  Find the outbound IRE for this packet and
2766 			 * pass it to ip_drop_packet().
2767 			 */
2768 			ip_drop_packet(mp, B_FALSE, NULL, NULL,
2769 			    DROPPER(ipss, ipds_esp_nomem),
2770 			    &espstack->esp_dropper);
2771 			return (IPSEC_STATUS_FAILED);
2772 		}
2773 		tailmp = tailmp->b_cont;
2774 	}
2775 
2776 	/*
2777 	 * If there's padding, N bytes of padding must be of the form 0x1,
2778 	 * 0x2, 0x3... 0xN.
2779 	 */
2780 	for (i = 0; i < padlen; ) {
2781 		i++;
2782 		*tailmp->b_wptr++ = i;
2783 	}
2784 	*tailmp->b_wptr++ = i;
2785 	*tailmp->b_wptr++ = protocol;
2786 
2787 	esp2dbg(espstack, ("data_Mp before encryption:\n"));
2788 	esp2dbg(espstack, (dump_msg(data_mp)));
2789 
2790 	/*
2791 	 * The packet is eligible for hardware acceleration if the
2792 	 * following conditions are satisfied:
2793 	 *
2794 	 * 1. the packet will not be fragmented
2795 	 * 2. the provider supports the algorithms specified by SA
2796 	 * 3. there is no pending control message being exchanged
2797 	 * 4. snoop is not attached
2798 	 * 5. the destination address is not a multicast address
2799 	 *
2800 	 * All five of these conditions are checked by IP prior to
2801 	 * sending the packet to ESP.
2802 	 *
2803 	 * But We, and We Alone, can, nay MUST check if the packet
2804 	 * is over NATT, and then disqualify it from hardware
2805 	 * acceleration.
2806 	 */
2807 
2808 	if (io->ipsec_out_is_capab_ill && !(assoc->ipsa_flags & IPSA_F_NATT)) {
2809 		return (esp_outbound_accelerated(ipsec_out_mp, mac_len));
2810 	}
2811 	ESP_BUMP_STAT(espstack, noaccel);
2812 
2813 	/*
2814 	 * Okay.  I've set up the pre-encryption ESP.  Let's do it!
2815 	 */
2816 
2817 	if (mac_len > 0) {
2818 		ASSERT(tailmp->b_wptr + mac_len <= tailmp->b_datap->db_lim);
2819 		icv_buf = tailmp->b_wptr;
2820 		tailmp->b_wptr += mac_len;
2821 	} else {
2822 		icv_buf = NULL;
2823 	}
2824 
2825 	return (esp_submit_req_outbound(ipsec_out_mp, assoc, icv_buf,
2826 	    datalen + padlen + 2));
2827 }
2828 
2829 /*
2830  * IP calls this to validate the ICMP errors that
2831  * we got from the network.
2832  */
2833 ipsec_status_t
2834 ipsecesp_icmp_error(mblk_t *ipsec_mp)
2835 {
2836 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
2837 	boolean_t is_inbound = (ii->ipsec_in_type == IPSEC_IN);
2838 	netstack_t	*ns;
2839 	ipsecesp_stack_t *espstack;
2840 	ipsec_stack_t	*ipss;
2841 
2842 	if (is_inbound) {
2843 		ns = ii->ipsec_in_ns;
2844 	} else {
2845 		ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
2846 
2847 		ns = io->ipsec_out_ns;
2848 	}
2849 	espstack = ns->netstack_ipsecesp;
2850 	ipss = ns->netstack_ipsec;
2851 
2852 	/*
2853 	 * Unless we get an entire packet back, this function is useless.
2854 	 * Why?
2855 	 *
2856 	 * 1.)	Partial packets are useless, because the "next header"
2857 	 *	is at the end of the decrypted ESP packet.  Without the
2858 	 *	whole packet, this is useless.
2859 	 *
2860 	 * 2.)	If we every use a stateful cipher, such as a stream or a
2861 	 *	one-time pad, we can't do anything.
2862 	 *
2863 	 * Since the chances of us getting an entire packet back are very
2864 	 * very small, we discard here.
2865 	 */
2866 	IP_ESP_BUMP_STAT(ipss, in_discards);
2867 	ip_drop_packet(ipsec_mp, B_TRUE, NULL, NULL,
2868 	    DROPPER(ipss, ipds_esp_icmp),
2869 	    &espstack->esp_dropper);
2870 	return (IPSEC_STATUS_FAILED);
2871 }
2872 
2873 /*
2874  * ESP module read put routine.
2875  */
2876 /* ARGSUSED */
2877 static void
2878 ipsecesp_rput(queue_t *q, mblk_t *mp)
2879 {
2880 	ipsecesp_stack_t	*espstack = (ipsecesp_stack_t *)q->q_ptr;
2881 
2882 	ASSERT(mp->b_datap->db_type != M_CTL);	/* No more IRE_DB_REQ. */
2883 
2884 	switch (mp->b_datap->db_type) {
2885 	case M_PROTO:
2886 	case M_PCPROTO:
2887 		/* TPI message of some sort. */
2888 		switch (*((t_scalar_t *)mp->b_rptr)) {
2889 		case T_BIND_ACK:
2890 			esp3dbg(espstack,
2891 			    ("Thank you IP from ESP for T_BIND_ACK\n"));
2892 			break;
2893 		case T_ERROR_ACK:
2894 			cmn_err(CE_WARN,
2895 			    "ipsecesp:  ESP received T_ERROR_ACK from IP.");
2896 			/*
2897 			 * Make esp_sadb.s_ip_q NULL, and in the
2898 			 * future, perhaps try again.
2899 			 */
2900 			espstack->esp_sadb.s_ip_q = NULL;
2901 			break;
2902 		case T_OK_ACK:
2903 			/* Probably from a (rarely sent) T_UNBIND_REQ. */
2904 			break;
2905 		default:
2906 			esp0dbg(("Unknown M_{,PC}PROTO message.\n"));
2907 		}
2908 		freemsg(mp);
2909 		break;
2910 	default:
2911 		/* For now, passthru message. */
2912 		esp2dbg(espstack, ("ESP got unknown mblk type %d.\n",
2913 		    mp->b_datap->db_type));
2914 		putnext(q, mp);
2915 	}
2916 }
2917 
2918 /*
2919  * Construct an SADB_REGISTER message with the current algorithms.
2920  */
2921 static boolean_t
2922 esp_register_out(uint32_t sequence, uint32_t pid, uint_t serial,
2923     ipsecesp_stack_t *espstack)
2924 {
2925 	mblk_t *pfkey_msg_mp, *keysock_out_mp;
2926 	sadb_msg_t *samsg;
2927 	sadb_supported_t *sasupp_auth = NULL;
2928 	sadb_supported_t *sasupp_encr = NULL;
2929 	sadb_alg_t *saalg;
2930 	uint_t allocsize = sizeof (*samsg);
2931 	uint_t i, numalgs_snap;
2932 	int current_aalgs;
2933 	ipsec_alginfo_t **authalgs;
2934 	uint_t num_aalgs;
2935 	int current_ealgs;
2936 	ipsec_alginfo_t **encralgs;
2937 	uint_t num_ealgs;
2938 	ipsec_stack_t	*ipss = espstack->ipsecesp_netstack->netstack_ipsec;
2939 
2940 	/* Allocate the KEYSOCK_OUT. */
2941 	keysock_out_mp = sadb_keysock_out(serial);
2942 	if (keysock_out_mp == NULL) {
2943 		esp0dbg(("esp_register_out: couldn't allocate mblk.\n"));
2944 		return (B_FALSE);
2945 	}
2946 
2947 	/*
2948 	 * Allocate the PF_KEY message that follows KEYSOCK_OUT.
2949 	 */
2950 
2951 	mutex_enter(&ipss->ipsec_alg_lock);
2952 
2953 	/*
2954 	 * Fill SADB_REGISTER message's algorithm descriptors.  Hold
2955 	 * down the lock while filling it.
2956 	 *
2957 	 * Return only valid algorithms, so the number of algorithms
2958 	 * to send up may be less than the number of algorithm entries
2959 	 * in the table.
2960 	 */
2961 	authalgs = ipss->ipsec_alglists[IPSEC_ALG_AUTH];
2962 	for (num_aalgs = 0, i = 0; i < IPSEC_MAX_ALGS; i++)
2963 		if (authalgs[i] != NULL && ALG_VALID(authalgs[i]))
2964 			num_aalgs++;
2965 
2966 	if (num_aalgs != 0) {
2967 		allocsize += (num_aalgs * sizeof (*saalg));
2968 		allocsize += sizeof (*sasupp_auth);
2969 	}
2970 	encralgs = ipss->ipsec_alglists[IPSEC_ALG_ENCR];
2971 	for (num_ealgs = 0, i = 0; i < IPSEC_MAX_ALGS; i++)
2972 		if (encralgs[i] != NULL && ALG_VALID(encralgs[i]))
2973 			num_ealgs++;
2974 
2975 	if (num_ealgs != 0) {
2976 		allocsize += (num_ealgs * sizeof (*saalg));
2977 		allocsize += sizeof (*sasupp_encr);
2978 	}
2979 	keysock_out_mp->b_cont = allocb(allocsize, BPRI_HI);
2980 	if (keysock_out_mp->b_cont == NULL) {
2981 		mutex_exit(&ipss->ipsec_alg_lock);
2982 		freemsg(keysock_out_mp);
2983 		return (B_FALSE);
2984 	}
2985 
2986 	pfkey_msg_mp = keysock_out_mp->b_cont;
2987 	pfkey_msg_mp->b_wptr += allocsize;
2988 	if (num_aalgs != 0) {
2989 		sasupp_auth = (sadb_supported_t *)
2990 		    (pfkey_msg_mp->b_rptr + sizeof (*samsg));
2991 		saalg = (sadb_alg_t *)(sasupp_auth + 1);
2992 
2993 		ASSERT(((ulong_t)saalg & 0x7) == 0);
2994 
2995 		numalgs_snap = 0;
2996 		for (i = 0;
2997 		    ((i < IPSEC_MAX_ALGS) && (numalgs_snap < num_aalgs));
2998 		    i++) {
2999 			if (authalgs[i] == NULL || !ALG_VALID(authalgs[i]))
3000 				continue;
3001 
3002 			saalg->sadb_alg_id = authalgs[i]->alg_id;
3003 			saalg->sadb_alg_ivlen = 0;
3004 			saalg->sadb_alg_minbits	= authalgs[i]->alg_ef_minbits;
3005 			saalg->sadb_alg_maxbits	= authalgs[i]->alg_ef_maxbits;
3006 			saalg->sadb_x_alg_defincr = authalgs[i]->alg_ef_default;
3007 			saalg->sadb_x_alg_increment =
3008 			    authalgs[i]->alg_increment;
3009 			numalgs_snap++;
3010 			saalg++;
3011 		}
3012 		ASSERT(numalgs_snap == num_aalgs);
3013 #ifdef DEBUG
3014 		/*
3015 		 * Reality check to make sure I snagged all of the
3016 		 * algorithms.
3017 		 */
3018 		for (; i < IPSEC_MAX_ALGS; i++) {
3019 			if (authalgs[i] != NULL && ALG_VALID(authalgs[i])) {
3020 				cmn_err(CE_PANIC, "esp_register_out()! "
3021 				    "Missed aalg #%d.\n", i);
3022 			}
3023 		}
3024 #endif /* DEBUG */
3025 	} else {
3026 		saalg = (sadb_alg_t *)(pfkey_msg_mp->b_rptr + sizeof (*samsg));
3027 	}
3028 
3029 	if (num_ealgs != 0) {
3030 		sasupp_encr = (sadb_supported_t *)saalg;
3031 		saalg = (sadb_alg_t *)(sasupp_encr + 1);
3032 
3033 		numalgs_snap = 0;
3034 		for (i = 0;
3035 		    ((i < IPSEC_MAX_ALGS) && (numalgs_snap < num_ealgs)); i++) {
3036 			if (encralgs[i] == NULL || !ALG_VALID(encralgs[i]))
3037 				continue;
3038 			saalg->sadb_alg_id = encralgs[i]->alg_id;
3039 			saalg->sadb_alg_ivlen = encralgs[i]->alg_datalen;
3040 			saalg->sadb_alg_minbits	= encralgs[i]->alg_ef_minbits;
3041 			saalg->sadb_alg_maxbits	= encralgs[i]->alg_ef_maxbits;
3042 			saalg->sadb_x_alg_defincr = encralgs[i]->alg_ef_default;
3043 			saalg->sadb_x_alg_increment =
3044 			    encralgs[i]->alg_increment;
3045 			numalgs_snap++;
3046 			saalg++;
3047 		}
3048 		ASSERT(numalgs_snap == num_ealgs);
3049 #ifdef DEBUG
3050 		/*
3051 		 * Reality check to make sure I snagged all of the
3052 		 * algorithms.
3053 		 */
3054 		for (; i < IPSEC_MAX_ALGS; i++) {
3055 			if (encralgs[i] != NULL && ALG_VALID(encralgs[i])) {
3056 				cmn_err(CE_PANIC, "esp_register_out()! "
3057 				    "Missed ealg #%d.\n", i);
3058 			}
3059 		}
3060 #endif /* DEBUG */
3061 	}
3062 
3063 	current_aalgs = num_aalgs;
3064 	current_ealgs = num_ealgs;
3065 
3066 	mutex_exit(&ipss->ipsec_alg_lock);
3067 
3068 	/* Now fill the rest of the SADB_REGISTER message. */
3069 
3070 	samsg = (sadb_msg_t *)pfkey_msg_mp->b_rptr;
3071 	samsg->sadb_msg_version = PF_KEY_V2;
3072 	samsg->sadb_msg_type = SADB_REGISTER;
3073 	samsg->sadb_msg_errno = 0;
3074 	samsg->sadb_msg_satype = SADB_SATYPE_ESP;
3075 	samsg->sadb_msg_len = SADB_8TO64(allocsize);
3076 	samsg->sadb_msg_reserved = 0;
3077 	/*
3078 	 * Assume caller has sufficient sequence/pid number info.  If it's one
3079 	 * from me over a new alg., I could give two hoots about sequence.
3080 	 */
3081 	samsg->sadb_msg_seq = sequence;
3082 	samsg->sadb_msg_pid = pid;
3083 
3084 	if (sasupp_auth != NULL) {
3085 		sasupp_auth->sadb_supported_len = SADB_8TO64(
3086 		    sizeof (*sasupp_auth) + sizeof (*saalg) * current_aalgs);
3087 		sasupp_auth->sadb_supported_exttype = SADB_EXT_SUPPORTED_AUTH;
3088 		sasupp_auth->sadb_supported_reserved = 0;
3089 	}
3090 
3091 	if (sasupp_encr != NULL) {
3092 		sasupp_encr->sadb_supported_len = SADB_8TO64(
3093 		    sizeof (*sasupp_encr) + sizeof (*saalg) * current_ealgs);
3094 		sasupp_encr->sadb_supported_exttype =
3095 		    SADB_EXT_SUPPORTED_ENCRYPT;
3096 		sasupp_encr->sadb_supported_reserved = 0;
3097 	}
3098 
3099 	if (espstack->esp_pfkey_q != NULL)
3100 		putnext(espstack->esp_pfkey_q, keysock_out_mp);
3101 	else {
3102 		freemsg(keysock_out_mp);
3103 		return (B_FALSE);
3104 	}
3105 
3106 	return (B_TRUE);
3107 }
3108 
3109 /*
3110  * Invoked when the algorithm table changes. Causes SADB_REGISTER
3111  * messages continaining the current list of algorithms to be
3112  * sent up to the ESP listeners.
3113  */
3114 void
3115 ipsecesp_algs_changed(netstack_t *ns)
3116 {
3117 	ipsecesp_stack_t	*espstack = ns->netstack_ipsecesp;
3118 
3119 	/*
3120 	 * Time to send a PF_KEY SADB_REGISTER message to ESP listeners
3121 	 * everywhere.  (The function itself checks for NULL esp_pfkey_q.)
3122 	 */
3123 	(void) esp_register_out(0, 0, 0, espstack);
3124 }
3125 
3126 /*
3127  * taskq_dispatch handler.
3128  */
3129 static void
3130 inbound_task(void *arg)
3131 {
3132 	esph_t *esph;
3133 	mblk_t *mp = (mblk_t *)arg;
3134 	ipsec_in_t *ii = (ipsec_in_t *)mp->b_rptr;
3135 	netstack_t		*ns = ii->ipsec_in_ns;
3136 	ipsecesp_stack_t	*espstack = ns->netstack_ipsecesp;
3137 	int ipsec_rc;
3138 
3139 	esp2dbg(espstack, ("in ESP inbound_task"));
3140 	ASSERT(espstack != NULL);
3141 
3142 	esph = ipsec_inbound_esp_sa(mp, ns);
3143 	if (esph == NULL)
3144 		return;
3145 	ASSERT(ii->ipsec_in_esp_sa != NULL);
3146 	ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(mp, esph);
3147 	if (ipsec_rc != IPSEC_STATUS_SUCCESS)
3148 		return;
3149 	ip_fanout_proto_again(mp, NULL, NULL, NULL);
3150 }
3151 
3152 /*
3153  * Now that weak-key passed, actually ADD the security association, and
3154  * send back a reply ADD message.
3155  */
3156 static int
3157 esp_add_sa_finish(mblk_t *mp, sadb_msg_t *samsg, keysock_in_t *ksi,
3158     int *diagnostic, ipsecesp_stack_t *espstack)
3159 {
3160 	isaf_t *primary = NULL, *secondary, *inbound, *outbound;
3161 	sadb_sa_t *assoc = (sadb_sa_t *)ksi->ks_in_extv[SADB_EXT_SA];
3162 	sadb_address_t *dstext =
3163 	    (sadb_address_t *)ksi->ks_in_extv[SADB_EXT_ADDRESS_DST];
3164 	struct sockaddr_in *dst;
3165 	struct sockaddr_in6 *dst6;
3166 	boolean_t is_ipv4, clone = B_FALSE, is_inbound = B_FALSE;
3167 	uint32_t *dstaddr;
3168 	ipsa_t *larval = NULL;
3169 	ipsacq_t *acqrec;
3170 	iacqf_t *acq_bucket;
3171 	mblk_t *acq_msgs = NULL;
3172 	int rc;
3173 	sadb_t *sp;
3174 	int outhash;
3175 	mblk_t *lpkt;
3176 	ipsec_stack_t	*ipss = espstack->ipsecesp_netstack->netstack_ipsec;
3177 
3178 	/*
3179 	 * Locate the appropriate table(s).
3180 	 */
3181 
3182 	dst = (struct sockaddr_in *)(dstext + 1);
3183 	dst6 = (struct sockaddr_in6 *)dst;
3184 	is_ipv4 = (dst->sin_family == AF_INET);
3185 	if (is_ipv4) {
3186 		sp = &espstack->esp_sadb.s_v4;
3187 		dstaddr = (uint32_t *)(&dst->sin_addr);
3188 		outhash = OUTBOUND_HASH_V4(sp, *(ipaddr_t *)dstaddr);
3189 	} else {
3190 		sp = &espstack->esp_sadb.s_v6;
3191 		dstaddr = (uint32_t *)(&dst6->sin6_addr);
3192 		outhash = OUTBOUND_HASH_V6(sp, *(in6_addr_t *)dstaddr);
3193 	}
3194 
3195 	inbound = INBOUND_BUCKET(sp, assoc->sadb_sa_spi);
3196 	outbound = &sp->sdb_of[outhash];
3197 
3198 	/*
3199 	 * Use the direction flags provided by the KMD to determine
3200 	 * if the inbound or outbound table should be the primary
3201 	 * for this SA. If these flags were absent then make this
3202 	 * decision based on the addresses.
3203 	 */
3204 	if (assoc->sadb_sa_flags & IPSA_F_INBOUND) {
3205 		primary = inbound;
3206 		secondary = outbound;
3207 		is_inbound = B_TRUE;
3208 		if (assoc->sadb_sa_flags & IPSA_F_OUTBOUND)
3209 			clone = B_TRUE;
3210 	} else {
3211 		if (assoc->sadb_sa_flags & IPSA_F_OUTBOUND) {
3212 			primary = outbound;
3213 			secondary = inbound;
3214 		}
3215 	}
3216 
3217 	if (primary == NULL) {
3218 		/*
3219 		 * The KMD did not set a direction flag, determine which
3220 		 * table to insert the SA into based on addresses.
3221 		 */
3222 		switch (ksi->ks_in_dsttype) {
3223 		case KS_IN_ADDR_MBCAST:
3224 			clone = B_TRUE;	/* All mcast SAs can be bidirectional */
3225 			assoc->sadb_sa_flags |= IPSA_F_OUTBOUND;
3226 			/* FALLTHRU */
3227 		/*
3228 		 * If the source address is either one of mine, or unspecified
3229 		 * (which is best summed up by saying "not 'not mine'"),
3230 		 * then the association is potentially bi-directional,
3231 		 * in that it can be used for inbound traffic and outbound
3232 		 * traffic.  The best example of such an SA is a multicast
3233 		 * SA (which allows me to receive the outbound traffic).
3234 		 */
3235 		case KS_IN_ADDR_ME:
3236 			assoc->sadb_sa_flags |= IPSA_F_INBOUND;
3237 			primary = inbound;
3238 			secondary = outbound;
3239 			if (ksi->ks_in_srctype != KS_IN_ADDR_NOTME)
3240 				clone = B_TRUE;
3241 			is_inbound = B_TRUE;
3242 			break;
3243 		/*
3244 		 * If the source address literally not mine (either
3245 		 * unspecified or not mine), then this SA may have an
3246 		 * address that WILL be mine after some configuration.
3247 		 * We pay the price for this by making it a bi-directional
3248 		 * SA.
3249 		 */
3250 		case KS_IN_ADDR_NOTME:
3251 			assoc->sadb_sa_flags |= IPSA_F_OUTBOUND;
3252 			primary = outbound;
3253 			secondary = inbound;
3254 			if (ksi->ks_in_srctype != KS_IN_ADDR_ME) {
3255 				assoc->sadb_sa_flags |= IPSA_F_INBOUND;
3256 				clone = B_TRUE;
3257 			}
3258 			break;
3259 		default:
3260 			*diagnostic = SADB_X_DIAGNOSTIC_BAD_DST;
3261 			return (EINVAL);
3262 		}
3263 	}
3264 
3265 	/*
3266 	 * Find a ACQUIRE list entry if possible.  If we've added an SA that
3267 	 * suits the needs of an ACQUIRE list entry, we can eliminate the
3268 	 * ACQUIRE list entry and transmit the enqueued packets.  Use the
3269 	 * high-bit of the sequence number to queue it.  Key off destination
3270 	 * addr, and change acqrec's state.
3271 	 */
3272 
3273 	if (samsg->sadb_msg_seq & IACQF_LOWEST_SEQ) {
3274 		acq_bucket = &sp->sdb_acq[outhash];
3275 		mutex_enter(&acq_bucket->iacqf_lock);
3276 		for (acqrec = acq_bucket->iacqf_ipsacq; acqrec != NULL;
3277 		    acqrec = acqrec->ipsacq_next) {
3278 			mutex_enter(&acqrec->ipsacq_lock);
3279 			/*
3280 			 * Q:  I only check sequence.  Should I check dst?
3281 			 * A: Yes, check dest because those are the packets
3282 			 *    that are queued up.
3283 			 */
3284 			if (acqrec->ipsacq_seq == samsg->sadb_msg_seq &&
3285 			    IPSA_ARE_ADDR_EQUAL(dstaddr,
3286 			    acqrec->ipsacq_dstaddr, acqrec->ipsacq_addrfam))
3287 				break;
3288 			mutex_exit(&acqrec->ipsacq_lock);
3289 		}
3290 		if (acqrec != NULL) {
3291 			/*
3292 			 * AHA!  I found an ACQUIRE record for this SA.
3293 			 * Grab the msg list, and free the acquire record.
3294 			 * I already am holding the lock for this record,
3295 			 * so all I have to do is free it.
3296 			 */
3297 			acq_msgs = acqrec->ipsacq_mp;
3298 			acqrec->ipsacq_mp = NULL;
3299 			mutex_exit(&acqrec->ipsacq_lock);
3300 			sadb_destroy_acquire(acqrec,
3301 			    espstack->ipsecesp_netstack);
3302 		}
3303 		mutex_exit(&acq_bucket->iacqf_lock);
3304 	}
3305 
3306 	/*
3307 	 * Find PF_KEY message, and see if I'm an update.  If so, find entry
3308 	 * in larval list (if there).
3309 	 */
3310 
3311 	if (samsg->sadb_msg_type == SADB_UPDATE) {
3312 		mutex_enter(&inbound->isaf_lock);
3313 		larval = ipsec_getassocbyspi(inbound, assoc->sadb_sa_spi,
3314 		    ALL_ZEROES_PTR, dstaddr, dst->sin_family);
3315 		mutex_exit(&inbound->isaf_lock);
3316 
3317 		if (larval == NULL) {
3318 			*diagnostic = SADB_X_DIAGNOSTIC_SA_NOTFOUND;
3319 			esp0dbg(("Larval update, but larval disappeared.\n"));
3320 			return (ESRCH);
3321 		} /* Else sadb_common_add unlinks it for me! */
3322 	}
3323 
3324 	lpkt = NULL;
3325 	if (larval != NULL)
3326 		lpkt = sadb_clear_lpkt(larval);
3327 
3328 	rc = sadb_common_add(espstack->esp_sadb.s_ip_q, espstack->esp_pfkey_q,
3329 	    mp, samsg, ksi, primary, secondary, larval, clone, is_inbound,
3330 	    diagnostic, espstack->ipsecesp_netstack, &espstack->esp_sadb);
3331 
3332 	if (rc == 0 && lpkt != NULL) {
3333 		rc = !taskq_dispatch(esp_taskq, inbound_task,
3334 		    (void *) lpkt, TQ_NOSLEEP);
3335 	}
3336 
3337 	if (rc != 0) {
3338 		ip_drop_packet(lpkt, B_TRUE, NULL, NULL,
3339 		    DROPPER(ipss, ipds_sadb_inlarval_timeout),
3340 		    &espstack->esp_dropper);
3341 	}
3342 
3343 	/*
3344 	 * How much more stack will I create with all of these
3345 	 * esp_outbound() calls?
3346 	 */
3347 
3348 	while (acq_msgs != NULL) {
3349 		mblk_t *mp = acq_msgs;
3350 
3351 		acq_msgs = acq_msgs->b_next;
3352 		mp->b_next = NULL;
3353 		if (rc == 0) {
3354 			if (ipsec_outbound_sa(mp, IPPROTO_ESP)) {
3355 				((ipsec_out_t *)(mp->b_rptr))->
3356 				    ipsec_out_esp_done = B_TRUE;
3357 				if (esp_outbound(mp) == IPSEC_STATUS_SUCCESS) {
3358 					ipha_t *ipha;
3359 
3360 					/* do AH processing if needed */
3361 					if (!esp_do_outbound_ah(mp))
3362 						continue;
3363 
3364 					ipha = (ipha_t *)mp->b_cont->b_rptr;
3365 
3366 					/* finish IPsec processing */
3367 					if (is_ipv4) {
3368 						ip_wput_ipsec_out(NULL, mp,
3369 						    ipha, NULL, NULL);
3370 					} else {
3371 						ip6_t *ip6h = (ip6_t *)ipha;
3372 						ip_wput_ipsec_out_v6(NULL,
3373 						    mp, ip6h, NULL, NULL);
3374 					}
3375 				}
3376 				continue;
3377 			}
3378 		}
3379 		ESP_BUMP_STAT(espstack, out_discards);
3380 		ip_drop_packet(mp, B_FALSE, NULL, NULL,
3381 		    DROPPER(ipss, ipds_sadb_acquire_timeout),
3382 		    &espstack->esp_dropper);
3383 	}
3384 
3385 	return (rc);
3386 }
3387 
3388 /*
3389  * Add new ESP security association.  This may become a generic AH/ESP
3390  * routine eventually.
3391  */
3392 static int
3393 esp_add_sa(mblk_t *mp, keysock_in_t *ksi, int *diagnostic, netstack_t *ns)
3394 {
3395 	sadb_sa_t *assoc = (sadb_sa_t *)ksi->ks_in_extv[SADB_EXT_SA];
3396 	sadb_address_t *srcext =
3397 	    (sadb_address_t *)ksi->ks_in_extv[SADB_EXT_ADDRESS_SRC];
3398 	sadb_address_t *dstext =
3399 	    (sadb_address_t *)ksi->ks_in_extv[SADB_EXT_ADDRESS_DST];
3400 	sadb_address_t *isrcext =
3401 	    (sadb_address_t *)ksi->ks_in_extv[SADB_X_EXT_ADDRESS_INNER_SRC];
3402 	sadb_address_t *idstext =
3403 	    (sadb_address_t *)ksi->ks_in_extv[SADB_X_EXT_ADDRESS_INNER_DST];
3404 	sadb_address_t *nttext_loc =
3405 	    (sadb_address_t *)ksi->ks_in_extv[SADB_X_EXT_ADDRESS_NATT_LOC];
3406 	sadb_address_t *nttext_rem =
3407 	    (sadb_address_t *)ksi->ks_in_extv[SADB_X_EXT_ADDRESS_NATT_REM];
3408 	sadb_key_t *akey = (sadb_key_t *)ksi->ks_in_extv[SADB_EXT_KEY_AUTH];
3409 	sadb_key_t *ekey = (sadb_key_t *)ksi->ks_in_extv[SADB_EXT_KEY_ENCRYPT];
3410 	struct sockaddr_in *src, *dst;
3411 	struct sockaddr_in *natt_loc, *natt_rem;
3412 	struct sockaddr_in6 *natt_loc6, *natt_rem6;
3413 	sadb_lifetime_t *soft =
3414 	    (sadb_lifetime_t *)ksi->ks_in_extv[SADB_EXT_LIFETIME_SOFT];
3415 	sadb_lifetime_t *hard =
3416 	    (sadb_lifetime_t *)ksi->ks_in_extv[SADB_EXT_LIFETIME_HARD];
3417 	ipsecesp_stack_t *espstack = ns->netstack_ipsecesp;
3418 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
3419 
3420 	/* I need certain extensions present for an ADD message. */
3421 	if (srcext == NULL) {
3422 		*diagnostic = SADB_X_DIAGNOSTIC_MISSING_SRC;
3423 		return (EINVAL);
3424 	}
3425 	if (dstext == NULL) {
3426 		*diagnostic = SADB_X_DIAGNOSTIC_MISSING_DST;
3427 		return (EINVAL);
3428 	}
3429 	if (isrcext == NULL && idstext != NULL) {
3430 		*diagnostic = SADB_X_DIAGNOSTIC_MISSING_INNER_SRC;
3431 		return (EINVAL);
3432 	}
3433 	if (isrcext != NULL && idstext == NULL) {
3434 		*diagnostic = SADB_X_DIAGNOSTIC_MISSING_INNER_DST;
3435 		return (EINVAL);
3436 	}
3437 	if (assoc == NULL) {
3438 		*diagnostic = SADB_X_DIAGNOSTIC_MISSING_SA;
3439 		return (EINVAL);
3440 	}
3441 	if (ekey == NULL && assoc->sadb_sa_encrypt != SADB_EALG_NULL) {
3442 		*diagnostic = SADB_X_DIAGNOSTIC_MISSING_EKEY;
3443 		return (EINVAL);
3444 	}
3445 
3446 	src = (struct sockaddr_in *)(srcext + 1);
3447 	dst = (struct sockaddr_in *)(dstext + 1);
3448 	natt_loc = (struct sockaddr_in *)(nttext_loc + 1);
3449 	natt_loc6 = (struct sockaddr_in6 *)(nttext_loc + 1);
3450 	natt_rem = (struct sockaddr_in *)(nttext_rem + 1);
3451 	natt_rem6 = (struct sockaddr_in6 *)(nttext_rem + 1);
3452 
3453 	/* Sundry ADD-specific reality checks. */
3454 	/* XXX STATS :  Logging/stats here? */
3455 	if (assoc->sadb_sa_state != SADB_SASTATE_MATURE) {
3456 		*diagnostic = SADB_X_DIAGNOSTIC_BAD_SASTATE;
3457 		return (EINVAL);
3458 	}
3459 	if (assoc->sadb_sa_encrypt == SADB_EALG_NONE) {
3460 		*diagnostic = SADB_X_DIAGNOSTIC_BAD_EALG;
3461 		return (EINVAL);
3462 	}
3463 
3464 	if (assoc->sadb_sa_encrypt == SADB_EALG_NULL &&
3465 	    assoc->sadb_sa_auth == SADB_AALG_NONE) {
3466 		*diagnostic = SADB_X_DIAGNOSTIC_BAD_AALG;
3467 		return (EINVAL);
3468 	}
3469 
3470 	if (assoc->sadb_sa_flags & ~(SADB_SAFLAGS_NOREPLAY |
3471 	    SADB_X_SAFLAGS_NATT_LOC | SADB_X_SAFLAGS_NATT_REM |
3472 	    SADB_X_SAFLAGS_TUNNEL | SADB_X_SAFLAGS_OUTBOUND |
3473 	    SADB_X_SAFLAGS_INBOUND | SADB_X_SAFLAGS_PAIRED)) {
3474 		*diagnostic = SADB_X_DIAGNOSTIC_BAD_SAFLAGS;
3475 		return (EINVAL);
3476 	}
3477 
3478 	if ((*diagnostic = sadb_hardsoftchk(hard, soft)) != 0) {
3479 		return (EINVAL);
3480 	}
3481 	ASSERT(src->sin_family == dst->sin_family);
3482 
3483 	if (assoc->sadb_sa_flags & SADB_X_SAFLAGS_NATT_LOC) {
3484 		if (nttext_loc == NULL) {
3485 			*diagnostic = SADB_X_DIAGNOSTIC_MISSING_NATT_LOC;
3486 			return (EINVAL);
3487 		}
3488 
3489 		if (natt_loc->sin_family == AF_INET6 &&
3490 		    !IN6_IS_ADDR_V4MAPPED(&natt_loc6->sin6_addr)) {
3491 			*diagnostic = SADB_X_DIAGNOSTIC_MALFORMED_NATT_LOC;
3492 			return (EINVAL);
3493 		}
3494 	}
3495 
3496 	if (assoc->sadb_sa_flags & SADB_X_SAFLAGS_NATT_REM) {
3497 		if (nttext_rem == NULL) {
3498 			*diagnostic = SADB_X_DIAGNOSTIC_MISSING_NATT_REM;
3499 			return (EINVAL);
3500 		}
3501 		if (natt_rem->sin_family == AF_INET6 &&
3502 		    !IN6_IS_ADDR_V4MAPPED(&natt_rem6->sin6_addr)) {
3503 			*diagnostic = SADB_X_DIAGNOSTIC_MALFORMED_NATT_REM;
3504 			return (EINVAL);
3505 		}
3506 	}
3507 
3508 
3509 	/* Stuff I don't support, for now.  XXX Diagnostic? */
3510 	if (ksi->ks_in_extv[SADB_EXT_LIFETIME_CURRENT] != NULL ||
3511 	    ksi->ks_in_extv[SADB_EXT_SENSITIVITY] != NULL)
3512 		return (EOPNOTSUPP);
3513 
3514 	/*
3515 	 * XXX Policy :  I'm not checking identities or sensitivity
3516 	 * labels at this time, but if I did, I'd do them here, before I sent
3517 	 * the weak key check up to the algorithm.
3518 	 */
3519 
3520 	mutex_enter(&ipss->ipsec_alg_lock);
3521 
3522 	/*
3523 	 * First locate the authentication algorithm.
3524 	 */
3525 	if (akey != NULL) {
3526 		ipsec_alginfo_t *aalg;
3527 
3528 		aalg = ipss->ipsec_alglists[IPSEC_ALG_AUTH]
3529 		    [assoc->sadb_sa_auth];
3530 		if (aalg == NULL || !ALG_VALID(aalg)) {
3531 			mutex_exit(&ipss->ipsec_alg_lock);
3532 			esp1dbg(espstack, ("Couldn't find auth alg #%d.\n",
3533 			    assoc->sadb_sa_auth));
3534 			*diagnostic = SADB_X_DIAGNOSTIC_BAD_AALG;
3535 			return (EINVAL);
3536 		}
3537 
3538 		/*
3539 		 * Sanity check key sizes.
3540 		 * Note: It's not possible to use SADB_AALG_NONE because
3541 		 * this auth_alg is not defined with ALG_FLAG_VALID. If this
3542 		 * ever changes, the same check for SADB_AALG_NONE and
3543 		 * a auth_key != NULL should be made here ( see below).
3544 		 */
3545 		if (!ipsec_valid_key_size(akey->sadb_key_bits, aalg)) {
3546 			mutex_exit(&ipss->ipsec_alg_lock);
3547 			*diagnostic = SADB_X_DIAGNOSTIC_BAD_AKEYBITS;
3548 			return (EINVAL);
3549 		}
3550 		ASSERT(aalg->alg_mech_type != CRYPTO_MECHANISM_INVALID);
3551 
3552 		/* check key and fix parity if needed */
3553 		if (ipsec_check_key(aalg->alg_mech_type, akey, B_TRUE,
3554 		    diagnostic) != 0) {
3555 			mutex_exit(&ipss->ipsec_alg_lock);
3556 			return (EINVAL);
3557 		}
3558 	}
3559 
3560 	/*
3561 	 * Then locate the encryption algorithm.
3562 	 */
3563 	if (ekey != NULL) {
3564 		ipsec_alginfo_t *ealg;
3565 
3566 		ealg = ipss->ipsec_alglists[IPSEC_ALG_ENCR]
3567 		    [assoc->sadb_sa_encrypt];
3568 		if (ealg == NULL || !ALG_VALID(ealg)) {
3569 			mutex_exit(&ipss->ipsec_alg_lock);
3570 			esp1dbg(espstack, ("Couldn't find encr alg #%d.\n",
3571 			    assoc->sadb_sa_encrypt));
3572 			*diagnostic = SADB_X_DIAGNOSTIC_BAD_EALG;
3573 			return (EINVAL);
3574 		}
3575 
3576 		/*
3577 		 * Sanity check key sizes. If the encryption algorithm is
3578 		 * SADB_EALG_NULL but the encryption key is NOT
3579 		 * NULL then complain.
3580 		 */
3581 		if ((assoc->sadb_sa_encrypt == SADB_EALG_NULL) ||
3582 		    (!ipsec_valid_key_size(ekey->sadb_key_bits, ealg))) {
3583 			mutex_exit(&ipss->ipsec_alg_lock);
3584 			*diagnostic = SADB_X_DIAGNOSTIC_BAD_EKEYBITS;
3585 			return (EINVAL);
3586 		}
3587 		ASSERT(ealg->alg_mech_type != CRYPTO_MECHANISM_INVALID);
3588 
3589 		/* check key */
3590 		if (ipsec_check_key(ealg->alg_mech_type, ekey, B_FALSE,
3591 		    diagnostic) != 0) {
3592 			mutex_exit(&ipss->ipsec_alg_lock);
3593 			return (EINVAL);
3594 		}
3595 	}
3596 	mutex_exit(&ipss->ipsec_alg_lock);
3597 
3598 	return (esp_add_sa_finish(mp, (sadb_msg_t *)mp->b_cont->b_rptr, ksi,
3599 	    diagnostic, espstack));
3600 }
3601 
3602 /*
3603  * Update a security association.  Updates come in two varieties.  The first
3604  * is an update of lifetimes on a non-larval SA.  The second is an update of
3605  * a larval SA, which ends up looking a lot more like an add.
3606  */
3607 static int
3608 esp_update_sa(mblk_t *mp, keysock_in_t *ksi, int *diagnostic,
3609     ipsecesp_stack_t *espstack, uint8_t sadb_msg_type)
3610 {
3611 	sadb_address_t *dstext =
3612 	    (sadb_address_t *)ksi->ks_in_extv[SADB_EXT_ADDRESS_DST];
3613 
3614 	if (dstext == NULL) {
3615 		*diagnostic = SADB_X_DIAGNOSTIC_MISSING_DST;
3616 		return (EINVAL);
3617 	}
3618 
3619 	return (sadb_update_sa(mp, ksi, &espstack->esp_sadb,
3620 	    diagnostic, espstack->esp_pfkey_q,
3621 	    esp_add_sa, espstack->ipsecesp_netstack, sadb_msg_type));
3622 }
3623 
3624 /*
3625  * Delete a security association.  This is REALLY likely to be code common to
3626  * both AH and ESP.  Find the association, then unlink it.
3627  */
3628 static int
3629 esp_del_sa(mblk_t *mp, keysock_in_t *ksi, int *diagnostic,
3630     ipsecesp_stack_t *espstack, uint8_t sadb_msg_type)
3631 {
3632 	sadb_sa_t *assoc = (sadb_sa_t *)ksi->ks_in_extv[SADB_EXT_SA];
3633 	sadb_address_t *dstext =
3634 	    (sadb_address_t *)ksi->ks_in_extv[SADB_EXT_ADDRESS_DST];
3635 	sadb_address_t *srcext =
3636 	    (sadb_address_t *)ksi->ks_in_extv[SADB_EXT_ADDRESS_SRC];
3637 	struct sockaddr_in *sin;
3638 
3639 	if (assoc == NULL) {
3640 		if (dstext != NULL) {
3641 			sin = (struct sockaddr_in *)(dstext + 1);
3642 		} else if (srcext != NULL) {
3643 			sin = (struct sockaddr_in *)(srcext + 1);
3644 		} else {
3645 			*diagnostic = SADB_X_DIAGNOSTIC_MISSING_SA;
3646 			return (EINVAL);
3647 		}
3648 		return (sadb_purge_sa(mp, ksi,
3649 		    (sin->sin_family == AF_INET6) ? &espstack->esp_sadb.s_v6 :
3650 		    &espstack->esp_sadb.s_v4, espstack->esp_pfkey_q,
3651 		    espstack->esp_sadb.s_ip_q));
3652 	}
3653 
3654 	return (sadb_delget_sa(mp, ksi, &espstack->esp_sadb, diagnostic,
3655 	    espstack->esp_pfkey_q, sadb_msg_type));
3656 }
3657 
3658 /*
3659  * Convert the entire contents of all of ESP's SA tables into PF_KEY SADB_DUMP
3660  * messages.
3661  */
3662 static void
3663 esp_dump(mblk_t *mp, keysock_in_t *ksi, ipsecesp_stack_t *espstack)
3664 {
3665 	int error;
3666 	sadb_msg_t *samsg;
3667 
3668 	/*
3669 	 * Dump each fanout, bailing if error is non-zero.
3670 	 */
3671 
3672 	error = sadb_dump(espstack->esp_pfkey_q, mp, ksi->ks_in_serial,
3673 	    &espstack->esp_sadb.s_v4);
3674 	if (error != 0)
3675 		goto bail;
3676 
3677 	error = sadb_dump(espstack->esp_pfkey_q, mp, ksi->ks_in_serial,
3678 	    &espstack->esp_sadb.s_v6);
3679 bail:
3680 	ASSERT(mp->b_cont != NULL);
3681 	samsg = (sadb_msg_t *)mp->b_cont->b_rptr;
3682 	samsg->sadb_msg_errno = (uint8_t)error;
3683 	sadb_pfkey_echo(espstack->esp_pfkey_q, mp,
3684 	    (sadb_msg_t *)mp->b_cont->b_rptr, ksi, NULL);
3685 }
3686 
3687 /*
3688  * First-cut reality check for an inbound PF_KEY message.
3689  */
3690 static boolean_t
3691 esp_pfkey_reality_failures(mblk_t *mp, keysock_in_t *ksi,
3692     ipsecesp_stack_t *espstack)
3693 {
3694 	int diagnostic;
3695 
3696 	if (ksi->ks_in_extv[SADB_EXT_PROPOSAL] != NULL) {
3697 		diagnostic = SADB_X_DIAGNOSTIC_PROP_PRESENT;
3698 		goto badmsg;
3699 	}
3700 	if (ksi->ks_in_extv[SADB_EXT_SUPPORTED_AUTH] != NULL ||
3701 	    ksi->ks_in_extv[SADB_EXT_SUPPORTED_ENCRYPT] != NULL) {
3702 		diagnostic = SADB_X_DIAGNOSTIC_SUPP_PRESENT;
3703 		goto badmsg;
3704 	}
3705 	return (B_FALSE);	/* False ==> no failures */
3706 
3707 badmsg:
3708 	sadb_pfkey_error(espstack->esp_pfkey_q, mp, EINVAL, diagnostic,
3709 	    ksi->ks_in_serial);
3710 	return (B_TRUE);	/* True ==> failures */
3711 }
3712 
3713 /*
3714  * ESP parsing of PF_KEY messages.  Keysock did most of the really silly
3715  * error cases.  What I receive is a fully-formed, syntactically legal
3716  * PF_KEY message.  I then need to check semantics...
3717  *
3718  * This code may become common to AH and ESP.  Stay tuned.
3719  *
3720  * I also make the assumption that db_ref's are cool.  If this assumption
3721  * is wrong, this means that someone other than keysock or me has been
3722  * mucking with PF_KEY messages.
3723  */
3724 static void
3725 esp_parse_pfkey(mblk_t *mp, ipsecesp_stack_t *espstack)
3726 {
3727 	mblk_t *msg = mp->b_cont;
3728 	sadb_msg_t *samsg;
3729 	keysock_in_t *ksi;
3730 	int error;
3731 	int diagnostic = SADB_X_DIAGNOSTIC_NONE;
3732 
3733 	ASSERT(msg != NULL);
3734 
3735 	samsg = (sadb_msg_t *)msg->b_rptr;
3736 	ksi = (keysock_in_t *)mp->b_rptr;
3737 
3738 	/*
3739 	 * If applicable, convert unspecified AF_INET6 to unspecified
3740 	 * AF_INET.  And do other address reality checks.
3741 	 */
3742 	if (!sadb_addrfix(ksi, espstack->esp_pfkey_q, mp,
3743 	    espstack->ipsecesp_netstack) ||
3744 	    esp_pfkey_reality_failures(mp, ksi, espstack)) {
3745 		return;
3746 	}
3747 
3748 	switch (samsg->sadb_msg_type) {
3749 	case SADB_ADD:
3750 		error = esp_add_sa(mp, ksi, &diagnostic,
3751 		    espstack->ipsecesp_netstack);
3752 		if (error != 0) {
3753 			sadb_pfkey_error(espstack->esp_pfkey_q, mp, error,
3754 			    diagnostic, ksi->ks_in_serial);
3755 		}
3756 		/* else esp_add_sa() took care of things. */
3757 		break;
3758 	case SADB_DELETE:
3759 	case SADB_X_DELPAIR:
3760 		error = esp_del_sa(mp, ksi, &diagnostic, espstack,
3761 		    samsg->sadb_msg_type);
3762 		if (error != 0) {
3763 			sadb_pfkey_error(espstack->esp_pfkey_q, mp, error,
3764 			    diagnostic, ksi->ks_in_serial);
3765 		}
3766 		/* Else esp_del_sa() took care of things. */
3767 		break;
3768 	case SADB_GET:
3769 		error = sadb_delget_sa(mp, ksi, &espstack->esp_sadb,
3770 		    &diagnostic, espstack->esp_pfkey_q, samsg->sadb_msg_type);
3771 		if (error != 0) {
3772 			sadb_pfkey_error(espstack->esp_pfkey_q, mp, error,
3773 			    diagnostic, ksi->ks_in_serial);
3774 		}
3775 		/* Else sadb_get_sa() took care of things. */
3776 		break;
3777 	case SADB_FLUSH:
3778 		sadbp_flush(&espstack->esp_sadb, espstack->ipsecesp_netstack);
3779 		sadb_pfkey_echo(espstack->esp_pfkey_q, mp, samsg, ksi, NULL);
3780 		break;
3781 	case SADB_REGISTER:
3782 		/*
3783 		 * Hmmm, let's do it!  Check for extensions (there should
3784 		 * be none), extract the fields, call esp_register_out(),
3785 		 * then either free or report an error.
3786 		 *
3787 		 * Keysock takes care of the PF_KEY bookkeeping for this.
3788 		 */
3789 		if (esp_register_out(samsg->sadb_msg_seq, samsg->sadb_msg_pid,
3790 		    ksi->ks_in_serial, espstack)) {
3791 			freemsg(mp);
3792 		} else {
3793 			/*
3794 			 * Only way this path hits is if there is a memory
3795 			 * failure.  It will not return B_FALSE because of
3796 			 * lack of esp_pfkey_q if I am in wput().
3797 			 */
3798 			sadb_pfkey_error(espstack->esp_pfkey_q, mp, ENOMEM,
3799 			    diagnostic, ksi->ks_in_serial);
3800 		}
3801 		break;
3802 	case SADB_UPDATE:
3803 	case SADB_X_UPDATEPAIR:
3804 		/*
3805 		 * Find a larval, if not there, find a full one and get
3806 		 * strict.
3807 		 */
3808 		error = esp_update_sa(mp, ksi, &diagnostic, espstack,
3809 		    samsg->sadb_msg_type);
3810 		if (error != 0) {
3811 			sadb_pfkey_error(espstack->esp_pfkey_q, mp, error,
3812 			    diagnostic, ksi->ks_in_serial);
3813 		}
3814 		/* else esp_update_sa() took care of things. */
3815 		break;
3816 	case SADB_GETSPI:
3817 		/*
3818 		 * Reserve a new larval entry.
3819 		 */
3820 		esp_getspi(mp, ksi, espstack);
3821 		break;
3822 	case SADB_ACQUIRE:
3823 		/*
3824 		 * Find larval and/or ACQUIRE record and kill it (them), I'm
3825 		 * most likely an error.  Inbound ACQUIRE messages should only
3826 		 * have the base header.
3827 		 */
3828 		sadb_in_acquire(samsg, &espstack->esp_sadb,
3829 		    espstack->esp_pfkey_q, espstack->ipsecesp_netstack);
3830 		freemsg(mp);
3831 		break;
3832 	case SADB_DUMP:
3833 		/*
3834 		 * Dump all entries.
3835 		 */
3836 		esp_dump(mp, ksi, espstack);
3837 		/* esp_dump will take care of the return message, etc. */
3838 		break;
3839 	case SADB_EXPIRE:
3840 		/* Should never reach me. */
3841 		sadb_pfkey_error(espstack->esp_pfkey_q, mp, EOPNOTSUPP,
3842 		    diagnostic, ksi->ks_in_serial);
3843 		break;
3844 	default:
3845 		sadb_pfkey_error(espstack->esp_pfkey_q, mp, EINVAL,
3846 		    SADB_X_DIAGNOSTIC_UNKNOWN_MSG, ksi->ks_in_serial);
3847 		break;
3848 	}
3849 }
3850 
3851 /*
3852  * Handle case where PF_KEY says it can't find a keysock for one of my
3853  * ACQUIRE messages.
3854  */
3855 static void
3856 esp_keysock_no_socket(mblk_t *mp, ipsecesp_stack_t *espstack)
3857 {
3858 	sadb_msg_t *samsg;
3859 	keysock_out_err_t *kse = (keysock_out_err_t *)mp->b_rptr;
3860 
3861 	if (mp->b_cont == NULL) {
3862 		freemsg(mp);
3863 		return;
3864 	}
3865 	samsg = (sadb_msg_t *)mp->b_cont->b_rptr;
3866 
3867 	/*
3868 	 * If keysock can't find any registered, delete the acquire record
3869 	 * immediately, and handle errors.
3870 	 */
3871 	if (samsg->sadb_msg_type == SADB_ACQUIRE) {
3872 		samsg->sadb_msg_errno = kse->ks_err_errno;
3873 		samsg->sadb_msg_len = SADB_8TO64(sizeof (*samsg));
3874 		/*
3875 		 * Use the write-side of the esp_pfkey_q, in case there is
3876 		 * no esp_sadb.s_ip_q.
3877 		 */
3878 		sadb_in_acquire(samsg, &espstack->esp_sadb,
3879 		    WR(espstack->esp_pfkey_q), espstack->ipsecesp_netstack);
3880 	}
3881 
3882 	freemsg(mp);
3883 }
3884 
3885 /*
3886  * ESP module write put routine.
3887  */
3888 static void
3889 ipsecesp_wput(queue_t *q, mblk_t *mp)
3890 {
3891 	ipsec_info_t *ii;
3892 	struct iocblk *iocp;
3893 	ipsecesp_stack_t	*espstack = (ipsecesp_stack_t *)q->q_ptr;
3894 
3895 	esp3dbg(espstack, ("In esp_wput().\n"));
3896 
3897 	/* NOTE: Each case must take care of freeing or passing mp. */
3898 	switch (mp->b_datap->db_type) {
3899 	case M_CTL:
3900 		if ((mp->b_wptr - mp->b_rptr) < sizeof (ipsec_info_t)) {
3901 			/* Not big enough message. */
3902 			freemsg(mp);
3903 			break;
3904 		}
3905 		ii = (ipsec_info_t *)mp->b_rptr;
3906 
3907 		switch (ii->ipsec_info_type) {
3908 		case KEYSOCK_OUT_ERR:
3909 			esp1dbg(espstack, ("Got KEYSOCK_OUT_ERR message.\n"));
3910 			esp_keysock_no_socket(mp, espstack);
3911 			break;
3912 		case KEYSOCK_IN:
3913 			ESP_BUMP_STAT(espstack, keysock_in);
3914 			esp3dbg(espstack, ("Got KEYSOCK_IN message.\n"));
3915 
3916 			/* Parse the message. */
3917 			esp_parse_pfkey(mp, espstack);
3918 			break;
3919 		case KEYSOCK_HELLO:
3920 			sadb_keysock_hello(&espstack->esp_pfkey_q, q, mp,
3921 			    esp_ager, (void *)espstack, &espstack->esp_event,
3922 			    SADB_SATYPE_ESP);
3923 			break;
3924 		default:
3925 			esp2dbg(espstack, ("Got M_CTL from above of 0x%x.\n",
3926 			    ii->ipsec_info_type));
3927 			freemsg(mp);
3928 			break;
3929 		}
3930 		break;
3931 	case M_IOCTL:
3932 		iocp = (struct iocblk *)mp->b_rptr;
3933 		switch (iocp->ioc_cmd) {
3934 		case ND_SET:
3935 		case ND_GET:
3936 			if (nd_getset(q, espstack->ipsecesp_g_nd, mp)) {
3937 				qreply(q, mp);
3938 				return;
3939 			} else {
3940 				iocp->ioc_error = ENOENT;
3941 			}
3942 			/* FALLTHRU */
3943 		default:
3944 			/* We really don't support any other ioctls, do we? */
3945 
3946 			/* Return EINVAL */
3947 			if (iocp->ioc_error != ENOENT)
3948 				iocp->ioc_error = EINVAL;
3949 			iocp->ioc_count = 0;
3950 			mp->b_datap->db_type = M_IOCACK;
3951 			qreply(q, mp);
3952 			return;
3953 		}
3954 	default:
3955 		esp3dbg(espstack,
3956 		    ("Got default message, type %d, passing to IP.\n",
3957 		    mp->b_datap->db_type));
3958 		putnext(q, mp);
3959 	}
3960 }
3961 
3962 /*
3963  * Process an outbound ESP packet that can be accelerated by a IPsec
3964  * hardware acceleration capable Provider.
3965  * The caller already inserted and initialized the ESP header.
3966  * This function allocates a tagging M_CTL, and adds room at the end
3967  * of the packet to hold the ICV if authentication is needed.
3968  *
3969  * On success returns B_TRUE, on failure returns B_FALSE and frees the
3970  * mblk chain ipsec_out.
3971  */
3972 static ipsec_status_t
3973 esp_outbound_accelerated(mblk_t *ipsec_out, uint_t icv_len)
3974 {
3975 	ipsec_out_t *io;
3976 	mblk_t *lastmp;
3977 	netstack_t	*ns;
3978 	ipsecesp_stack_t *espstack;
3979 	ipsec_stack_t	*ipss;
3980 
3981 	io = (ipsec_out_t *)ipsec_out->b_rptr;
3982 	ns = io->ipsec_out_ns;
3983 	espstack = ns->netstack_ipsecesp;
3984 	ipss = ns->netstack_ipsec;
3985 
3986 	ESP_BUMP_STAT(espstack, out_accelerated);
3987 
3988 	/* mark packet as being accelerated in IPSEC_OUT */
3989 	ASSERT(io->ipsec_out_accelerated == B_FALSE);
3990 	io->ipsec_out_accelerated = B_TRUE;
3991 
3992 	/*
3993 	 * add room at the end of the packet for the ICV if needed
3994 	 */
3995 	if (icv_len > 0) {
3996 		/* go to last mblk */
3997 		lastmp = ipsec_out;	/* For following while loop. */
3998 		do {
3999 			lastmp = lastmp->b_cont;
4000 		} while (lastmp->b_cont != NULL);
4001 
4002 		/* if not enough available room, allocate new mblk */
4003 		if ((lastmp->b_wptr + icv_len) > lastmp->b_datap->db_lim) {
4004 			lastmp->b_cont = allocb(icv_len, BPRI_HI);
4005 			if (lastmp->b_cont == NULL) {
4006 				ESP_BUMP_STAT(espstack, out_discards);
4007 				ip_drop_packet(ipsec_out, B_FALSE, NULL, NULL,
4008 				    DROPPER(ipss, ipds_esp_nomem),
4009 				    &espstack->esp_dropper);
4010 				return (IPSEC_STATUS_FAILED);
4011 			}
4012 			lastmp = lastmp->b_cont;
4013 		}
4014 		lastmp->b_wptr += icv_len;
4015 	}
4016 
4017 	return (IPSEC_STATUS_SUCCESS);
4018 }
4019 
4020 /*
4021  * Process an inbound accelerated ESP packet.
4022  * On success returns B_TRUE, on failure returns B_FALSE and frees the
4023  * mblk chain ipsec_in.
4024  */
4025 static ipsec_status_t
4026 esp_inbound_accelerated(mblk_t *ipsec_in, mblk_t *data_mp, boolean_t isv4,
4027     ipsa_t *assoc)
4028 {
4029 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_in->b_rptr;
4030 	mblk_t *hada_mp;
4031 	uint32_t icv_len = 0;
4032 	da_ipsec_t *hada;
4033 	ipha_t *ipha;
4034 	ip6_t *ip6h;
4035 	kstat_named_t *counter;
4036 	netstack_t	*ns = ii->ipsec_in_ns;
4037 	ipsecesp_stack_t *espstack = ns->netstack_ipsecesp;
4038 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
4039 
4040 	ESP_BUMP_STAT(espstack, in_accelerated);
4041 
4042 	hada_mp = ii->ipsec_in_da;
4043 	ASSERT(hada_mp != NULL);
4044 	hada = (da_ipsec_t *)hada_mp->b_rptr;
4045 
4046 	/*
4047 	 * We only support one level of decapsulation in hardware, so
4048 	 * nuke the pointer.
4049 	 */
4050 	ii->ipsec_in_da = NULL;
4051 	ii->ipsec_in_accelerated = B_FALSE;
4052 
4053 	if (assoc->ipsa_auth_alg != IPSA_AALG_NONE) {
4054 		/*
4055 		 * ESP with authentication. We expect the Provider to have
4056 		 * computed the ICV and placed it in the hardware acceleration
4057 		 * data attributes.
4058 		 *
4059 		 * Extract ICV length from attributes M_CTL and sanity check
4060 		 * its value. We allow the mblk to be smaller than da_ipsec_t
4061 		 * for a small ICV, as long as the entire ICV fits within the
4062 		 * mblk.
4063 		 *
4064 		 * Also ensures that the ICV length computed by Provider
4065 		 * corresponds to the ICV length of the agorithm specified by
4066 		 * the SA.
4067 		 */
4068 		icv_len = hada->da_icv_len;
4069 		if ((icv_len != assoc->ipsa_mac_len) ||
4070 		    (icv_len > DA_ICV_MAX_LEN) || (MBLKL(hada_mp) <
4071 		    (sizeof (da_ipsec_t) - DA_ICV_MAX_LEN + icv_len))) {
4072 			esp0dbg(("esp_inbound_accelerated: "
4073 			    "ICV len (%u) incorrect or mblk too small (%u)\n",
4074 			    icv_len, (uint32_t)(MBLKL(hada_mp))));
4075 			counter = DROPPER(ipss, ipds_esp_bad_auth);
4076 			goto esp_in_discard;
4077 		}
4078 	}
4079 
4080 	/* get pointers to IP header */
4081 	if (isv4) {
4082 		ipha = (ipha_t *)data_mp->b_rptr;
4083 	} else {
4084 		ip6h = (ip6_t *)data_mp->b_rptr;
4085 	}
4086 
4087 	/*
4088 	 * Compare ICV in ESP packet vs ICV computed by adapter.
4089 	 * We also remove the ICV from the end of the packet since
4090 	 * it will no longer be needed.
4091 	 *
4092 	 * Assume that esp_inbound() already ensured that the pkt
4093 	 * was in one mblk.
4094 	 */
4095 	ASSERT(data_mp->b_cont == NULL);
4096 	data_mp->b_wptr -= icv_len;
4097 	/* adjust IP header */
4098 	if (isv4)
4099 		ipha->ipha_length = htons(ntohs(ipha->ipha_length) - icv_len);
4100 	else
4101 		ip6h->ip6_plen = htons(ntohs(ip6h->ip6_plen) - icv_len);
4102 	if (icv_len && bcmp(hada->da_icv, data_mp->b_wptr, icv_len)) {
4103 		int af;
4104 		void *addr;
4105 
4106 		if (isv4) {
4107 			addr = &ipha->ipha_dst;
4108 			af = AF_INET;
4109 		} else {
4110 			addr = &ip6h->ip6_dst;
4111 			af = AF_INET6;
4112 		}
4113 
4114 		/*
4115 		 * Log the event. Don't print to the console, block
4116 		 * potential denial-of-service attack.
4117 		 */
4118 		ESP_BUMP_STAT(espstack, bad_auth);
4119 		ipsec_assocfailure(info.mi_idnum, 0, 0, SL_ERROR | SL_WARN,
4120 		    "ESP Authentication failed spi %x, dst_addr %s",
4121 		    assoc->ipsa_spi, addr, af, espstack->ipsecesp_netstack);
4122 		counter = DROPPER(ipss, ipds_esp_bad_auth);
4123 		goto esp_in_discard;
4124 	}
4125 
4126 	esp3dbg(espstack, ("esp_inbound_accelerated: ESP authentication "
4127 	    "succeeded, checking replay\n"));
4128 
4129 	ipsec_in->b_cont = data_mp;
4130 
4131 	/*
4132 	 * Remove ESP header and padding from packet.
4133 	 */
4134 	if (!esp_strip_header(data_mp, ii->ipsec_in_v4, assoc->ipsa_iv_len,
4135 	    &counter, espstack)) {
4136 		esp1dbg(espstack, ("esp_inbound_accelerated: "
4137 		    "esp_strip_header() failed\n"));
4138 		goto esp_in_discard;
4139 	}
4140 
4141 	freeb(hada_mp);
4142 
4143 	/*
4144 	 * Account for usage..
4145 	 */
4146 	if (!esp_age_bytes(assoc, msgdsize(data_mp), B_TRUE)) {
4147 		/* The ipsa has hit hard expiration, LOG and AUDIT. */
4148 		ESP_BUMP_STAT(espstack, bytes_expired);
4149 		IP_ESP_BUMP_STAT(ipss, in_discards);
4150 		ipsec_assocfailure(info.mi_idnum, 0, 0, SL_ERROR | SL_WARN,
4151 		    "ESP association 0x%x, dst %s had bytes expire.\n",
4152 		    assoc->ipsa_spi, assoc->ipsa_dstaddr, assoc->ipsa_addrfam,
4153 		    espstack->ipsecesp_netstack);
4154 		ip_drop_packet(ipsec_in, B_TRUE, NULL, NULL,
4155 		    DROPPER(ipss, ipds_esp_bytes_expire),
4156 		    &espstack->esp_dropper);
4157 		return (IPSEC_STATUS_FAILED);
4158 	}
4159 
4160 	/* done processing the packet */
4161 	return (IPSEC_STATUS_SUCCESS);
4162 
4163 esp_in_discard:
4164 	IP_ESP_BUMP_STAT(ipss, in_discards);
4165 	freeb(hada_mp);
4166 
4167 	ipsec_in->b_cont = data_mp;	/* For ip_drop_packet()'s sake... */
4168 	ip_drop_packet(ipsec_in, B_TRUE, NULL, NULL, counter,
4169 	    &espstack->esp_dropper);
4170 
4171 	return (IPSEC_STATUS_FAILED);
4172 }
4173 
4174 /*
4175  * Wrapper to allow IP to trigger an ESP association failure message
4176  * during inbound SA selection.
4177  */
4178 void
4179 ipsecesp_in_assocfailure(mblk_t *mp, char level, ushort_t sl, char *fmt,
4180     uint32_t spi, void *addr, int af, ipsecesp_stack_t *espstack)
4181 {
4182 	ipsec_stack_t	*ipss = espstack->ipsecesp_netstack->netstack_ipsec;
4183 
4184 	if (espstack->ipsecesp_log_unknown_spi) {
4185 		ipsec_assocfailure(info.mi_idnum, 0, level, sl, fmt, spi,
4186 		    addr, af, espstack->ipsecesp_netstack);
4187 	}
4188 
4189 	ip_drop_packet(mp, B_TRUE, NULL, NULL,
4190 	    DROPPER(ipss, ipds_esp_no_sa),
4191 	    &espstack->esp_dropper);
4192 }
4193 
4194 /*
4195  * Initialize the ESP input and output processing functions.
4196  */
4197 void
4198 ipsecesp_init_funcs(ipsa_t *sa)
4199 {
4200 	if (sa->ipsa_output_func == NULL)
4201 		sa->ipsa_output_func = esp_outbound;
4202 	if (sa->ipsa_input_func == NULL)
4203 		sa->ipsa_input_func = esp_inbound;
4204 }
4205