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