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