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