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