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