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