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