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