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