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