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