Home | History | Annotate | Line # | Download | only in netipsec
xform_ah.c revision 1.87
      1 /*	$NetBSD: xform_ah.c,v 1.87 2018/02/26 06:40:08 maxv Exp $	*/
      2 /*	$FreeBSD: src/sys/netipsec/xform_ah.c,v 1.1.4.1 2003/01/24 05:11:36 sam Exp $	*/
      3 /*	$OpenBSD: ip_ah.c,v 1.63 2001/06/26 06:18:58 angelos Exp $ */
      4 /*
      5  * The authors of this code are John Ioannidis (ji (at) tla.org),
      6  * Angelos D. Keromytis (kermit (at) csd.uch.gr) and
      7  * Niels Provos (provos (at) physnet.uni-hamburg.de).
      8  *
      9  * The original version of this code was written by John Ioannidis
     10  * for BSD/OS in Athens, Greece, in November 1995.
     11  *
     12  * Ported to OpenBSD and NetBSD, with additional transforms, in December 1996,
     13  * by Angelos D. Keromytis.
     14  *
     15  * Additional transforms and features in 1997 and 1998 by Angelos D. Keromytis
     16  * and Niels Provos.
     17  *
     18  * Additional features in 1999 by Angelos D. Keromytis and Niklas Hallqvist.
     19  *
     20  * Copyright (c) 1995, 1996, 1997, 1998, 1999 by John Ioannidis,
     21  * Angelos D. Keromytis and Niels Provos.
     22  * Copyright (c) 1999 Niklas Hallqvist.
     23  * Copyright (c) 2001 Angelos D. Keromytis.
     24  *
     25  * Permission to use, copy, and modify this software with or without fee
     26  * is hereby granted, provided that this entire notice is included in
     27  * all copies of any software which is or includes a copy or
     28  * modification of this software.
     29  * You may use this code under the GNU public license if you so wish. Please
     30  * contribute changes back to the authors under this freer than GPL license
     31  * so that we may further the use of strong encryption without limitations to
     32  * all.
     33  *
     34  * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR
     35  * IMPLIED WARRANTY. IN PARTICULAR, NONE OF THE AUTHORS MAKES ANY
     36  * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE
     37  * MERCHANTABILITY OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR
     38  * PURPOSE.
     39  */
     40 
     41 #include <sys/cdefs.h>
     42 __KERNEL_RCSID(0, "$NetBSD: xform_ah.c,v 1.87 2018/02/26 06:40:08 maxv Exp $");
     43 
     44 #if defined(_KERNEL_OPT)
     45 #include "opt_inet.h"
     46 #include "opt_ipsec.h"
     47 #endif
     48 
     49 #include <sys/param.h>
     50 #include <sys/systm.h>
     51 #include <sys/mbuf.h>
     52 #include <sys/socket.h>
     53 #include <sys/syslog.h>
     54 #include <sys/kernel.h>
     55 #include <sys/sysctl.h>
     56 #include <sys/pool.h>
     57 #include <sys/pserialize.h>
     58 #include <sys/kmem.h>
     59 
     60 #include <net/if.h>
     61 
     62 #include <netinet/in.h>
     63 #include <netinet/in_systm.h>
     64 #include <netinet/ip.h>
     65 #include <netinet/ip_ecn.h>
     66 #include <netinet/ip_var.h>
     67 #include <netinet/ip6.h>
     68 
     69 #include <net/route.h>
     70 #include <netipsec/ipsec.h>
     71 #include <netipsec/ipsec_private.h>
     72 #include <netipsec/ah.h>
     73 #include <netipsec/ah_var.h>
     74 #include <netipsec/xform.h>
     75 
     76 #ifdef INET6
     77 #include <netinet6/ip6_var.h>
     78 #include <netinet6/scope6_var.h>
     79 #include <netipsec/ipsec6.h>
     80 #endif
     81 
     82 #include <netipsec/key.h>
     83 #include <netipsec/key_debug.h>
     84 
     85 #include <opencrypto/cryptodev.h>
     86 
     87 /*
     88  * Return header size in bytes.  The old protocol did not support
     89  * the replay counter; the new protocol always includes the counter.
     90  */
     91 #define HDRSIZE(sav) \
     92 	(((sav)->flags & SADB_X_EXT_OLD) ? \
     93 		sizeof(struct ah) : sizeof(struct ah) + sizeof(uint32_t))
     94 /*
     95  * Return authenticator size in bytes.  The old protocol is known
     96  * to use a fixed 16-byte authenticator.  The new algorithm gets
     97  * this size from the xform but is (currently) always 12.
     98  */
     99 #define	AUTHSIZE(sav) \
    100 	((sav->flags & SADB_X_EXT_OLD) ? 16 : (sav)->tdb_authalgxform->authsize)
    101 
    102 percpu_t *ahstat_percpu;
    103 
    104 int ah_enable = 1;			/* control flow of packets with AH */
    105 int ip4_ah_cleartos = 1;		/* clear ip_tos when doing AH calc */
    106 
    107 static unsigned char ipseczeroes[256];	/* larger than an ip6 extension hdr */
    108 
    109 int ah_max_authsize;			/* max authsize over all algorithms */
    110 
    111 static int ah_input_cb(struct cryptop *);
    112 static int ah_output_cb(struct cryptop *);
    113 
    114 const uint8_t ah_stats[256] = { SADB_AALG_STATS_INIT };
    115 
    116 static pool_cache_t ah_tdb_crypto_pool_cache;
    117 static size_t ah_pool_item_size;
    118 
    119 /*
    120  * NB: this is public for use by the PF_KEY support.
    121  */
    122 const struct auth_hash *
    123 ah_algorithm_lookup(int alg)
    124 {
    125 
    126 	switch (alg) {
    127 	case SADB_X_AALG_NULL:
    128 		return &auth_hash_null;
    129 	case SADB_AALG_MD5HMAC:
    130 		return &auth_hash_hmac_md5_96;
    131 	case SADB_AALG_SHA1HMAC:
    132 		return &auth_hash_hmac_sha1_96;
    133 	case SADB_X_AALG_RIPEMD160HMAC:
    134 		return &auth_hash_hmac_ripemd_160_96;
    135 	case SADB_X_AALG_MD5:
    136 		return &auth_hash_key_md5;
    137 	case SADB_X_AALG_SHA:
    138 		return &auth_hash_key_sha1;
    139 	case SADB_X_AALG_SHA2_256:
    140 		return &auth_hash_hmac_sha2_256;
    141 	case SADB_X_AALG_SHA2_384:
    142 		return &auth_hash_hmac_sha2_384;
    143 	case SADB_X_AALG_SHA2_512:
    144 		return &auth_hash_hmac_sha2_512;
    145 	case SADB_X_AALG_AES_XCBC_MAC:
    146 		return &auth_hash_aes_xcbc_mac_96;
    147 	}
    148 	return NULL;
    149 }
    150 
    151 size_t
    152 ah_hdrsiz(const struct secasvar *sav)
    153 {
    154 	size_t size;
    155 
    156 	if (sav != NULL) {
    157 		int authsize;
    158 		KASSERT(sav->tdb_authalgxform != NULL);
    159 		/*XXX not right for null algorithm--does it matter??*/
    160 		authsize = AUTHSIZE(sav);
    161 		size = roundup(authsize, sizeof(uint32_t)) + HDRSIZE(sav);
    162 	} else {
    163 		/* default guess */
    164 		size = sizeof(struct ah) + sizeof(uint32_t) + ah_max_authsize;
    165 	}
    166 	return size;
    167 }
    168 
    169 /*
    170  * NB: public for use by esp_init.
    171  */
    172 int
    173 ah_init0(struct secasvar *sav, const struct xformsw *xsp,
    174 	 struct cryptoini *cria)
    175 {
    176 	const struct auth_hash *thash;
    177 	int keylen;
    178 
    179 	thash = ah_algorithm_lookup(sav->alg_auth);
    180 	if (thash == NULL) {
    181 		DPRINTF(("%s: unsupported authentication algorithm %u\n",
    182 			__func__, sav->alg_auth));
    183 		return EINVAL;
    184 	}
    185 	/*
    186 	 * Verify the replay state block allocation is consistent with
    187 	 * the protocol type.  We check here so we can make assumptions
    188 	 * later during protocol processing.
    189 	 */
    190 	/* NB: replay state is setup elsewhere (sigh) */
    191 	if (((sav->flags&SADB_X_EXT_OLD) == 0) ^ (sav->replay != NULL)) {
    192 		DPRINTF(("%s: replay state block inconsistency, "
    193 			"%s algorithm %s replay state\n", __func__,
    194 			(sav->flags & SADB_X_EXT_OLD) ? "old" : "new",
    195 			sav->replay == NULL ? "without" : "with"));
    196 		return EINVAL;
    197 	}
    198 	if (sav->key_auth == NULL) {
    199 		DPRINTF(("%s: no authentication key for %s algorithm\n",
    200 			__func__, thash->name));
    201 		return EINVAL;
    202 	}
    203 	keylen = _KEYLEN(sav->key_auth);
    204 	if (keylen != thash->keysize && thash->keysize != 0) {
    205 		DPRINTF(("%s: invalid keylength %d, algorithm %s requires "
    206 			 "keysize %d\n", __func__,
    207 			 keylen, thash->name, thash->keysize));
    208 		return EINVAL;
    209 	}
    210 
    211 	sav->tdb_xform = xsp;
    212 	sav->tdb_authalgxform = thash;
    213 
    214 	/* Initialize crypto session. */
    215 	memset(cria, 0, sizeof(*cria));
    216 	cria->cri_alg = sav->tdb_authalgxform->type;
    217 	cria->cri_klen = _KEYBITS(sav->key_auth);
    218 	cria->cri_key = _KEYBUF(sav->key_auth);
    219 
    220 	return 0;
    221 }
    222 
    223 /*
    224  * ah_init() is called when an SPI is being set up.
    225  */
    226 static int
    227 ah_init(struct secasvar *sav, const struct xformsw *xsp)
    228 {
    229 	struct cryptoini cria;
    230 	int error;
    231 
    232 	error = ah_init0(sav, xsp, &cria);
    233 	if (!error)
    234 		error = crypto_newsession(&sav->tdb_cryptoid,
    235 					   &cria, crypto_support);
    236 	return error;
    237 }
    238 
    239 /*
    240  * Paranoia.
    241  *
    242  * NB: public for use by esp_zeroize (XXX).
    243  */
    244 int
    245 ah_zeroize(struct secasvar *sav)
    246 {
    247 	int err;
    248 
    249 	if (sav->key_auth) {
    250 		explicit_memset(_KEYBUF(sav->key_auth), 0,
    251 		    _KEYLEN(sav->key_auth));
    252 	}
    253 
    254 	err = crypto_freesession(sav->tdb_cryptoid);
    255 	sav->tdb_cryptoid = 0;
    256 	sav->tdb_authalgxform = NULL;
    257 	sav->tdb_xform = NULL;
    258 	return err;
    259 }
    260 
    261 /*
    262  * Massage IPv4/IPv6 headers for AH processing.
    263  */
    264 static int
    265 ah_massage_headers(struct mbuf **m0, int proto, int skip, int alg, int out)
    266 {
    267 	struct mbuf *m = *m0;
    268 	unsigned char *ptr;
    269 	int off, count;
    270 #ifdef INET
    271 	struct ip *ip;
    272 #endif
    273 #ifdef INET6
    274 	struct ip6_ext *ip6e;
    275 	struct ip6_hdr ip6;
    276 	struct ip6_rthdr *rh;
    277 	int alloc, ad, nxt;
    278 #endif
    279 
    280 	switch (proto) {
    281 #ifdef INET
    282 	case AF_INET:
    283 		/*
    284 		 * This is the least painful way of dealing with IPv4 header
    285 		 * and option processing -- just make sure they're in
    286 		 * contiguous memory.
    287 		 */
    288 		*m0 = m = m_pullup(m, skip);
    289 		if (m == NULL) {
    290 			DPRINTF(("%s: m_pullup failed\n", __func__));
    291 			return ENOBUFS;
    292 		}
    293 
    294 		/* Fix the IP header */
    295 		ip = mtod(m, struct ip *);
    296 		if (ip4_ah_cleartos)
    297 			ip->ip_tos = 0;
    298 		ip->ip_ttl = 0;
    299 		ip->ip_sum = 0;
    300 		ip->ip_off = htons(ntohs(ip->ip_off) & ip4_ah_offsetmask);
    301 
    302 		/*
    303 		 * On FreeBSD, ip_off and ip_len assumed in host endian;
    304 		 * they are converted (if necessary) by ip_input().
    305 		 * On NetBSD, ip_off and ip_len are in network byte order.
    306 		 * They must be massaged back to network byte order
    307 		 * before verifying the  HMAC. Moreover, on FreeBSD,
    308 		 * we should add `skip' back into the massaged ip_len
    309 		 * (presumably ip_input() deducted it before we got here?)
    310 		 * whereas on NetBSD, we should not.
    311 		 */
    312 		if (!out) {
    313 			uint16_t inlen = ntohs(ip->ip_len);
    314 
    315 			ip->ip_len = htons(inlen);
    316 
    317 			if (alg == CRYPTO_MD5_KPDK || alg == CRYPTO_SHA1_KPDK)
    318 				ip->ip_off  &= htons(IP_DF);
    319 			else
    320 				ip->ip_off = 0;
    321 		} else {
    322 			if (alg == CRYPTO_MD5_KPDK || alg == CRYPTO_SHA1_KPDK)
    323 				ip->ip_off &= htons(IP_DF);
    324 			else
    325 				ip->ip_off = 0;
    326 		}
    327 
    328 		ptr = mtod(m, unsigned char *);
    329 
    330 		/* IPv4 option processing */
    331 		for (off = sizeof(struct ip); off < skip;) {
    332 			if (ptr[off] == IPOPT_EOL || ptr[off] == IPOPT_NOP ||
    333 			    off + 1 < skip)
    334 				;
    335 			else {
    336 				DPRINTF(("%s: illegal IPv4 option length for "
    337 				    "option %d\n", __func__, ptr[off]));
    338 
    339 				m_freem(m);
    340 				return EINVAL;
    341 			}
    342 
    343 			switch (ptr[off]) {
    344 			case IPOPT_EOL:
    345 				off = skip;  /* End the loop. */
    346 				break;
    347 
    348 			case IPOPT_NOP:
    349 				off++;
    350 				break;
    351 
    352 			case IPOPT_SECURITY:	/* 0x82 */
    353 			case 0x85:	/* Extended security. */
    354 			case 0x86:	/* Commercial security. */
    355 			case 0x94:	/* Router alert */
    356 			case 0x95:	/* RFC1770 */
    357 				/* Sanity check for option length. */
    358 				if (ptr[off + 1] < 2) {
    359 					DPRINTF(("%s: illegal IPv4 option "
    360 					    "length for option %d\n", __func__,
    361 					    ptr[off]));
    362 
    363 					m_freem(m);
    364 					return EINVAL;
    365 				}
    366 
    367 				off += ptr[off + 1];
    368 				break;
    369 
    370 			case IPOPT_LSRR:
    371 			case IPOPT_SSRR:
    372 				/* Sanity check for option length. */
    373 				if (ptr[off + 1] < 2) {
    374 					DPRINTF(("%s: illegal IPv4 option "
    375 					    "length for option %d\n", __func__,
    376 					    ptr[off]));
    377 
    378 					m_freem(m);
    379 					return EINVAL;
    380 				}
    381 
    382 				/*
    383 				 * On output, if we have either of the
    384 				 * source routing options, we should
    385 				 * swap the destination address of the
    386 				 * IP header with the last address
    387 				 * specified in the option, as that is
    388 				 * what the destination's IP header
    389 				 * will look like.
    390 				 */
    391 				if (out)
    392 					memcpy(&ip->ip_dst,
    393 					    ptr + off + ptr[off + 1] -
    394 					    sizeof(struct in_addr),
    395 					    sizeof(struct in_addr));
    396 
    397 				/* Fall through */
    398 			default:
    399 				/* Sanity check for option length. */
    400 				if (ptr[off + 1] < 2) {
    401 					DPRINTF(("%s: illegal IPv4 option "
    402 					    "length for option %d\n", __func__,
    403 					    ptr[off]));
    404 					m_freem(m);
    405 					return EINVAL;
    406 				}
    407 
    408 				/* Zeroize all other options. */
    409 				count = ptr[off + 1];
    410 				memcpy(ptr + off, ipseczeroes, count);
    411 				off += count;
    412 				break;
    413 			}
    414 
    415 			/* Sanity check. */
    416 			if (off > skip)	{
    417 				DPRINTF(("%s: malformed IPv4 options header\n",
    418 					__func__));
    419 				m_freem(m);
    420 				return EINVAL;
    421 			}
    422 		}
    423 
    424 		break;
    425 #endif /* INET */
    426 
    427 #ifdef INET6
    428 	case AF_INET6:  /* Ugly... */
    429 		/* Copy and "cook" the IPv6 header. */
    430 		m_copydata(m, 0, sizeof(ip6), &ip6);
    431 
    432 		/* We don't do IPv6 Jumbograms. */
    433 		if (ip6.ip6_plen == 0) {
    434 			DPRINTF(("%s: unsupported IPv6 jumbogram\n", __func__));
    435 			m_freem(m);
    436 			return EMSGSIZE;
    437 		}
    438 
    439 		ip6.ip6_flow = 0;
    440 		ip6.ip6_hlim = 0;
    441 		ip6.ip6_vfc &= ~IPV6_VERSION_MASK;
    442 		ip6.ip6_vfc |= IPV6_VERSION;
    443 
    444 		/* Scoped address handling. */
    445 		if (IN6_IS_SCOPE_LINKLOCAL(&ip6.ip6_src))
    446 			ip6.ip6_src.s6_addr16[1] = 0;
    447 		if (IN6_IS_SCOPE_LINKLOCAL(&ip6.ip6_dst))
    448 			ip6.ip6_dst.s6_addr16[1] = 0;
    449 
    450 		/* Done with IPv6 header. */
    451 		m_copyback(m, 0, sizeof(struct ip6_hdr), &ip6);
    452 
    453 		/* Let's deal with the remaining headers (if any). */
    454 		if (skip - sizeof(struct ip6_hdr) > 0) {
    455 			if (m->m_len <= skip) {
    456 				ptr = malloc(skip - sizeof(struct ip6_hdr),
    457 				    M_XDATA, M_NOWAIT);
    458 				if (ptr == NULL) {
    459 					DPRINTF(("%s: failed to allocate "
    460 					    "memory for IPv6 headers\n",
    461 					    __func__));
    462 					m_freem(m);
    463 					return ENOBUFS;
    464 				}
    465 
    466 				/*
    467 				 * Copy all the protocol headers after
    468 				 * the IPv6 header.
    469 				 */
    470 				m_copydata(m, sizeof(struct ip6_hdr),
    471 				    skip - sizeof(struct ip6_hdr), ptr);
    472 				alloc = 1;
    473 			} else {
    474 				/* No need to allocate memory. */
    475 				ptr = mtod(m, unsigned char *) +
    476 				    sizeof(struct ip6_hdr);
    477 				alloc = 0;
    478 			}
    479 		} else
    480 			break;
    481 
    482 		nxt = ip6.ip6_nxt & 0xff; /* Next header type. */
    483 
    484 		for (off = 0; off < skip - sizeof(struct ip6_hdr);) {
    485 			int noff;
    486 
    487 			switch (nxt) {
    488 			case IPPROTO_HOPOPTS:
    489 			case IPPROTO_DSTOPTS:
    490 				ip6e = (struct ip6_ext *)(ptr + off);
    491 				noff = off + ((ip6e->ip6e_len + 1) << 3);
    492 
    493 				/* Sanity check. */
    494 				if (noff > skip - sizeof(struct ip6_hdr)) {
    495 					goto error6;
    496 				}
    497 
    498 				/*
    499 				 * Zero out mutable options.
    500 				 */
    501 				for (count = off + sizeof(struct ip6_ext);
    502 				     count < noff;) {
    503 					if (ptr[count] == IP6OPT_PAD1) {
    504 						count++;
    505 						continue;
    506 					}
    507 
    508 					if (count + 1 >= noff) {
    509 						goto error6;
    510 					}
    511 					ad = ptr[count + 1] + 2;
    512 
    513 					if (count + ad > noff) {
    514 						goto error6;
    515 					}
    516 
    517 					if (ptr[count] & IP6OPT_MUTABLE) {
    518 						memset(ptr + count, 0, ad);
    519 					}
    520 
    521 					count += ad;
    522 				}
    523 
    524 				if (count != noff) {
    525 					goto error6;
    526 				}
    527 
    528 				/* Advance. */
    529 				off += ((ip6e->ip6e_len + 1) << 3);
    530 				nxt = ip6e->ip6e_nxt;
    531 				break;
    532 
    533 			case IPPROTO_ROUTING:
    534 				/*
    535 				 * Always include routing headers in
    536 				 * computation.
    537 				 */
    538 				ip6e = (struct ip6_ext *)(ptr + off);
    539 				rh = (struct ip6_rthdr *)(ptr + off);
    540 				/*
    541 				 * must adjust content to make it look like
    542 				 * its final form (as seen at the final
    543 				 * destination).
    544 				 * we only know how to massage type 0 routing
    545 				 * header.
    546 				 */
    547 				if (out && rh->ip6r_type == IPV6_RTHDR_TYPE_0) {
    548 					struct ip6_rthdr0 *rh0;
    549 					struct in6_addr *addr, finaldst;
    550 					int i;
    551 
    552 					rh0 = (struct ip6_rthdr0 *)rh;
    553 					addr = (struct in6_addr *)(rh0 + 1);
    554 
    555 					for (i = 0; i < rh0->ip6r0_segleft; i++)
    556 						in6_clearscope(&addr[i]);
    557 
    558 					finaldst = addr[rh0->ip6r0_segleft - 1];
    559 					memmove(&addr[1], &addr[0],
    560 						sizeof(struct in6_addr) *
    561 						(rh0->ip6r0_segleft - 1));
    562 
    563 					m_copydata(m, 0, sizeof(ip6), &ip6);
    564 					addr[0] = ip6.ip6_dst;
    565 					ip6.ip6_dst = finaldst;
    566 					m_copyback(m, 0, sizeof(ip6), &ip6);
    567 
    568 					rh0->ip6r0_segleft = 0;
    569 				}
    570 
    571 				/* advance */
    572 				off += ((ip6e->ip6e_len + 1) << 3);
    573 				nxt = ip6e->ip6e_nxt;
    574 				break;
    575 
    576 			default:
    577 				DPRINTF(("%s: unexpected IPv6 header type %d\n",
    578 				    __func__, off));
    579 error6:
    580 				if (alloc)
    581 					free(ptr, M_XDATA);
    582 				m_freem(m);
    583 				return EINVAL;
    584 			}
    585 		}
    586 
    587 		/* Copyback and free, if we allocated. */
    588 		if (alloc) {
    589 			m_copyback(m, sizeof(struct ip6_hdr),
    590 			    skip - sizeof(struct ip6_hdr), ptr);
    591 			free(ptr, M_XDATA);
    592 		}
    593 
    594 		break;
    595 #endif /* INET6 */
    596 	}
    597 
    598 	return 0;
    599 }
    600 
    601 /*
    602  * ah_input() gets called to verify that an input packet
    603  * passes authentication.
    604  */
    605 static int
    606 ah_input(struct mbuf *m, struct secasvar *sav, int skip, int protoff)
    607 {
    608 	const struct auth_hash *ahx;
    609 	struct tdb_crypto *tc = NULL;
    610 	struct newah *ah;
    611 	int hl, rplen, authsize, error, stat = AH_STAT_HDROPS;
    612 	struct cryptodesc *crda;
    613 	struct cryptop *crp = NULL;
    614 	bool pool_used;
    615 	uint8_t nxt;
    616 
    617 	IPSEC_SPLASSERT_SOFTNET(__func__);
    618 
    619 	KASSERT(sav != NULL);
    620 	KASSERT(sav->key_auth != NULL);
    621 	KASSERT(sav->tdb_authalgxform != NULL);
    622 
    623 	/* Figure out header size. */
    624 	rplen = HDRSIZE(sav);
    625 
    626 	/* XXX don't pullup, just copy header */
    627 	IP6_EXTHDR_GET(ah, struct newah *, m, skip, rplen);
    628 	if (ah == NULL) {
    629 		DPRINTF(("%s: cannot pullup header\n", __func__));
    630 		error = ENOBUFS;
    631 		stat = AH_STAT_HDROPS;	/*XXX*/
    632 		goto bad;
    633 	}
    634 
    635 	nxt = ah->ah_nxt;
    636 
    637 	/* Check replay window, if applicable. */
    638 	if (sav->replay && !ipsec_chkreplay(ntohl(ah->ah_seq), sav)) {
    639 		char buf[IPSEC_LOGSASTRLEN];
    640 		DPRINTF(("%s: packet replay failure: %s\n", __func__,
    641 		    ipsec_logsastr(sav, buf, sizeof(buf))));
    642 		stat = AH_STAT_REPLAY;
    643 		error = ENOBUFS;
    644 		goto bad;
    645 	}
    646 
    647 	/* Verify AH header length. */
    648 	hl = ah->ah_len * sizeof(uint32_t);
    649 	ahx = sav->tdb_authalgxform;
    650 	authsize = AUTHSIZE(sav);
    651 	if (hl != authsize + rplen - sizeof(struct ah)) {
    652 		char buf[IPSEC_ADDRSTRLEN];
    653 		DPRINTF(("%s: bad authenticator length %u (expecting %lu)"
    654 			" for packet in SA %s/%08lx\n", __func__,
    655 			hl, (u_long) (authsize + rplen - sizeof(struct ah)),
    656 			ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
    657 			(u_long) ntohl(sav->spi)));
    658 		stat = AH_STAT_BADAUTHL;
    659 		error = EACCES;
    660 		goto bad;
    661 	}
    662 	if (skip + authsize + rplen > m->m_pkthdr.len) {
    663 		char buf[IPSEC_ADDRSTRLEN];
    664 		DPRINTF(("%s: bad mbuf length %u (expecting >= %lu)"
    665 			" for packet in SA %s/%08lx\n", __func__,
    666 			m->m_pkthdr.len, (u_long)(skip + authsize + rplen),
    667 			ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
    668 			(u_long) ntohl(sav->spi)));
    669 		stat = AH_STAT_BADAUTHL;
    670 		error = EACCES;
    671 		goto bad;
    672 	}
    673 
    674 	AH_STATADD(AH_STAT_IBYTES, m->m_pkthdr.len - skip - hl);
    675 
    676 	/* Get crypto descriptors. */
    677 	crp = crypto_getreq(1);
    678 	if (crp == NULL) {
    679 		DPRINTF(("%s: failed to acquire crypto descriptor\n", __func__));
    680 		stat = AH_STAT_CRYPTO;
    681 		error = ENOBUFS;
    682 		goto bad;
    683 	}
    684 
    685 	crda = crp->crp_desc;
    686 	KASSERT(crda != NULL);
    687 
    688 	crda->crd_skip = 0;
    689 	crda->crd_len = m->m_pkthdr.len;
    690 	crda->crd_inject = skip + rplen;
    691 
    692 	/* Authentication operation. */
    693 	crda->crd_alg = ahx->type;
    694 	crda->crd_key = _KEYBUF(sav->key_auth);
    695 	crda->crd_klen = _KEYBITS(sav->key_auth);
    696 
    697 	/* Allocate IPsec-specific opaque crypto info. */
    698 	size_t size = sizeof(*tc);
    699 	size_t extra = skip + rplen + authsize;
    700 	size += extra;
    701 
    702 	if (__predict_true(size <= ah_pool_item_size)) {
    703 		tc = pool_cache_get(ah_tdb_crypto_pool_cache, PR_NOWAIT);
    704 		pool_used = true;
    705 	} else {
    706 		/* size can exceed on IPv6 packets with large options.  */
    707 		tc = kmem_intr_zalloc(size, KM_NOSLEEP);
    708 		pool_used = false;
    709 	}
    710 	if (tc == NULL) {
    711 		DPRINTF(("%s: failed to allocate tdb_crypto\n", __func__));
    712 		stat = AH_STAT_CRYPTO;
    713 		error = ENOBUFS;
    714 		goto bad;
    715 	}
    716 
    717 	error = m_makewritable(&m, 0, extra, M_NOWAIT);
    718 	if (error) {
    719 		DPRINTF(("%s: failed to m_makewritable\n", __func__));
    720 		goto bad;
    721 	}
    722 
    723 	/*
    724 	 * Save the authenticator, the skipped portion of the packet,
    725 	 * and the AH header.
    726 	 */
    727 	m_copydata(m, 0, extra, (tc + 1));
    728 	/* Zeroize the authenticator on the packet. */
    729 	m_copyback(m, skip + rplen, authsize, ipseczeroes);
    730 
    731 	/* "Massage" the packet headers for crypto processing. */
    732 	error = ah_massage_headers(&m, sav->sah->saidx.dst.sa.sa_family,
    733 	    skip, ahx->type, 0);
    734 	if (error != 0) {
    735 		/* NB: mbuf is free'd by ah_massage_headers */
    736 		m = NULL;
    737 		goto bad;
    738 	}
    739 
    740     {
    741 	int s = pserialize_read_enter();
    742 
    743 	/*
    744 	 * Take another reference to the SA for opencrypto callback.
    745 	 */
    746 	if (__predict_false(sav->state == SADB_SASTATE_DEAD)) {
    747 		pserialize_read_exit(s);
    748 		stat = AH_STAT_NOTDB;
    749 		error = ENOENT;
    750 		goto bad;
    751 	}
    752 	KEY_SA_REF(sav);
    753 	pserialize_read_exit(s);
    754     }
    755 
    756 	/* Crypto operation descriptor. */
    757 	crp->crp_ilen = m->m_pkthdr.len; /* Total input length. */
    758 	crp->crp_flags = CRYPTO_F_IMBUF;
    759 	crp->crp_buf = m;
    760 	crp->crp_callback = ah_input_cb;
    761 	crp->crp_sid = sav->tdb_cryptoid;
    762 	crp->crp_opaque = tc;
    763 
    764 	/* These are passed as-is to the callback. */
    765 	tc->tc_spi = sav->spi;
    766 	tc->tc_dst = sav->sah->saidx.dst;
    767 	tc->tc_proto = sav->sah->saidx.proto;
    768 	tc->tc_nxt = nxt;
    769 	tc->tc_protoff = protoff;
    770 	tc->tc_skip = skip;
    771 	tc->tc_sav = sav;
    772 
    773 	DPRINTF(("%s: hash over %d bytes, skip %d: "
    774 		 "crda len %d skip %d inject %d\n", __func__,
    775 		 crp->crp_ilen, tc->tc_skip,
    776 		 crda->crd_len, crda->crd_skip, crda->crd_inject));
    777 
    778 	return crypto_dispatch(crp);
    779 
    780 bad:
    781 	if (tc != NULL) {
    782 		if (__predict_true(pool_used))
    783 			pool_cache_put(ah_tdb_crypto_pool_cache, tc);
    784 		else
    785 			kmem_intr_free(tc, size);
    786 	}
    787 	if (crp != NULL)
    788 		crypto_freereq(crp);
    789 	if (m != NULL)
    790 		m_freem(m);
    791 	AH_STATINC(stat);
    792 	return error;
    793 }
    794 
    795 #ifdef INET6
    796 #define	IPSEC_COMMON_INPUT_CB(m, sav, skip, protoff) do {		     \
    797 	if (saidx->dst.sa.sa_family == AF_INET6) {			     \
    798 		error = ipsec6_common_input_cb(m, sav, skip, protoff);	     \
    799 	} else {							     \
    800 		error = ipsec4_common_input_cb(m, sav, skip, protoff);	     \
    801 	}								     \
    802 } while (0)
    803 #else
    804 #define	IPSEC_COMMON_INPUT_CB(m, sav, skip, protoff)			     \
    805 	(error = ipsec4_common_input_cb(m, sav, skip, protoff))
    806 #endif
    807 
    808 /*
    809  * AH input callback from the crypto driver.
    810  */
    811 static int
    812 ah_input_cb(struct cryptop *crp)
    813 {
    814 	char buf[IPSEC_ADDRSTRLEN];
    815 	int rplen, error, skip, protoff;
    816 	unsigned char calc[AH_ALEN_MAX];
    817 	struct mbuf *m;
    818 	struct tdb_crypto *tc;
    819 	struct secasvar *sav;
    820 	struct secasindex *saidx;
    821 	uint8_t nxt;
    822 	char *ptr;
    823 	int authsize;
    824 	uint16_t dport;
    825 	uint16_t sport;
    826 	bool pool_used;
    827 	size_t size;
    828 	IPSEC_DECLARE_LOCK_VARIABLE;
    829 
    830 	KASSERT(crp->crp_opaque != NULL);
    831 	tc = crp->crp_opaque;
    832 	skip = tc->tc_skip;
    833 	nxt = tc->tc_nxt;
    834 	protoff = tc->tc_protoff;
    835 	m = crp->crp_buf;
    836 
    837 
    838 	/* find the source port for NAT-T */
    839 	nat_t_ports_get(m, &dport, &sport);
    840 
    841 	IPSEC_ACQUIRE_GLOBAL_LOCKS();
    842 
    843 	sav = tc->tc_sav;
    844 	saidx = &sav->sah->saidx;
    845 	KASSERTMSG(saidx->dst.sa.sa_family == AF_INET ||
    846 	    saidx->dst.sa.sa_family == AF_INET6,
    847 	    "unexpected protocol family %u", saidx->dst.sa.sa_family);
    848 
    849 	/* Figure out header size. */
    850 	rplen = HDRSIZE(sav);
    851 	authsize = AUTHSIZE(sav);
    852 
    853 	size = sizeof(*tc) + skip + rplen + authsize;
    854 	if (__predict_true(size <= ah_pool_item_size))
    855 		pool_used = true;
    856 	else
    857 		pool_used = false;
    858 
    859 	/* Check for crypto errors. */
    860 	if (crp->crp_etype) {
    861 		if (sav->tdb_cryptoid != 0)
    862 			sav->tdb_cryptoid = crp->crp_sid;
    863 
    864 		if (crp->crp_etype == EAGAIN) {
    865 			IPSEC_RELEASE_GLOBAL_LOCKS();
    866 			return crypto_dispatch(crp);
    867 		}
    868 
    869 		AH_STATINC(AH_STAT_NOXFORM);
    870 		DPRINTF(("%s: crypto error %d\n", __func__, crp->crp_etype));
    871 		error = crp->crp_etype;
    872 		goto bad;
    873 	} else {
    874 		AH_STATINC(AH_STAT_HIST + ah_stats[sav->alg_auth]);
    875 		crypto_freereq(crp);		/* No longer needed. */
    876 		crp = NULL;
    877 	}
    878 
    879 	if (ipsec_debug)
    880 		memset(calc, 0, sizeof(calc));
    881 
    882 	/* Copy authenticator off the packet. */
    883 	m_copydata(m, skip + rplen, authsize, calc);
    884 
    885 	ptr = (char *)(tc + 1);
    886 	const uint8_t *pppp = ptr + skip + rplen;
    887 
    888 	/* Verify authenticator. */
    889 	if (!consttime_memequal(pppp, calc, authsize)) {
    890 		DPRINTF(("%s: authentication hash mismatch " \
    891 		    "over %d bytes " \
    892 		    "for packet in SA %s/%08lx:\n" \
    893 	    "%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x, " \
    894 	    "%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x\n",
    895 		    __func__, authsize,
    896 		    ipsec_address(&saidx->dst, buf, sizeof(buf)),
    897 		    (u_long) ntohl(sav->spi),
    898 			 calc[0], calc[1], calc[2], calc[3],
    899 			 calc[4], calc[5], calc[6], calc[7],
    900 			 calc[8], calc[9], calc[10], calc[11],
    901 			 pppp[0], pppp[1], pppp[2], pppp[3],
    902 			 pppp[4], pppp[5], pppp[6], pppp[7],
    903 			 pppp[8], pppp[9], pppp[10], pppp[11]
    904 			 ));
    905 		AH_STATINC(AH_STAT_BADAUTH);
    906 		error = EACCES;
    907 		goto bad;
    908 	}
    909 
    910 	/* Fix the Next Protocol field. */
    911 	ptr[protoff] = nxt;
    912 
    913 	/* Copyback the saved (uncooked) network headers. */
    914 	m_copyback(m, 0, skip, ptr);
    915 
    916 	if (__predict_true(pool_used))
    917 		pool_cache_put(ah_tdb_crypto_pool_cache, tc);
    918 	else
    919 		kmem_intr_free(tc, size);
    920 	tc = NULL;
    921 
    922 	/*
    923 	 * Header is now authenticated.
    924 	 */
    925 	m->m_flags |= M_AUTHIPHDR|M_AUTHIPDGM;
    926 
    927 	/*
    928 	 * Update replay sequence number, if appropriate.
    929 	 */
    930 	if (sav->replay) {
    931 		uint32_t seq;
    932 
    933 		m_copydata(m, skip + offsetof(struct newah, ah_seq),
    934 		    sizeof(seq), &seq);
    935 		if (ipsec_updatereplay(ntohl(seq), sav)) {
    936 			AH_STATINC(AH_STAT_REPLAY);
    937 			error = ENOBUFS; /* XXX as above */
    938 			goto bad;
    939 		}
    940 	}
    941 
    942 	/*
    943 	 * Remove the AH header and authenticator from the mbuf.
    944 	 */
    945 	error = m_striphdr(m, skip, rplen + authsize);
    946 	if (error) {
    947 		DPRINTF(("%s: mangled mbuf chain for SA %s/%08lx\n", __func__,
    948 		    ipsec_address(&saidx->dst, buf, sizeof(buf)),
    949 		    (u_long) ntohl(sav->spi)));
    950 
    951 		AH_STATINC(AH_STAT_HDROPS);
    952 		goto bad;
    953 	}
    954 
    955 	IPSEC_COMMON_INPUT_CB(m, sav, skip, protoff);
    956 
    957 	KEY_SA_UNREF(&sav);
    958 	IPSEC_RELEASE_GLOBAL_LOCKS();
    959 	return error;
    960 
    961 bad:
    962 	if (sav)
    963 		KEY_SA_UNREF(&sav);
    964 	IPSEC_RELEASE_GLOBAL_LOCKS();
    965 	if (m != NULL)
    966 		m_freem(m);
    967 	if (tc != NULL) {
    968 		if (pool_used)
    969 			pool_cache_put(ah_tdb_crypto_pool_cache, tc);
    970 		else
    971 			kmem_intr_free(tc, size);
    972 	}
    973 	if (crp != NULL)
    974 		crypto_freereq(crp);
    975 	return error;
    976 }
    977 
    978 /*
    979  * AH output routine, called by ipsec[46]_process_packet().
    980  */
    981 static int
    982 ah_output(struct mbuf *m, const struct ipsecrequest *isr, struct secasvar *sav,
    983     struct mbuf **mp, int skip, int protoff)
    984 {
    985 	char buf[IPSEC_ADDRSTRLEN];
    986 	const struct auth_hash *ahx;
    987 	struct cryptodesc *crda;
    988 	struct tdb_crypto *tc;
    989 	struct mbuf *mi;
    990 	struct cryptop *crp;
    991 	uint16_t iplen;
    992 	int error, rplen, authsize, maxpacketsize, roff;
    993 	uint8_t prot;
    994 	struct newah *ah;
    995 	size_t ipoffs;
    996 	bool pool_used;
    997 
    998 	IPSEC_SPLASSERT_SOFTNET(__func__);
    999 
   1000 	KASSERT(sav != NULL);
   1001 	KASSERT(sav->tdb_authalgxform != NULL);
   1002 	ahx = sav->tdb_authalgxform;
   1003 
   1004 	AH_STATINC(AH_STAT_OUTPUT);
   1005 
   1006 	/* Figure out header size. */
   1007 	rplen = HDRSIZE(sav);
   1008 
   1009 	/* Check for maximum packet size violations. */
   1010 	switch (sav->sah->saidx.dst.sa.sa_family) {
   1011 #ifdef INET
   1012 	case AF_INET:
   1013 		maxpacketsize = IP_MAXPACKET;
   1014 		ipoffs = offsetof(struct ip, ip_len);
   1015 		break;
   1016 #endif
   1017 #ifdef INET6
   1018 	case AF_INET6:
   1019 		maxpacketsize = IPV6_MAXPACKET;
   1020 		ipoffs = offsetof(struct ip6_hdr, ip6_plen);
   1021 		break;
   1022 #endif
   1023 	default:
   1024 		DPRINTF(("%s: unknown/unsupported protocol "
   1025 		    "family %u, SA %s/%08lx\n", __func__,
   1026 		    sav->sah->saidx.dst.sa.sa_family,
   1027 		    ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
   1028 		    (u_long) ntohl(sav->spi)));
   1029 		AH_STATINC(AH_STAT_NOPF);
   1030 		error = EPFNOSUPPORT;
   1031 		goto bad;
   1032 	}
   1033 	authsize = AUTHSIZE(sav);
   1034 	if (rplen + authsize + m->m_pkthdr.len > maxpacketsize) {
   1035 		DPRINTF(("%s: packet in SA %s/%08lx got too big "
   1036 		    "(len %u, max len %u)\n", __func__,
   1037 		    ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
   1038 		    (u_long) ntohl(sav->spi),
   1039 		    rplen + authsize + m->m_pkthdr.len, maxpacketsize));
   1040 		AH_STATINC(AH_STAT_TOOBIG);
   1041 		error = EMSGSIZE;
   1042 		goto bad;
   1043 	}
   1044 
   1045 	/* Update the counters. */
   1046 	AH_STATADD(AH_STAT_OBYTES, m->m_pkthdr.len - skip);
   1047 
   1048 	m = m_clone(m);
   1049 	if (m == NULL) {
   1050 		DPRINTF(("%s: cannot clone mbuf chain, SA %s/%08lx\n", __func__,
   1051 		    ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
   1052 		    (u_long) ntohl(sav->spi)));
   1053 		AH_STATINC(AH_STAT_HDROPS);
   1054 		error = ENOBUFS;
   1055 		goto bad;
   1056 	}
   1057 
   1058 	/* Inject AH header. */
   1059 	mi = m_makespace(m, skip, rplen + authsize, &roff);
   1060 	if (mi == NULL) {
   1061 		DPRINTF(("%s: failed to inject %u byte AH header for SA "
   1062 		    "%s/%08lx\n", __func__,
   1063 		    rplen + authsize,
   1064 		    ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
   1065 		    (u_long) ntohl(sav->spi)));
   1066 		AH_STATINC(AH_STAT_HDROPS);
   1067 		error = ENOBUFS;
   1068 		goto bad;
   1069 	}
   1070 
   1071 	/*
   1072 	 * The AH header is guaranteed by m_makespace() to be in
   1073 	 * contiguous memory, at roff bytes offset into the returned mbuf.
   1074 	 */
   1075 	ah = (struct newah *)(mtod(mi, char *) + roff);
   1076 
   1077 	/* Initialize the AH header. */
   1078 	m_copydata(m, protoff, sizeof(uint8_t), &ah->ah_nxt);
   1079 	ah->ah_len = (rplen + authsize - sizeof(struct ah)) / sizeof(uint32_t);
   1080 	ah->ah_reserve = 0;
   1081 	ah->ah_spi = sav->spi;
   1082 
   1083 	/* Zeroize authenticator. */
   1084 	m_copyback(m, skip + rplen, authsize, ipseczeroes);
   1085 
   1086 	/* Insert packet replay counter, as requested.  */
   1087 	if (sav->replay) {
   1088 		if (sav->replay->count == ~0 &&
   1089 		    (sav->flags & SADB_X_EXT_CYCSEQ) == 0) {
   1090 			DPRINTF(("%s: replay counter wrapped for SA %s/%08lx\n",
   1091 			    __func__, ipsec_address(&sav->sah->saidx.dst, buf,
   1092 			    sizeof(buf)), (u_long) ntohl(sav->spi)));
   1093 			AH_STATINC(AH_STAT_WRAP);
   1094 			error = EINVAL;
   1095 			goto bad;
   1096 		}
   1097 #ifdef IPSEC_DEBUG
   1098 		/* Emulate replay attack when ipsec_replay is TRUE. */
   1099 		if (!ipsec_replay)
   1100 #endif
   1101 			sav->replay->count++;
   1102 		ah->ah_seq = htonl(sav->replay->count);
   1103 	}
   1104 
   1105 	/* Get crypto descriptors. */
   1106 	crp = crypto_getreq(1);
   1107 	if (crp == NULL) {
   1108 		DPRINTF(("%s: failed to acquire crypto descriptors\n",
   1109 		    __func__));
   1110 		AH_STATINC(AH_STAT_CRYPTO);
   1111 		error = ENOBUFS;
   1112 		goto bad;
   1113 	}
   1114 
   1115 	crda = crp->crp_desc;
   1116 
   1117 	crda->crd_skip = 0;
   1118 	crda->crd_inject = skip + rplen;
   1119 	crda->crd_len = m->m_pkthdr.len;
   1120 
   1121 	/* Authentication operation. */
   1122 	crda->crd_alg = ahx->type;
   1123 	crda->crd_key = _KEYBUF(sav->key_auth);
   1124 	crda->crd_klen = _KEYBITS(sav->key_auth);
   1125 
   1126 	/* Allocate IPsec-specific opaque crypto info. */
   1127 	size_t size = sizeof(*tc) + skip;
   1128 
   1129 	if (__predict_true(size <= ah_pool_item_size)) {
   1130 		tc = pool_cache_get(ah_tdb_crypto_pool_cache, PR_NOWAIT);
   1131 		pool_used = true;
   1132 	} else {
   1133 		/* size can exceed on IPv6 packets with large options.  */
   1134 		tc = kmem_intr_zalloc(size, KM_NOSLEEP);
   1135 		pool_used = false;
   1136 	}
   1137 	if (tc == NULL) {
   1138 		DPRINTF(("%s: failed to allocate tdb_crypto\n", __func__));
   1139 		AH_STATINC(AH_STAT_CRYPTO);
   1140 		error = ENOBUFS;
   1141 		goto bad_crp;
   1142 	}
   1143 
   1144 	uint8_t *pext = (char *)(tc + 1);
   1145 	/* Save the skipped portion of the packet. */
   1146 	m_copydata(m, 0, skip, pext);
   1147 
   1148 	/*
   1149 	 * Fix IP header length on the header used for
   1150 	 * authentication. We don't need to fix the original
   1151 	 * header length as it will be fixed by our caller.
   1152 	 */
   1153 	memcpy(&iplen, pext + ipoffs, sizeof(iplen));
   1154 	iplen = htons(ntohs(iplen) + rplen + authsize);
   1155 	m_copyback(m, ipoffs, sizeof(iplen), &iplen);
   1156 
   1157 	/* Fix the Next Header field in saved header. */
   1158 	pext[protoff] = IPPROTO_AH;
   1159 
   1160 	/* Update the Next Protocol field in the IP header. */
   1161 	prot = IPPROTO_AH;
   1162 	m_copyback(m, protoff, sizeof(prot), &prot);
   1163 
   1164 	/* "Massage" the packet headers for crypto processing. */
   1165 	error = ah_massage_headers(&m, sav->sah->saidx.dst.sa.sa_family,
   1166 	    skip, ahx->type, 1);
   1167 	if (error != 0) {
   1168 		m = NULL;	/* mbuf was free'd by ah_massage_headers. */
   1169 		goto bad_tc;
   1170 	}
   1171 
   1172     {
   1173 	int s = pserialize_read_enter();
   1174 
   1175 	/*
   1176 	 * Take another reference to the SP and the SA for opencrypto callback.
   1177 	 */
   1178 	if (__predict_false(isr->sp->state == IPSEC_SPSTATE_DEAD ||
   1179 	    sav->state == SADB_SASTATE_DEAD)) {
   1180 		pserialize_read_exit(s);
   1181 		AH_STATINC(AH_STAT_NOTDB);
   1182 		error = ENOENT;
   1183 		goto bad_tc;
   1184 	}
   1185 	KEY_SP_REF(isr->sp);
   1186 	KEY_SA_REF(sav);
   1187 	pserialize_read_exit(s);
   1188     }
   1189 
   1190 	/* Crypto operation descriptor. */
   1191 	crp->crp_ilen = m->m_pkthdr.len; /* Total input length. */
   1192 	crp->crp_flags = CRYPTO_F_IMBUF;
   1193 	crp->crp_buf = m;
   1194 	crp->crp_callback = ah_output_cb;
   1195 	crp->crp_sid = sav->tdb_cryptoid;
   1196 	crp->crp_opaque = tc;
   1197 
   1198 	/* These are passed as-is to the callback. */
   1199 	tc->tc_isr = isr;
   1200 	tc->tc_spi = sav->spi;
   1201 	tc->tc_dst = sav->sah->saidx.dst;
   1202 	tc->tc_proto = sav->sah->saidx.proto;
   1203 	tc->tc_skip = skip;
   1204 	tc->tc_protoff = protoff;
   1205 	tc->tc_sav = sav;
   1206 
   1207 	return crypto_dispatch(crp);
   1208 
   1209 bad_tc:
   1210 	if (__predict_true(pool_used))
   1211 		pool_cache_put(ah_tdb_crypto_pool_cache, tc);
   1212 	else
   1213 		kmem_intr_free(tc, size);
   1214 bad_crp:
   1215 	crypto_freereq(crp);
   1216 bad:
   1217 	if (m)
   1218 		m_freem(m);
   1219 	return (error);
   1220 }
   1221 
   1222 /*
   1223  * AH output callback from the crypto driver.
   1224  */
   1225 static int
   1226 ah_output_cb(struct cryptop *crp)
   1227 {
   1228 	int skip, error;
   1229 	struct tdb_crypto *tc;
   1230 	const struct ipsecrequest *isr;
   1231 	struct secasvar *sav;
   1232 	struct mbuf *m;
   1233 	void *ptr;
   1234 	int err;
   1235 	size_t size;
   1236 	bool pool_used;
   1237 	IPSEC_DECLARE_LOCK_VARIABLE;
   1238 
   1239 	KASSERT(crp->crp_opaque != NULL);
   1240 	tc = crp->crp_opaque;
   1241 	skip = tc->tc_skip;
   1242 	ptr = (tc + 1);
   1243 	m = crp->crp_buf;
   1244 	size = sizeof(*tc) + skip;
   1245 	pool_used = size <= ah_pool_item_size;
   1246 
   1247 	IPSEC_ACQUIRE_GLOBAL_LOCKS();
   1248 
   1249 	isr = tc->tc_isr;
   1250 	sav = tc->tc_sav;
   1251 
   1252 	/* Check for crypto errors. */
   1253 	if (crp->crp_etype) {
   1254 		if (sav->tdb_cryptoid != 0)
   1255 			sav->tdb_cryptoid = crp->crp_sid;
   1256 
   1257 		if (crp->crp_etype == EAGAIN) {
   1258 			IPSEC_RELEASE_GLOBAL_LOCKS();
   1259 			return crypto_dispatch(crp);
   1260 		}
   1261 
   1262 		AH_STATINC(AH_STAT_NOXFORM);
   1263 		DPRINTF(("%s: crypto error %d\n", __func__, crp->crp_etype));
   1264 		error = crp->crp_etype;
   1265 		goto bad;
   1266 	}
   1267 
   1268 	AH_STATINC(AH_STAT_HIST + ah_stats[sav->alg_auth]);
   1269 
   1270 	/*
   1271 	 * Copy original headers (with the new protocol number) back
   1272 	 * in place.
   1273 	 */
   1274 	m_copyback(m, 0, skip, ptr);
   1275 
   1276 	/* No longer needed. */
   1277 	if (__predict_true(pool_used))
   1278 		pool_cache_put(ah_tdb_crypto_pool_cache, tc);
   1279 	else
   1280 		kmem_intr_free(tc, size);
   1281 	crypto_freereq(crp);
   1282 
   1283 #ifdef IPSEC_DEBUG
   1284 	/* Emulate man-in-the-middle attack when ipsec_integrity is TRUE. */
   1285 	if (ipsec_integrity) {
   1286 		int alen;
   1287 
   1288 		/*
   1289 		 * Corrupt HMAC if we want to test integrity verification of
   1290 		 * the other side.
   1291 		 */
   1292 		alen = AUTHSIZE(sav);
   1293 		m_copyback(m, m->m_pkthdr.len - alen, alen, ipseczeroes);
   1294 	}
   1295 #endif
   1296 
   1297 	/* NB: m is reclaimed by ipsec_process_done. */
   1298 	err = ipsec_process_done(m, isr, sav);
   1299 	KEY_SA_UNREF(&sav);
   1300 	KEY_SP_UNREF(&isr->sp);
   1301 	IPSEC_RELEASE_GLOBAL_LOCKS();
   1302 	return err;
   1303 bad:
   1304 	if (sav)
   1305 		KEY_SA_UNREF(&sav);
   1306 	KEY_SP_UNREF(&isr->sp);
   1307 	IPSEC_RELEASE_GLOBAL_LOCKS();
   1308 	if (m)
   1309 		m_freem(m);
   1310 	if (__predict_true(pool_used))
   1311 		pool_cache_put(ah_tdb_crypto_pool_cache, tc);
   1312 	else
   1313 		kmem_intr_free(tc, size);
   1314 	crypto_freereq(crp);
   1315 	return error;
   1316 }
   1317 
   1318 static struct xformsw ah_xformsw = {
   1319 	.xf_type	= XF_AH,
   1320 	.xf_flags	= XFT_AUTH,
   1321 	.xf_name	= "IPsec AH",
   1322 	.xf_init	= ah_init,
   1323 	.xf_zeroize	= ah_zeroize,
   1324 	.xf_input	= ah_input,
   1325 	.xf_output	= ah_output,
   1326 	.xf_next	= NULL,
   1327 };
   1328 
   1329 void
   1330 ah_attach(void)
   1331 {
   1332 	ahstat_percpu = percpu_alloc(sizeof(uint64_t) * AH_NSTATS);
   1333 
   1334 #define MAXAUTHSIZE(name)						\
   1335 	if ((auth_hash_ ## name).authsize > ah_max_authsize)		\
   1336 		ah_max_authsize = (auth_hash_ ## name).authsize
   1337 
   1338 	ah_max_authsize = 0;
   1339 	MAXAUTHSIZE(null);
   1340 	MAXAUTHSIZE(md5);
   1341 	MAXAUTHSIZE(sha1);
   1342 	MAXAUTHSIZE(key_md5);
   1343 	MAXAUTHSIZE(key_sha1);
   1344 	MAXAUTHSIZE(hmac_md5);
   1345 	MAXAUTHSIZE(hmac_sha1);
   1346 	MAXAUTHSIZE(hmac_ripemd_160);
   1347 	MAXAUTHSIZE(hmac_md5_96);
   1348 	MAXAUTHSIZE(hmac_sha1_96);
   1349 	MAXAUTHSIZE(hmac_ripemd_160_96);
   1350 	MAXAUTHSIZE(hmac_sha2_256);
   1351 	MAXAUTHSIZE(hmac_sha2_384);
   1352 	MAXAUTHSIZE(hmac_sha2_512);
   1353 	MAXAUTHSIZE(aes_xcbc_mac_96);
   1354 	MAXAUTHSIZE(gmac_aes_128);
   1355 	MAXAUTHSIZE(gmac_aes_192);
   1356 	MAXAUTHSIZE(gmac_aes_256);
   1357 	IPSECLOG(LOG_DEBUG, "ah_max_authsize=%d\n", ah_max_authsize);
   1358 
   1359 #undef MAXAUTHSIZE
   1360 
   1361 	ah_pool_item_size = sizeof(struct tdb_crypto) +
   1362 	    sizeof(struct ip) + MAX_IPOPTLEN +
   1363 	    sizeof(struct ah) + sizeof(uint32_t) + ah_max_authsize;
   1364 	ah_tdb_crypto_pool_cache = pool_cache_init(ah_pool_item_size,
   1365 	    coherency_unit, 0, 0, "ah_tdb_crypto", NULL, IPL_SOFTNET,
   1366 	    NULL, NULL, NULL);
   1367 
   1368 	xform_register(&ah_xformsw);
   1369 }
   1370