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