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