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