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