Home | History | Annotate | Line # | Download | only in netipsec
xform_ah.c revision 1.88
      1 /*	$NetBSD: xform_ah.c,v 1.88 2018/04/13 09:34:20 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.88 2018/04/13 09:34:20 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 			/* XXX XXX: What are we trying to achieve here? */
    314 			uint16_t inlen = ntohs(ip->ip_len);
    315 			ip->ip_len = htons(inlen);
    316 		}
    317 
    318 		if (alg == CRYPTO_MD5_KPDK || alg == CRYPTO_SHA1_KPDK)
    319 			ip->ip_off &= htons(IP_DF);
    320 		else
    321 			ip->ip_off = 0;
    322 
    323 		ptr = mtod(m, unsigned char *);
    324 
    325 		/* IPv4 option processing */
    326 		for (off = sizeof(struct ip); off < skip;) {
    327 			if (ptr[off] == IPOPT_EOL || ptr[off] == IPOPT_NOP ||
    328 			    off + 1 < skip)
    329 				;
    330 			else {
    331 				DPRINTF(("%s: illegal IPv4 option length for "
    332 				    "option %d\n", __func__, ptr[off]));
    333 
    334 				m_freem(m);
    335 				return EINVAL;
    336 			}
    337 
    338 			switch (ptr[off]) {
    339 			case IPOPT_EOL:
    340 				off = skip;  /* End the loop. */
    341 				break;
    342 
    343 			case IPOPT_NOP:
    344 				off++;
    345 				break;
    346 
    347 			case IPOPT_SECURITY:	/* 0x82 */
    348 			case 0x85:	/* Extended security. */
    349 			case 0x86:	/* Commercial security. */
    350 			case 0x94:	/* Router alert */
    351 			case 0x95:	/* RFC1770 */
    352 				/* Sanity check for option length. */
    353 				if (ptr[off + 1] < 2) {
    354 					DPRINTF(("%s: illegal IPv4 option "
    355 					    "length for option %d\n", __func__,
    356 					    ptr[off]));
    357 
    358 					m_freem(m);
    359 					return EINVAL;
    360 				}
    361 
    362 				off += ptr[off + 1];
    363 				break;
    364 
    365 			case IPOPT_LSRR:
    366 			case IPOPT_SSRR:
    367 				/* Sanity check for option length. */
    368 				if (ptr[off + 1] < 2) {
    369 					DPRINTF(("%s: illegal IPv4 option "
    370 					    "length for option %d\n", __func__,
    371 					    ptr[off]));
    372 
    373 					m_freem(m);
    374 					return EINVAL;
    375 				}
    376 
    377 				/*
    378 				 * On output, if we have either of the
    379 				 * source routing options, we should
    380 				 * swap the destination address of the
    381 				 * IP header with the last address
    382 				 * specified in the option, as that is
    383 				 * what the destination's IP header
    384 				 * will look like.
    385 				 */
    386 				if (out)
    387 					memcpy(&ip->ip_dst,
    388 					    ptr + off + ptr[off + 1] -
    389 					    sizeof(struct in_addr),
    390 					    sizeof(struct in_addr));
    391 
    392 				/* Fall through */
    393 			default:
    394 				/* Sanity check for option length. */
    395 				if (ptr[off + 1] < 2) {
    396 					DPRINTF(("%s: illegal IPv4 option "
    397 					    "length for option %d\n", __func__,
    398 					    ptr[off]));
    399 					m_freem(m);
    400 					return EINVAL;
    401 				}
    402 
    403 				/* Zeroize all other options. */
    404 				count = ptr[off + 1];
    405 				memcpy(ptr + off, ipseczeroes, count);
    406 				off += count;
    407 				break;
    408 			}
    409 
    410 			/* Sanity check. */
    411 			if (off > skip)	{
    412 				DPRINTF(("%s: malformed IPv4 options header\n",
    413 					__func__));
    414 				m_freem(m);
    415 				return EINVAL;
    416 			}
    417 		}
    418 
    419 		break;
    420 #endif /* INET */
    421 
    422 #ifdef INET6
    423 	case AF_INET6:  /* Ugly... */
    424 		/* Copy and "cook" the IPv6 header. */
    425 		m_copydata(m, 0, sizeof(ip6), &ip6);
    426 
    427 		/* We don't do IPv6 Jumbograms. */
    428 		if (ip6.ip6_plen == 0) {
    429 			DPRINTF(("%s: unsupported IPv6 jumbogram\n", __func__));
    430 			m_freem(m);
    431 			return EMSGSIZE;
    432 		}
    433 
    434 		ip6.ip6_flow = 0;
    435 		ip6.ip6_hlim = 0;
    436 		ip6.ip6_vfc &= ~IPV6_VERSION_MASK;
    437 		ip6.ip6_vfc |= IPV6_VERSION;
    438 
    439 		/* Scoped address handling. */
    440 		if (IN6_IS_SCOPE_LINKLOCAL(&ip6.ip6_src))
    441 			ip6.ip6_src.s6_addr16[1] = 0;
    442 		if (IN6_IS_SCOPE_LINKLOCAL(&ip6.ip6_dst))
    443 			ip6.ip6_dst.s6_addr16[1] = 0;
    444 
    445 		/* Done with IPv6 header. */
    446 		m_copyback(m, 0, sizeof(struct ip6_hdr), &ip6);
    447 
    448 		/* Let's deal with the remaining headers (if any). */
    449 		if (skip - sizeof(struct ip6_hdr) > 0) {
    450 			if (m->m_len <= skip) {
    451 				ptr = malloc(skip - sizeof(struct ip6_hdr),
    452 				    M_XDATA, M_NOWAIT);
    453 				if (ptr == NULL) {
    454 					DPRINTF(("%s: failed to allocate "
    455 					    "memory for IPv6 headers\n",
    456 					    __func__));
    457 					m_freem(m);
    458 					return ENOBUFS;
    459 				}
    460 
    461 				/*
    462 				 * Copy all the protocol headers after
    463 				 * the IPv6 header.
    464 				 */
    465 				m_copydata(m, sizeof(struct ip6_hdr),
    466 				    skip - sizeof(struct ip6_hdr), ptr);
    467 				alloc = 1;
    468 			} else {
    469 				/* No need to allocate memory. */
    470 				ptr = mtod(m, unsigned char *) +
    471 				    sizeof(struct ip6_hdr);
    472 				alloc = 0;
    473 			}
    474 		} else
    475 			break;
    476 
    477 		nxt = ip6.ip6_nxt & 0xff; /* Next header type. */
    478 
    479 		for (off = 0; off < skip - sizeof(struct ip6_hdr);) {
    480 			int noff;
    481 
    482 			switch (nxt) {
    483 			case IPPROTO_HOPOPTS:
    484 			case IPPROTO_DSTOPTS:
    485 				ip6e = (struct ip6_ext *)(ptr + off);
    486 				noff = off + ((ip6e->ip6e_len + 1) << 3);
    487 
    488 				/* Sanity check. */
    489 				if (noff > skip - sizeof(struct ip6_hdr)) {
    490 					goto error6;
    491 				}
    492 
    493 				/*
    494 				 * Zero out mutable options.
    495 				 */
    496 				for (count = off + sizeof(struct ip6_ext);
    497 				     count < noff;) {
    498 					if (ptr[count] == IP6OPT_PAD1) {
    499 						count++;
    500 						continue;
    501 					}
    502 
    503 					if (count + 1 >= noff) {
    504 						goto error6;
    505 					}
    506 					ad = ptr[count + 1] + 2;
    507 
    508 					if (count + ad > noff) {
    509 						goto error6;
    510 					}
    511 
    512 					if (ptr[count] & IP6OPT_MUTABLE) {
    513 						memset(ptr + count, 0, ad);
    514 					}
    515 
    516 					count += ad;
    517 				}
    518 
    519 				if (count != noff) {
    520 					goto error6;
    521 				}
    522 
    523 				/* Advance. */
    524 				off += ((ip6e->ip6e_len + 1) << 3);
    525 				nxt = ip6e->ip6e_nxt;
    526 				break;
    527 
    528 			case IPPROTO_ROUTING:
    529 				/*
    530 				 * Always include routing headers in
    531 				 * computation.
    532 				 */
    533 				ip6e = (struct ip6_ext *)(ptr + off);
    534 				rh = (struct ip6_rthdr *)(ptr + off);
    535 				/*
    536 				 * must adjust content to make it look like
    537 				 * its final form (as seen at the final
    538 				 * destination).
    539 				 * we only know how to massage type 0 routing
    540 				 * header.
    541 				 */
    542 				if (out && rh->ip6r_type == IPV6_RTHDR_TYPE_0) {
    543 					struct ip6_rthdr0 *rh0;
    544 					struct in6_addr *addr, finaldst;
    545 					int i;
    546 
    547 					rh0 = (struct ip6_rthdr0 *)rh;
    548 					addr = (struct in6_addr *)(rh0 + 1);
    549 
    550 					for (i = 0; i < rh0->ip6r0_segleft; i++)
    551 						in6_clearscope(&addr[i]);
    552 
    553 					finaldst = addr[rh0->ip6r0_segleft - 1];
    554 					memmove(&addr[1], &addr[0],
    555 						sizeof(struct in6_addr) *
    556 						(rh0->ip6r0_segleft - 1));
    557 
    558 					m_copydata(m, 0, sizeof(ip6), &ip6);
    559 					addr[0] = ip6.ip6_dst;
    560 					ip6.ip6_dst = finaldst;
    561 					m_copyback(m, 0, sizeof(ip6), &ip6);
    562 
    563 					rh0->ip6r0_segleft = 0;
    564 				}
    565 
    566 				/* advance */
    567 				off += ((ip6e->ip6e_len + 1) << 3);
    568 				nxt = ip6e->ip6e_nxt;
    569 				break;
    570 
    571 			default:
    572 				DPRINTF(("%s: unexpected IPv6 header type %d\n",
    573 				    __func__, off));
    574 error6:
    575 				if (alloc)
    576 					free(ptr, M_XDATA);
    577 				m_freem(m);
    578 				return EINVAL;
    579 			}
    580 		}
    581 
    582 		/* Copyback and free, if we allocated. */
    583 		if (alloc) {
    584 			m_copyback(m, sizeof(struct ip6_hdr),
    585 			    skip - sizeof(struct ip6_hdr), ptr);
    586 			free(ptr, M_XDATA);
    587 		}
    588 
    589 		break;
    590 #endif /* INET6 */
    591 	}
    592 
    593 	return 0;
    594 }
    595 
    596 /*
    597  * ah_input() gets called to verify that an input packet
    598  * passes authentication.
    599  */
    600 static int
    601 ah_input(struct mbuf *m, struct secasvar *sav, int skip, int protoff)
    602 {
    603 	const struct auth_hash *ahx;
    604 	struct tdb_crypto *tc = NULL;
    605 	struct newah *ah;
    606 	int hl, rplen, authsize, error, stat = AH_STAT_HDROPS;
    607 	struct cryptodesc *crda;
    608 	struct cryptop *crp = NULL;
    609 	bool pool_used;
    610 	uint8_t nxt;
    611 
    612 	IPSEC_SPLASSERT_SOFTNET(__func__);
    613 
    614 	KASSERT(sav != NULL);
    615 	KASSERT(sav->key_auth != NULL);
    616 	KASSERT(sav->tdb_authalgxform != NULL);
    617 
    618 	/* Figure out header size. */
    619 	rplen = HDRSIZE(sav);
    620 
    621 	/* XXX don't pullup, just copy header */
    622 	IP6_EXTHDR_GET(ah, struct newah *, m, skip, rplen);
    623 	if (ah == NULL) {
    624 		DPRINTF(("%s: cannot pullup header\n", __func__));
    625 		error = ENOBUFS;
    626 		stat = AH_STAT_HDROPS;	/*XXX*/
    627 		goto bad;
    628 	}
    629 
    630 	nxt = ah->ah_nxt;
    631 
    632 	/* Check replay window, if applicable. */
    633 	if (sav->replay && !ipsec_chkreplay(ntohl(ah->ah_seq), sav)) {
    634 		char buf[IPSEC_LOGSASTRLEN];
    635 		DPRINTF(("%s: packet replay failure: %s\n", __func__,
    636 		    ipsec_logsastr(sav, buf, sizeof(buf))));
    637 		stat = AH_STAT_REPLAY;
    638 		error = ENOBUFS;
    639 		goto bad;
    640 	}
    641 
    642 	/* Verify AH header length. */
    643 	hl = ah->ah_len * sizeof(uint32_t);
    644 	ahx = sav->tdb_authalgxform;
    645 	authsize = AUTHSIZE(sav);
    646 	if (hl != authsize + rplen - sizeof(struct ah)) {
    647 		char buf[IPSEC_ADDRSTRLEN];
    648 		DPRINTF(("%s: bad authenticator length %u (expecting %lu)"
    649 			" for packet in SA %s/%08lx\n", __func__,
    650 			hl, (u_long) (authsize + rplen - sizeof(struct ah)),
    651 			ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
    652 			(u_long) ntohl(sav->spi)));
    653 		stat = AH_STAT_BADAUTHL;
    654 		error = EACCES;
    655 		goto bad;
    656 	}
    657 	if (skip + authsize + rplen > m->m_pkthdr.len) {
    658 		char buf[IPSEC_ADDRSTRLEN];
    659 		DPRINTF(("%s: bad mbuf length %u (expecting >= %lu)"
    660 			" for packet in SA %s/%08lx\n", __func__,
    661 			m->m_pkthdr.len, (u_long)(skip + authsize + rplen),
    662 			ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
    663 			(u_long) ntohl(sav->spi)));
    664 		stat = AH_STAT_BADAUTHL;
    665 		error = EACCES;
    666 		goto bad;
    667 	}
    668 
    669 	AH_STATADD(AH_STAT_IBYTES, m->m_pkthdr.len - skip - hl);
    670 
    671 	/* Get crypto descriptors. */
    672 	crp = crypto_getreq(1);
    673 	if (crp == NULL) {
    674 		DPRINTF(("%s: failed to acquire crypto descriptor\n", __func__));
    675 		stat = AH_STAT_CRYPTO;
    676 		error = ENOBUFS;
    677 		goto bad;
    678 	}
    679 
    680 	crda = crp->crp_desc;
    681 	KASSERT(crda != NULL);
    682 
    683 	crda->crd_skip = 0;
    684 	crda->crd_len = m->m_pkthdr.len;
    685 	crda->crd_inject = skip + rplen;
    686 
    687 	/* Authentication operation. */
    688 	crda->crd_alg = ahx->type;
    689 	crda->crd_key = _KEYBUF(sav->key_auth);
    690 	crda->crd_klen = _KEYBITS(sav->key_auth);
    691 
    692 	/* Allocate IPsec-specific opaque crypto info. */
    693 	size_t size = sizeof(*tc);
    694 	size_t extra = skip + rplen + authsize;
    695 	size += extra;
    696 
    697 	if (__predict_true(size <= ah_pool_item_size)) {
    698 		tc = pool_cache_get(ah_tdb_crypto_pool_cache, PR_NOWAIT);
    699 		pool_used = true;
    700 	} else {
    701 		/* size can exceed on IPv6 packets with large options.  */
    702 		tc = kmem_intr_zalloc(size, KM_NOSLEEP);
    703 		pool_used = false;
    704 	}
    705 	if (tc == NULL) {
    706 		DPRINTF(("%s: failed to allocate tdb_crypto\n", __func__));
    707 		stat = AH_STAT_CRYPTO;
    708 		error = ENOBUFS;
    709 		goto bad;
    710 	}
    711 
    712 	error = m_makewritable(&m, 0, extra, M_NOWAIT);
    713 	if (error) {
    714 		DPRINTF(("%s: failed to m_makewritable\n", __func__));
    715 		goto bad;
    716 	}
    717 
    718 	/*
    719 	 * Save the authenticator, the skipped portion of the packet,
    720 	 * and the AH header.
    721 	 */
    722 	m_copydata(m, 0, extra, (tc + 1));
    723 	/* Zeroize the authenticator on the packet. */
    724 	m_copyback(m, skip + rplen, authsize, ipseczeroes);
    725 
    726 	/* "Massage" the packet headers for crypto processing. */
    727 	error = ah_massage_headers(&m, sav->sah->saidx.dst.sa.sa_family,
    728 	    skip, ahx->type, 0);
    729 	if (error != 0) {
    730 		/* NB: mbuf is free'd by ah_massage_headers */
    731 		m = NULL;
    732 		goto bad;
    733 	}
    734 
    735     {
    736 	int s = pserialize_read_enter();
    737 
    738 	/*
    739 	 * Take another reference to the SA for opencrypto callback.
    740 	 */
    741 	if (__predict_false(sav->state == SADB_SASTATE_DEAD)) {
    742 		pserialize_read_exit(s);
    743 		stat = AH_STAT_NOTDB;
    744 		error = ENOENT;
    745 		goto bad;
    746 	}
    747 	KEY_SA_REF(sav);
    748 	pserialize_read_exit(s);
    749     }
    750 
    751 	/* Crypto operation descriptor. */
    752 	crp->crp_ilen = m->m_pkthdr.len; /* Total input length. */
    753 	crp->crp_flags = CRYPTO_F_IMBUF;
    754 	crp->crp_buf = m;
    755 	crp->crp_callback = ah_input_cb;
    756 	crp->crp_sid = sav->tdb_cryptoid;
    757 	crp->crp_opaque = tc;
    758 
    759 	/* These are passed as-is to the callback. */
    760 	tc->tc_spi = sav->spi;
    761 	tc->tc_dst = sav->sah->saidx.dst;
    762 	tc->tc_proto = sav->sah->saidx.proto;
    763 	tc->tc_nxt = nxt;
    764 	tc->tc_protoff = protoff;
    765 	tc->tc_skip = skip;
    766 	tc->tc_sav = sav;
    767 
    768 	DPRINTF(("%s: hash over %d bytes, skip %d: "
    769 		 "crda len %d skip %d inject %d\n", __func__,
    770 		 crp->crp_ilen, tc->tc_skip,
    771 		 crda->crd_len, crda->crd_skip, crda->crd_inject));
    772 
    773 	return crypto_dispatch(crp);
    774 
    775 bad:
    776 	if (tc != NULL) {
    777 		if (__predict_true(pool_used))
    778 			pool_cache_put(ah_tdb_crypto_pool_cache, tc);
    779 		else
    780 			kmem_intr_free(tc, size);
    781 	}
    782 	if (crp != NULL)
    783 		crypto_freereq(crp);
    784 	if (m != NULL)
    785 		m_freem(m);
    786 	AH_STATINC(stat);
    787 	return error;
    788 }
    789 
    790 #ifdef INET6
    791 #define	IPSEC_COMMON_INPUT_CB(m, sav, skip, protoff) do {		     \
    792 	if (saidx->dst.sa.sa_family == AF_INET6) {			     \
    793 		error = ipsec6_common_input_cb(m, sav, skip, protoff);	     \
    794 	} else {							     \
    795 		error = ipsec4_common_input_cb(m, sav, skip, protoff);	     \
    796 	}								     \
    797 } while (0)
    798 #else
    799 #define	IPSEC_COMMON_INPUT_CB(m, sav, skip, protoff)			     \
    800 	(error = ipsec4_common_input_cb(m, sav, skip, protoff))
    801 #endif
    802 
    803 /*
    804  * AH input callback from the crypto driver.
    805  */
    806 static int
    807 ah_input_cb(struct cryptop *crp)
    808 {
    809 	char buf[IPSEC_ADDRSTRLEN];
    810 	int rplen, error, skip, protoff;
    811 	unsigned char calc[AH_ALEN_MAX];
    812 	struct mbuf *m;
    813 	struct tdb_crypto *tc;
    814 	struct secasvar *sav;
    815 	struct secasindex *saidx;
    816 	uint8_t nxt;
    817 	char *ptr;
    818 	int authsize;
    819 	uint16_t dport;
    820 	uint16_t sport;
    821 	bool pool_used;
    822 	size_t size;
    823 	IPSEC_DECLARE_LOCK_VARIABLE;
    824 
    825 	KASSERT(crp->crp_opaque != NULL);
    826 	tc = crp->crp_opaque;
    827 	skip = tc->tc_skip;
    828 	nxt = tc->tc_nxt;
    829 	protoff = tc->tc_protoff;
    830 	m = crp->crp_buf;
    831 
    832 
    833 	/* find the source port for NAT-T */
    834 	nat_t_ports_get(m, &dport, &sport);
    835 
    836 	IPSEC_ACQUIRE_GLOBAL_LOCKS();
    837 
    838 	sav = tc->tc_sav;
    839 	saidx = &sav->sah->saidx;
    840 	KASSERTMSG(saidx->dst.sa.sa_family == AF_INET ||
    841 	    saidx->dst.sa.sa_family == AF_INET6,
    842 	    "unexpected protocol family %u", saidx->dst.sa.sa_family);
    843 
    844 	/* Figure out header size. */
    845 	rplen = HDRSIZE(sav);
    846 	authsize = AUTHSIZE(sav);
    847 
    848 	size = sizeof(*tc) + skip + rplen + authsize;
    849 	if (__predict_true(size <= ah_pool_item_size))
    850 		pool_used = true;
    851 	else
    852 		pool_used = false;
    853 
    854 	/* Check for crypto errors. */
    855 	if (crp->crp_etype) {
    856 		if (sav->tdb_cryptoid != 0)
    857 			sav->tdb_cryptoid = crp->crp_sid;
    858 
    859 		if (crp->crp_etype == EAGAIN) {
    860 			IPSEC_RELEASE_GLOBAL_LOCKS();
    861 			return crypto_dispatch(crp);
    862 		}
    863 
    864 		AH_STATINC(AH_STAT_NOXFORM);
    865 		DPRINTF(("%s: crypto error %d\n", __func__, crp->crp_etype));
    866 		error = crp->crp_etype;
    867 		goto bad;
    868 	} else {
    869 		AH_STATINC(AH_STAT_HIST + ah_stats[sav->alg_auth]);
    870 		crypto_freereq(crp);		/* No longer needed. */
    871 		crp = NULL;
    872 	}
    873 
    874 	if (ipsec_debug)
    875 		memset(calc, 0, sizeof(calc));
    876 
    877 	/* Copy authenticator off the packet. */
    878 	m_copydata(m, skip + rplen, authsize, calc);
    879 
    880 	ptr = (char *)(tc + 1);
    881 	const uint8_t *pppp = ptr + skip + rplen;
    882 
    883 	/* Verify authenticator. */
    884 	if (!consttime_memequal(pppp, calc, authsize)) {
    885 		DPRINTF(("%s: authentication hash mismatch " \
    886 		    "over %d bytes " \
    887 		    "for packet in SA %s/%08lx:\n" \
    888 	    "%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x, " \
    889 	    "%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x\n",
    890 		    __func__, authsize,
    891 		    ipsec_address(&saidx->dst, buf, sizeof(buf)),
    892 		    (u_long) ntohl(sav->spi),
    893 			 calc[0], calc[1], calc[2], calc[3],
    894 			 calc[4], calc[5], calc[6], calc[7],
    895 			 calc[8], calc[9], calc[10], calc[11],
    896 			 pppp[0], pppp[1], pppp[2], pppp[3],
    897 			 pppp[4], pppp[5], pppp[6], pppp[7],
    898 			 pppp[8], pppp[9], pppp[10], pppp[11]
    899 			 ));
    900 		AH_STATINC(AH_STAT_BADAUTH);
    901 		error = EACCES;
    902 		goto bad;
    903 	}
    904 
    905 	/* Fix the Next Protocol field. */
    906 	ptr[protoff] = nxt;
    907 
    908 	/* Copyback the saved (uncooked) network headers. */
    909 	m_copyback(m, 0, skip, ptr);
    910 
    911 	if (__predict_true(pool_used))
    912 		pool_cache_put(ah_tdb_crypto_pool_cache, tc);
    913 	else
    914 		kmem_intr_free(tc, size);
    915 	tc = NULL;
    916 
    917 	/*
    918 	 * Header is now authenticated.
    919 	 */
    920 	m->m_flags |= M_AUTHIPHDR|M_AUTHIPDGM;
    921 
    922 	/*
    923 	 * Update replay sequence number, if appropriate.
    924 	 */
    925 	if (sav->replay) {
    926 		uint32_t seq;
    927 
    928 		m_copydata(m, skip + offsetof(struct newah, ah_seq),
    929 		    sizeof(seq), &seq);
    930 		if (ipsec_updatereplay(ntohl(seq), sav)) {
    931 			AH_STATINC(AH_STAT_REPLAY);
    932 			error = ENOBUFS; /* XXX as above */
    933 			goto bad;
    934 		}
    935 	}
    936 
    937 	/*
    938 	 * Remove the AH header and authenticator from the mbuf.
    939 	 */
    940 	error = m_striphdr(m, skip, rplen + authsize);
    941 	if (error) {
    942 		DPRINTF(("%s: mangled mbuf chain for SA %s/%08lx\n", __func__,
    943 		    ipsec_address(&saidx->dst, buf, sizeof(buf)),
    944 		    (u_long) ntohl(sav->spi)));
    945 
    946 		AH_STATINC(AH_STAT_HDROPS);
    947 		goto bad;
    948 	}
    949 
    950 	IPSEC_COMMON_INPUT_CB(m, sav, skip, protoff);
    951 
    952 	KEY_SA_UNREF(&sav);
    953 	IPSEC_RELEASE_GLOBAL_LOCKS();
    954 	return error;
    955 
    956 bad:
    957 	if (sav)
    958 		KEY_SA_UNREF(&sav);
    959 	IPSEC_RELEASE_GLOBAL_LOCKS();
    960 	if (m != NULL)
    961 		m_freem(m);
    962 	if (tc != NULL) {
    963 		if (pool_used)
    964 			pool_cache_put(ah_tdb_crypto_pool_cache, tc);
    965 		else
    966 			kmem_intr_free(tc, size);
    967 	}
    968 	if (crp != NULL)
    969 		crypto_freereq(crp);
    970 	return error;
    971 }
    972 
    973 /*
    974  * AH output routine, called by ipsec[46]_process_packet().
    975  */
    976 static int
    977 ah_output(struct mbuf *m, const struct ipsecrequest *isr, struct secasvar *sav,
    978     struct mbuf **mp, int skip, int protoff)
    979 {
    980 	char buf[IPSEC_ADDRSTRLEN];
    981 	const struct auth_hash *ahx;
    982 	struct cryptodesc *crda;
    983 	struct tdb_crypto *tc;
    984 	struct mbuf *mi;
    985 	struct cryptop *crp;
    986 	uint16_t iplen;
    987 	int error, rplen, authsize, maxpacketsize, roff;
    988 	uint8_t prot;
    989 	struct newah *ah;
    990 	size_t ipoffs;
    991 	bool pool_used;
    992 
    993 	IPSEC_SPLASSERT_SOFTNET(__func__);
    994 
    995 	KASSERT(sav != NULL);
    996 	KASSERT(sav->tdb_authalgxform != NULL);
    997 	ahx = sav->tdb_authalgxform;
    998 
    999 	AH_STATINC(AH_STAT_OUTPUT);
   1000 
   1001 	/* Figure out header size. */
   1002 	rplen = HDRSIZE(sav);
   1003 
   1004 	/* Check for maximum packet size violations. */
   1005 	switch (sav->sah->saidx.dst.sa.sa_family) {
   1006 #ifdef INET
   1007 	case AF_INET:
   1008 		maxpacketsize = IP_MAXPACKET;
   1009 		ipoffs = offsetof(struct ip, ip_len);
   1010 		break;
   1011 #endif
   1012 #ifdef INET6
   1013 	case AF_INET6:
   1014 		maxpacketsize = IPV6_MAXPACKET;
   1015 		ipoffs = offsetof(struct ip6_hdr, ip6_plen);
   1016 		break;
   1017 #endif
   1018 	default:
   1019 		DPRINTF(("%s: unknown/unsupported protocol "
   1020 		    "family %u, SA %s/%08lx\n", __func__,
   1021 		    sav->sah->saidx.dst.sa.sa_family,
   1022 		    ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
   1023 		    (u_long) ntohl(sav->spi)));
   1024 		AH_STATINC(AH_STAT_NOPF);
   1025 		error = EPFNOSUPPORT;
   1026 		goto bad;
   1027 	}
   1028 	authsize = AUTHSIZE(sav);
   1029 	if (rplen + authsize + m->m_pkthdr.len > maxpacketsize) {
   1030 		DPRINTF(("%s: packet in SA %s/%08lx got too big "
   1031 		    "(len %u, max len %u)\n", __func__,
   1032 		    ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
   1033 		    (u_long) ntohl(sav->spi),
   1034 		    rplen + authsize + m->m_pkthdr.len, maxpacketsize));
   1035 		AH_STATINC(AH_STAT_TOOBIG);
   1036 		error = EMSGSIZE;
   1037 		goto bad;
   1038 	}
   1039 
   1040 	/* Update the counters. */
   1041 	AH_STATADD(AH_STAT_OBYTES, m->m_pkthdr.len - skip);
   1042 
   1043 	m = m_clone(m);
   1044 	if (m == NULL) {
   1045 		DPRINTF(("%s: cannot clone mbuf chain, SA %s/%08lx\n", __func__,
   1046 		    ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
   1047 		    (u_long) ntohl(sav->spi)));
   1048 		AH_STATINC(AH_STAT_HDROPS);
   1049 		error = ENOBUFS;
   1050 		goto bad;
   1051 	}
   1052 
   1053 	/* Inject AH header. */
   1054 	mi = m_makespace(m, skip, rplen + authsize, &roff);
   1055 	if (mi == NULL) {
   1056 		DPRINTF(("%s: failed to inject %u byte AH header for SA "
   1057 		    "%s/%08lx\n", __func__,
   1058 		    rplen + authsize,
   1059 		    ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
   1060 		    (u_long) ntohl(sav->spi)));
   1061 		AH_STATINC(AH_STAT_HDROPS);
   1062 		error = ENOBUFS;
   1063 		goto bad;
   1064 	}
   1065 
   1066 	/*
   1067 	 * The AH header is guaranteed by m_makespace() to be in
   1068 	 * contiguous memory, at roff bytes offset into the returned mbuf.
   1069 	 */
   1070 	ah = (struct newah *)(mtod(mi, char *) + roff);
   1071 
   1072 	/* Initialize the AH header. */
   1073 	m_copydata(m, protoff, sizeof(uint8_t), &ah->ah_nxt);
   1074 	ah->ah_len = (rplen + authsize - sizeof(struct ah)) / sizeof(uint32_t);
   1075 	ah->ah_reserve = 0;
   1076 	ah->ah_spi = sav->spi;
   1077 
   1078 	/* Zeroize authenticator. */
   1079 	m_copyback(m, skip + rplen, authsize, ipseczeroes);
   1080 
   1081 	/* Insert packet replay counter, as requested.  */
   1082 	if (sav->replay) {
   1083 		if (sav->replay->count == ~0 &&
   1084 		    (sav->flags & SADB_X_EXT_CYCSEQ) == 0) {
   1085 			DPRINTF(("%s: replay counter wrapped for SA %s/%08lx\n",
   1086 			    __func__, ipsec_address(&sav->sah->saidx.dst, buf,
   1087 			    sizeof(buf)), (u_long) ntohl(sav->spi)));
   1088 			AH_STATINC(AH_STAT_WRAP);
   1089 			error = EINVAL;
   1090 			goto bad;
   1091 		}
   1092 #ifdef IPSEC_DEBUG
   1093 		/* Emulate replay attack when ipsec_replay is TRUE. */
   1094 		if (!ipsec_replay)
   1095 #endif
   1096 			sav->replay->count++;
   1097 		ah->ah_seq = htonl(sav->replay->count);
   1098 	}
   1099 
   1100 	/* Get crypto descriptors. */
   1101 	crp = crypto_getreq(1);
   1102 	if (crp == NULL) {
   1103 		DPRINTF(("%s: failed to acquire crypto descriptors\n",
   1104 		    __func__));
   1105 		AH_STATINC(AH_STAT_CRYPTO);
   1106 		error = ENOBUFS;
   1107 		goto bad;
   1108 	}
   1109 
   1110 	crda = crp->crp_desc;
   1111 
   1112 	crda->crd_skip = 0;
   1113 	crda->crd_inject = skip + rplen;
   1114 	crda->crd_len = m->m_pkthdr.len;
   1115 
   1116 	/* Authentication operation. */
   1117 	crda->crd_alg = ahx->type;
   1118 	crda->crd_key = _KEYBUF(sav->key_auth);
   1119 	crda->crd_klen = _KEYBITS(sav->key_auth);
   1120 
   1121 	/* Allocate IPsec-specific opaque crypto info. */
   1122 	size_t size = sizeof(*tc) + skip;
   1123 
   1124 	if (__predict_true(size <= ah_pool_item_size)) {
   1125 		tc = pool_cache_get(ah_tdb_crypto_pool_cache, PR_NOWAIT);
   1126 		pool_used = true;
   1127 	} else {
   1128 		/* size can exceed on IPv6 packets with large options.  */
   1129 		tc = kmem_intr_zalloc(size, KM_NOSLEEP);
   1130 		pool_used = false;
   1131 	}
   1132 	if (tc == NULL) {
   1133 		DPRINTF(("%s: failed to allocate tdb_crypto\n", __func__));
   1134 		AH_STATINC(AH_STAT_CRYPTO);
   1135 		error = ENOBUFS;
   1136 		goto bad_crp;
   1137 	}
   1138 
   1139 	uint8_t *pext = (char *)(tc + 1);
   1140 	/* Save the skipped portion of the packet. */
   1141 	m_copydata(m, 0, skip, pext);
   1142 
   1143 	/*
   1144 	 * Fix IP header length on the header used for
   1145 	 * authentication. We don't need to fix the original
   1146 	 * header length as it will be fixed by our caller.
   1147 	 */
   1148 	memcpy(&iplen, pext + ipoffs, sizeof(iplen));
   1149 	iplen = htons(ntohs(iplen) + rplen + authsize);
   1150 	m_copyback(m, ipoffs, sizeof(iplen), &iplen);
   1151 
   1152 	/* Fix the Next Header field in saved header. */
   1153 	pext[protoff] = IPPROTO_AH;
   1154 
   1155 	/* Update the Next Protocol field in the IP header. */
   1156 	prot = IPPROTO_AH;
   1157 	m_copyback(m, protoff, sizeof(prot), &prot);
   1158 
   1159 	/* "Massage" the packet headers for crypto processing. */
   1160 	error = ah_massage_headers(&m, sav->sah->saidx.dst.sa.sa_family,
   1161 	    skip, ahx->type, 1);
   1162 	if (error != 0) {
   1163 		m = NULL;	/* mbuf was free'd by ah_massage_headers. */
   1164 		goto bad_tc;
   1165 	}
   1166 
   1167     {
   1168 	int s = pserialize_read_enter();
   1169 
   1170 	/*
   1171 	 * Take another reference to the SP and the SA for opencrypto callback.
   1172 	 */
   1173 	if (__predict_false(isr->sp->state == IPSEC_SPSTATE_DEAD ||
   1174 	    sav->state == SADB_SASTATE_DEAD)) {
   1175 		pserialize_read_exit(s);
   1176 		AH_STATINC(AH_STAT_NOTDB);
   1177 		error = ENOENT;
   1178 		goto bad_tc;
   1179 	}
   1180 	KEY_SP_REF(isr->sp);
   1181 	KEY_SA_REF(sav);
   1182 	pserialize_read_exit(s);
   1183     }
   1184 
   1185 	/* Crypto operation descriptor. */
   1186 	crp->crp_ilen = m->m_pkthdr.len; /* Total input length. */
   1187 	crp->crp_flags = CRYPTO_F_IMBUF;
   1188 	crp->crp_buf = m;
   1189 	crp->crp_callback = ah_output_cb;
   1190 	crp->crp_sid = sav->tdb_cryptoid;
   1191 	crp->crp_opaque = tc;
   1192 
   1193 	/* These are passed as-is to the callback. */
   1194 	tc->tc_isr = isr;
   1195 	tc->tc_spi = sav->spi;
   1196 	tc->tc_dst = sav->sah->saidx.dst;
   1197 	tc->tc_proto = sav->sah->saidx.proto;
   1198 	tc->tc_skip = skip;
   1199 	tc->tc_protoff = protoff;
   1200 	tc->tc_sav = sav;
   1201 
   1202 	return crypto_dispatch(crp);
   1203 
   1204 bad_tc:
   1205 	if (__predict_true(pool_used))
   1206 		pool_cache_put(ah_tdb_crypto_pool_cache, tc);
   1207 	else
   1208 		kmem_intr_free(tc, size);
   1209 bad_crp:
   1210 	crypto_freereq(crp);
   1211 bad:
   1212 	if (m)
   1213 		m_freem(m);
   1214 	return (error);
   1215 }
   1216 
   1217 /*
   1218  * AH output callback from the crypto driver.
   1219  */
   1220 static int
   1221 ah_output_cb(struct cryptop *crp)
   1222 {
   1223 	int skip, error;
   1224 	struct tdb_crypto *tc;
   1225 	const struct ipsecrequest *isr;
   1226 	struct secasvar *sav;
   1227 	struct mbuf *m;
   1228 	void *ptr;
   1229 	int err;
   1230 	size_t size;
   1231 	bool pool_used;
   1232 	IPSEC_DECLARE_LOCK_VARIABLE;
   1233 
   1234 	KASSERT(crp->crp_opaque != NULL);
   1235 	tc = crp->crp_opaque;
   1236 	skip = tc->tc_skip;
   1237 	ptr = (tc + 1);
   1238 	m = crp->crp_buf;
   1239 	size = sizeof(*tc) + skip;
   1240 	pool_used = size <= ah_pool_item_size;
   1241 
   1242 	IPSEC_ACQUIRE_GLOBAL_LOCKS();
   1243 
   1244 	isr = tc->tc_isr;
   1245 	sav = tc->tc_sav;
   1246 
   1247 	/* Check for crypto errors. */
   1248 	if (crp->crp_etype) {
   1249 		if (sav->tdb_cryptoid != 0)
   1250 			sav->tdb_cryptoid = crp->crp_sid;
   1251 
   1252 		if (crp->crp_etype == EAGAIN) {
   1253 			IPSEC_RELEASE_GLOBAL_LOCKS();
   1254 			return crypto_dispatch(crp);
   1255 		}
   1256 
   1257 		AH_STATINC(AH_STAT_NOXFORM);
   1258 		DPRINTF(("%s: crypto error %d\n", __func__, crp->crp_etype));
   1259 		error = crp->crp_etype;
   1260 		goto bad;
   1261 	}
   1262 
   1263 	AH_STATINC(AH_STAT_HIST + ah_stats[sav->alg_auth]);
   1264 
   1265 	/*
   1266 	 * Copy original headers (with the new protocol number) back
   1267 	 * in place.
   1268 	 */
   1269 	m_copyback(m, 0, skip, ptr);
   1270 
   1271 	/* No longer needed. */
   1272 	if (__predict_true(pool_used))
   1273 		pool_cache_put(ah_tdb_crypto_pool_cache, tc);
   1274 	else
   1275 		kmem_intr_free(tc, size);
   1276 	crypto_freereq(crp);
   1277 
   1278 #ifdef IPSEC_DEBUG
   1279 	/* Emulate man-in-the-middle attack when ipsec_integrity is TRUE. */
   1280 	if (ipsec_integrity) {
   1281 		int alen;
   1282 
   1283 		/*
   1284 		 * Corrupt HMAC if we want to test integrity verification of
   1285 		 * the other side.
   1286 		 */
   1287 		alen = AUTHSIZE(sav);
   1288 		m_copyback(m, m->m_pkthdr.len - alen, alen, ipseczeroes);
   1289 	}
   1290 #endif
   1291 
   1292 	/* NB: m is reclaimed by ipsec_process_done. */
   1293 	err = ipsec_process_done(m, isr, sav);
   1294 	KEY_SA_UNREF(&sav);
   1295 	KEY_SP_UNREF(&isr->sp);
   1296 	IPSEC_RELEASE_GLOBAL_LOCKS();
   1297 	return err;
   1298 bad:
   1299 	if (sav)
   1300 		KEY_SA_UNREF(&sav);
   1301 	KEY_SP_UNREF(&isr->sp);
   1302 	IPSEC_RELEASE_GLOBAL_LOCKS();
   1303 	if (m)
   1304 		m_freem(m);
   1305 	if (__predict_true(pool_used))
   1306 		pool_cache_put(ah_tdb_crypto_pool_cache, tc);
   1307 	else
   1308 		kmem_intr_free(tc, size);
   1309 	crypto_freereq(crp);
   1310 	return error;
   1311 }
   1312 
   1313 static struct xformsw ah_xformsw = {
   1314 	.xf_type	= XF_AH,
   1315 	.xf_flags	= XFT_AUTH,
   1316 	.xf_name	= "IPsec AH",
   1317 	.xf_init	= ah_init,
   1318 	.xf_zeroize	= ah_zeroize,
   1319 	.xf_input	= ah_input,
   1320 	.xf_output	= ah_output,
   1321 	.xf_next	= NULL,
   1322 };
   1323 
   1324 void
   1325 ah_attach(void)
   1326 {
   1327 	ahstat_percpu = percpu_alloc(sizeof(uint64_t) * AH_NSTATS);
   1328 
   1329 #define MAXAUTHSIZE(name)						\
   1330 	if ((auth_hash_ ## name).authsize > ah_max_authsize)		\
   1331 		ah_max_authsize = (auth_hash_ ## name).authsize
   1332 
   1333 	ah_max_authsize = 0;
   1334 	MAXAUTHSIZE(null);
   1335 	MAXAUTHSIZE(md5);
   1336 	MAXAUTHSIZE(sha1);
   1337 	MAXAUTHSIZE(key_md5);
   1338 	MAXAUTHSIZE(key_sha1);
   1339 	MAXAUTHSIZE(hmac_md5);
   1340 	MAXAUTHSIZE(hmac_sha1);
   1341 	MAXAUTHSIZE(hmac_ripemd_160);
   1342 	MAXAUTHSIZE(hmac_md5_96);
   1343 	MAXAUTHSIZE(hmac_sha1_96);
   1344 	MAXAUTHSIZE(hmac_ripemd_160_96);
   1345 	MAXAUTHSIZE(hmac_sha2_256);
   1346 	MAXAUTHSIZE(hmac_sha2_384);
   1347 	MAXAUTHSIZE(hmac_sha2_512);
   1348 	MAXAUTHSIZE(aes_xcbc_mac_96);
   1349 	MAXAUTHSIZE(gmac_aes_128);
   1350 	MAXAUTHSIZE(gmac_aes_192);
   1351 	MAXAUTHSIZE(gmac_aes_256);
   1352 	IPSECLOG(LOG_DEBUG, "ah_max_authsize=%d\n", ah_max_authsize);
   1353 
   1354 #undef MAXAUTHSIZE
   1355 
   1356 	ah_pool_item_size = sizeof(struct tdb_crypto) +
   1357 	    sizeof(struct ip) + MAX_IPOPTLEN +
   1358 	    sizeof(struct ah) + sizeof(uint32_t) + ah_max_authsize;
   1359 	ah_tdb_crypto_pool_cache = pool_cache_init(ah_pool_item_size,
   1360 	    coherency_unit, 0, 0, "ah_tdb_crypto", NULL, IPL_SOFTNET,
   1361 	    NULL, NULL, NULL);
   1362 
   1363 	xform_register(&ah_xformsw);
   1364 }
   1365