xref: /freebsd/sys/netipsec/xform_ah.c (revision 780fb4a2fa9a9aee5ac48a60b790f567c0dc13e9)
1 /*	$FreeBSD$	*/
2 /*	$OpenBSD: ip_ah.c,v 1.63 2001/06/26 06:18:58 angelos Exp $ */
3 /*-
4  * The authors of this code are John Ioannidis (ji@tla.org),
5  * Angelos D. Keromytis (kermit@csd.uch.gr) and
6  * Niels Provos (provos@physnet.uni-hamburg.de).
7  *
8  * The original version of this code was written by John Ioannidis
9  * for BSD/OS in Athens, Greece, in November 1995.
10  *
11  * Ported to OpenBSD and NetBSD, with additional transforms, in December 1996,
12  * by Angelos D. Keromytis.
13  *
14  * Additional transforms and features in 1997 and 1998 by Angelos D. Keromytis
15  * and Niels Provos.
16  *
17  * Additional features in 1999 by Angelos D. Keromytis and Niklas Hallqvist.
18  *
19  * Copyright (c) 1995, 1996, 1997, 1998, 1999 by John Ioannidis,
20  * Angelos D. Keromytis and Niels Provos.
21  * Copyright (c) 1999 Niklas Hallqvist.
22  * Copyright (c) 2001 Angelos D. Keromytis.
23  *
24  * Permission to use, copy, and modify this software with or without fee
25  * is hereby granted, provided that this entire notice is included in
26  * all copies of any software which is or includes a copy or
27  * modification of this software.
28  * You may use this code under the GNU public license if you so wish. Please
29  * contribute changes back to the authors under this freer than GPL license
30  * so that we may further the use of strong encryption without limitations to
31  * all.
32  *
33  * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR
34  * IMPLIED WARRANTY. IN PARTICULAR, NONE OF THE AUTHORS MAKES ANY
35  * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE
36  * MERCHANTABILITY OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR
37  * PURPOSE.
38  */
39 #include "opt_inet.h"
40 #include "opt_inet6.h"
41 
42 #include <sys/param.h>
43 #include <sys/systm.h>
44 #include <sys/mbuf.h>
45 #include <sys/socket.h>
46 #include <sys/syslog.h>
47 #include <sys/kernel.h>
48 #include <sys/lock.h>
49 #include <sys/mutex.h>
50 #include <sys/sysctl.h>
51 
52 #include <net/if.h>
53 #include <net/vnet.h>
54 
55 #include <netinet/in.h>
56 #include <netinet/in_systm.h>
57 #include <netinet/ip.h>
58 #include <netinet/ip_ecn.h>
59 #include <netinet/ip6.h>
60 
61 #include <netipsec/ipsec.h>
62 #include <netipsec/ah.h>
63 #include <netipsec/ah_var.h>
64 #include <netipsec/xform.h>
65 
66 #ifdef INET6
67 #include <netinet6/ip6_var.h>
68 #include <netipsec/ipsec6.h>
69 #include <netinet6/ip6_ecn.h>
70 #endif
71 
72 #include <netipsec/key.h>
73 #include <netipsec/key_debug.h>
74 
75 #include <opencrypto/cryptodev.h>
76 
77 /*
78  * Return header size in bytes.  The old protocol did not support
79  * the replay counter; the new protocol always includes the counter.
80  */
81 #define HDRSIZE(sav) \
82 	(((sav)->flags & SADB_X_EXT_OLD) ? \
83 		sizeof (struct ah) : sizeof (struct ah) + sizeof (u_int32_t))
84 /*
85  * Return authenticator size in bytes, based on a field in the
86  * algorithm descriptor.
87  */
88 #define	AUTHSIZE(sav)	((sav->flags & SADB_X_EXT_OLD) ? 16 :	\
89 			 xform_ah_authsize((sav)->tdb_authalgxform))
90 
91 VNET_DEFINE(int, ah_enable) = 1;	/* control flow of packets with AH */
92 VNET_DEFINE(int, ah_cleartos) = 1;	/* clear ip_tos when doing AH calc */
93 VNET_PCPUSTAT_DEFINE(struct ahstat, ahstat);
94 VNET_PCPUSTAT_SYSINIT(ahstat);
95 
96 #ifdef VIMAGE
97 VNET_PCPUSTAT_SYSUNINIT(ahstat);
98 #endif /* VIMAGE */
99 
100 #ifdef INET
101 SYSCTL_DECL(_net_inet_ah);
102 SYSCTL_INT(_net_inet_ah, OID_AUTO, ah_enable,
103 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ah_enable), 0, "");
104 SYSCTL_INT(_net_inet_ah, OID_AUTO, ah_cleartos,
105 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ah_cleartos), 0, "");
106 SYSCTL_VNET_PCPUSTAT(_net_inet_ah, IPSECCTL_STATS, stats, struct ahstat,
107     ahstat, "AH statistics (struct ahstat, netipsec/ah_var.h)");
108 #endif
109 
110 static unsigned char ipseczeroes[256];	/* larger than an ip6 extension hdr */
111 
112 static int ah_input_cb(struct cryptop*);
113 static int ah_output_cb(struct cryptop*);
114 
115 int
116 xform_ah_authsize(const struct auth_hash *esph)
117 {
118 	int alen;
119 
120 	if (esph == NULL)
121 		return 0;
122 
123 	switch (esph->type) {
124 	case CRYPTO_SHA2_256_HMAC:
125 	case CRYPTO_SHA2_384_HMAC:
126 	case CRYPTO_SHA2_512_HMAC:
127 		alen = esph->hashsize / 2;	/* RFC4868 2.3 */
128 		break;
129 
130 	case CRYPTO_AES_128_NIST_GMAC:
131 	case CRYPTO_AES_192_NIST_GMAC:
132 	case CRYPTO_AES_256_NIST_GMAC:
133 		alen = esph->hashsize;
134 		break;
135 
136 	default:
137 		alen = AH_HMAC_HASHLEN;
138 		break;
139 	}
140 
141 	return alen;
142 }
143 
144 size_t
145 ah_hdrsiz(struct secasvar *sav)
146 {
147 	size_t size;
148 
149 	if (sav != NULL) {
150 		int authsize, rplen, align;
151 
152 		IPSEC_ASSERT(sav->tdb_authalgxform != NULL, ("null xform"));
153 		/*XXX not right for null algorithm--does it matter??*/
154 
155 		/* RFC4302: use the correct alignment. */
156 		align = sizeof(uint32_t);
157 #ifdef INET6
158 		if (sav->sah->saidx.dst.sa.sa_family == AF_INET6) {
159 			align = sizeof(uint64_t);
160 		}
161 #endif
162 		rplen = HDRSIZE(sav);
163 		authsize = AUTHSIZE(sav);
164 		size = roundup(rplen + authsize, align);
165 	} else {
166 		/* default guess */
167 		size = sizeof (struct ah) + sizeof (u_int32_t) + 16;
168 	}
169 	return size;
170 }
171 
172 /*
173  * NB: public for use by esp_init.
174  */
175 int
176 ah_init0(struct secasvar *sav, struct xformsw *xsp, struct cryptoini *cria)
177 {
178 	const struct auth_hash *thash;
179 	int keylen;
180 
181 	thash = auth_algorithm_lookup(sav->alg_auth);
182 	if (thash == NULL) {
183 		DPRINTF(("%s: unsupported authentication algorithm %u\n",
184 			__func__, sav->alg_auth));
185 		return EINVAL;
186 	}
187 	/*
188 	 * Verify the replay state block allocation is consistent with
189 	 * the protocol type.  We check here so we can make assumptions
190 	 * later during protocol processing.
191 	 */
192 	/* NB: replay state is setup elsewhere (sigh) */
193 	if (((sav->flags&SADB_X_EXT_OLD) == 0) ^ (sav->replay != NULL)) {
194 		DPRINTF(("%s: replay state block inconsistency, "
195 			"%s algorithm %s replay state\n", __func__,
196 			(sav->flags & SADB_X_EXT_OLD) ? "old" : "new",
197 			sav->replay == NULL ? "without" : "with"));
198 		return EINVAL;
199 	}
200 	if (sav->key_auth == NULL) {
201 		DPRINTF(("%s: no authentication key for %s algorithm\n",
202 			__func__, thash->name));
203 		return EINVAL;
204 	}
205 	keylen = _KEYLEN(sav->key_auth);
206 	if (keylen > thash->keysize && thash->keysize != 0) {
207 		DPRINTF(("%s: invalid keylength %d, algorithm %s requires "
208 			"keysize less than %d\n", __func__,
209 			 keylen, thash->name, thash->keysize));
210 		return EINVAL;
211 	}
212 
213 	sav->tdb_xform = xsp;
214 	sav->tdb_authalgxform = thash;
215 
216 	/* Initialize crypto session. */
217 	bzero(cria, sizeof (*cria));
218 	cria->cri_alg = sav->tdb_authalgxform->type;
219 	cria->cri_klen = _KEYBITS(sav->key_auth);
220 	cria->cri_key = sav->key_auth->key_data;
221 	cria->cri_mlen = AUTHSIZE(sav);
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 	return error ? error :
237 		 crypto_newsession(&sav->tdb_cryptoid, &cria, V_crypto_support);
238 }
239 
240 /*
241  * Paranoia.
242  *
243  * NB: public for use by esp_zeroize (XXX).
244  */
245 int
246 ah_zeroize(struct secasvar *sav)
247 {
248 	int err;
249 
250 	if (sav->key_auth)
251 		bzero(sav->key_auth->key_data, _KEYLEN(sav->key_auth));
252 
253 	err = crypto_freesession(sav->tdb_cryptoid);
254 	sav->tdb_cryptoid = 0;
255 	sav->tdb_authalgxform = NULL;
256 	sav->tdb_xform = NULL;
257 	return err;
258 }
259 
260 /*
261  * Massage IPv4/IPv6 headers for AH processing.
262  */
263 static int
264 ah_massage_headers(struct mbuf **m0, int proto, int skip, int alg, int out)
265 {
266 	struct mbuf *m = *m0;
267 	unsigned char *ptr;
268 	int off, count;
269 
270 #ifdef INET
271 	struct ip *ip;
272 #endif /* INET */
273 
274 #ifdef INET6
275 	struct ip6_ext *ip6e;
276 	struct ip6_hdr ip6;
277 	int ad, alloc, nxt, noff;
278 #endif /* INET6 */
279 
280 	switch (proto) {
281 #ifdef INET
282 	case AF_INET:
283 		/*
284 		 * This is the least painful way of dealing with IPv4 header
285 		 * and option processing -- just make sure they're in
286 		 * contiguous memory.
287 		 */
288 		*m0 = m = m_pullup(m, skip);
289 		if (m == NULL) {
290 			DPRINTF(("%s: m_pullup failed\n", __func__));
291 			return ENOBUFS;
292 		}
293 
294 		/* Fix the IP header */
295 		ip = mtod(m, struct ip *);
296 		if (V_ah_cleartos)
297 			ip->ip_tos = 0;
298 		ip->ip_ttl = 0;
299 		ip->ip_sum = 0;
300 
301 		if (alg == CRYPTO_MD5_KPDK || alg == CRYPTO_SHA1_KPDK)
302 			ip->ip_off &= htons(IP_DF);
303 		else
304 			ip->ip_off = htons(0);
305 
306 		ptr = mtod(m, unsigned char *);
307 
308 		/* IPv4 option processing */
309 		for (off = sizeof(struct ip); off < skip;) {
310 			if (ptr[off] == IPOPT_EOL || ptr[off] == IPOPT_NOP ||
311 			    off + 1 < skip)
312 				;
313 			else {
314 				DPRINTF(("%s: illegal IPv4 option length for "
315 					"option %d\n", __func__, ptr[off]));
316 
317 				m_freem(m);
318 				return EINVAL;
319 			}
320 
321 			switch (ptr[off]) {
322 			case IPOPT_EOL:
323 				off = skip;  /* End the loop. */
324 				break;
325 
326 			case IPOPT_NOP:
327 				off++;
328 				break;
329 
330 			case IPOPT_SECURITY:	/* 0x82 */
331 			case 0x85:	/* Extended security. */
332 			case 0x86:	/* Commercial security. */
333 			case 0x94:	/* Router alert */
334 			case 0x95:	/* RFC1770 */
335 				/* Sanity check for option length. */
336 				if (ptr[off + 1] < 2) {
337 					DPRINTF(("%s: illegal IPv4 option "
338 						"length for option %d\n",
339 						__func__, ptr[off]));
340 
341 					m_freem(m);
342 					return EINVAL;
343 				}
344 
345 				off += ptr[off + 1];
346 				break;
347 
348 			case IPOPT_LSRR:
349 			case IPOPT_SSRR:
350 				/* Sanity check for option length. */
351 				if (ptr[off + 1] < 2) {
352 					DPRINTF(("%s: illegal IPv4 option "
353 						"length for option %d\n",
354 						__func__, ptr[off]));
355 
356 					m_freem(m);
357 					return EINVAL;
358 				}
359 
360 				/*
361 				 * On output, if we have either of the
362 				 * source routing options, we should
363 				 * swap the destination address of the
364 				 * IP header with the last address
365 				 * specified in the option, as that is
366 				 * what the destination's IP header
367 				 * will look like.
368 				 */
369 				if (out)
370 					bcopy(ptr + off + ptr[off + 1] -
371 					    sizeof(struct in_addr),
372 					    &(ip->ip_dst), sizeof(struct in_addr));
373 
374 				/* Fall through */
375 			default:
376 				/* Sanity check for option length. */
377 				if (ptr[off + 1] < 2) {
378 					DPRINTF(("%s: illegal IPv4 option "
379 						"length for option %d\n",
380 						__func__, ptr[off]));
381 					m_freem(m);
382 					return EINVAL;
383 				}
384 
385 				/* Zeroize all other options. */
386 				count = ptr[off + 1];
387 				bcopy(ipseczeroes, ptr + off, count);
388 				off += count;
389 				break;
390 			}
391 
392 			/* Sanity check. */
393 			if (off > skip)	{
394 				DPRINTF(("%s: malformed IPv4 options header\n",
395 					__func__));
396 
397 				m_freem(m);
398 				return EINVAL;
399 			}
400 		}
401 
402 		break;
403 #endif /* INET */
404 
405 #ifdef INET6
406 	case AF_INET6:  /* Ugly... */
407 		/* Copy and "cook" the IPv6 header. */
408 		m_copydata(m, 0, sizeof(ip6), (caddr_t) &ip6);
409 
410 		/* We don't do IPv6 Jumbograms. */
411 		if (ip6.ip6_plen == 0) {
412 			DPRINTF(("%s: unsupported IPv6 jumbogram\n", __func__));
413 			m_freem(m);
414 			return EMSGSIZE;
415 		}
416 
417 		ip6.ip6_flow = 0;
418 		ip6.ip6_hlim = 0;
419 		ip6.ip6_vfc &= ~IPV6_VERSION_MASK;
420 		ip6.ip6_vfc |= IPV6_VERSION;
421 
422 		/* Scoped address handling. */
423 		if (IN6_IS_SCOPE_LINKLOCAL(&ip6.ip6_src))
424 			ip6.ip6_src.s6_addr16[1] = 0;
425 		if (IN6_IS_SCOPE_LINKLOCAL(&ip6.ip6_dst))
426 			ip6.ip6_dst.s6_addr16[1] = 0;
427 
428 		/* Done with IPv6 header. */
429 		m_copyback(m, 0, sizeof(struct ip6_hdr), (caddr_t) &ip6);
430 
431 		/* Let's deal with the remaining headers (if any). */
432 		if (skip - sizeof(struct ip6_hdr) > 0) {
433 			if (m->m_len <= skip) {
434 				ptr = (unsigned char *) malloc(
435 				    skip - sizeof(struct ip6_hdr),
436 				    M_XDATA, M_NOWAIT);
437 				if (ptr == NULL) {
438 					DPRINTF(("%s: failed to allocate memory"
439 						"for IPv6 headers\n",__func__));
440 					m_freem(m);
441 					return ENOBUFS;
442 				}
443 
444 				/*
445 				 * Copy all the protocol headers after
446 				 * the IPv6 header.
447 				 */
448 				m_copydata(m, sizeof(struct ip6_hdr),
449 				    skip - sizeof(struct ip6_hdr), ptr);
450 				alloc = 1;
451 			} else {
452 				/* No need to allocate memory. */
453 				ptr = mtod(m, unsigned char *) +
454 				    sizeof(struct ip6_hdr);
455 				alloc = 0;
456 			}
457 		} else
458 			break;
459 
460 		nxt = ip6.ip6_nxt & 0xff; /* Next header type. */
461 
462 		for (off = 0; off < skip - sizeof(struct ip6_hdr);)
463 			switch (nxt) {
464 			case IPPROTO_HOPOPTS:
465 			case IPPROTO_DSTOPTS:
466 				ip6e = (struct ip6_ext *)(ptr + off);
467 				noff = off + ((ip6e->ip6e_len + 1) << 3);
468 
469 				/* Sanity check. */
470 				if (noff > skip - sizeof(struct ip6_hdr))
471 					goto error6;
472 
473 				/*
474 				 * Zero out mutable options.
475 				 */
476 				for (count = off + sizeof(struct ip6_ext);
477 				     count < noff;) {
478 					if (ptr[count] == IP6OPT_PAD1) {
479 						count++;
480 						continue; /* Skip padding. */
481 					}
482 
483 					ad = ptr[count + 1] + 2;
484 					if (count + ad > noff)
485 						goto error6;
486 
487 					if (ptr[count] & IP6OPT_MUTABLE)
488 						memset(ptr + count, 0, ad);
489 					count += ad;
490 				}
491 
492 				if (count != noff)
493 					goto error6;
494 
495 				/* Advance. */
496 				off += ((ip6e->ip6e_len + 1) << 3);
497 				nxt = ip6e->ip6e_nxt;
498 				break;
499 
500 			case IPPROTO_ROUTING:
501 				/*
502 				 * Always include routing headers in
503 				 * computation.
504 				 */
505 				ip6e = (struct ip6_ext *) (ptr + off);
506 				off += ((ip6e->ip6e_len + 1) << 3);
507 				nxt = ip6e->ip6e_nxt;
508 				break;
509 
510 			default:
511 				DPRINTF(("%s: unexpected IPv6 header type %d",
512 					__func__, off));
513 error6:
514 				if (alloc)
515 					free(ptr, M_XDATA);
516 				m_freem(m);
517 				return EINVAL;
518 			}
519 
520 		/* Copyback and free, if we allocated. */
521 		if (alloc) {
522 			m_copyback(m, sizeof(struct ip6_hdr),
523 			    skip - sizeof(struct ip6_hdr), ptr);
524 			free(ptr, M_XDATA);
525 		}
526 
527 		break;
528 #endif /* INET6 */
529 	}
530 
531 	return 0;
532 }
533 
534 /*
535  * ah_input() gets called to verify that an input packet
536  * passes authentication.
537  */
538 static int
539 ah_input(struct mbuf *m, struct secasvar *sav, int skip, int protoff)
540 {
541 	IPSEC_DEBUG_DECLARE(char buf[128]);
542 	const struct auth_hash *ahx;
543 	struct cryptodesc *crda;
544 	struct cryptop *crp;
545 	struct xform_data *xd;
546 	struct newah *ah;
547 	uint64_t cryptoid;
548 	int hl, rplen, authsize, ahsize, error;
549 
550 	IPSEC_ASSERT(sav != NULL, ("null SA"));
551 	IPSEC_ASSERT(sav->key_auth != NULL, ("null authentication key"));
552 	IPSEC_ASSERT(sav->tdb_authalgxform != NULL,
553 		("null authentication xform"));
554 
555 	/* Figure out header size. */
556 	rplen = HDRSIZE(sav);
557 
558 	/* XXX don't pullup, just copy header */
559 	IP6_EXTHDR_GET(ah, struct newah *, m, skip, rplen);
560 	if (ah == NULL) {
561 		DPRINTF(("ah_input: cannot pullup header\n"));
562 		AHSTAT_INC(ahs_hdrops);		/*XXX*/
563 		error = ENOBUFS;
564 		goto bad;
565 	}
566 
567 	/* Check replay window, if applicable. */
568 	SECASVAR_LOCK(sav);
569 	if (sav->replay != NULL && sav->replay->wsize != 0 &&
570 	    ipsec_chkreplay(ntohl(ah->ah_seq), sav) == 0) {
571 		SECASVAR_UNLOCK(sav);
572 		AHSTAT_INC(ahs_replay);
573 		DPRINTF(("%s: packet replay failure: %s\n", __func__,
574 		    ipsec_sa2str(sav, buf, sizeof(buf))));
575 		error = EACCES;
576 		goto bad;
577 	}
578 	cryptoid = sav->tdb_cryptoid;
579 	SECASVAR_UNLOCK(sav);
580 
581 	/* Verify AH header length. */
582 	hl = sizeof(struct ah) + (ah->ah_len * sizeof (u_int32_t));
583 	ahx = sav->tdb_authalgxform;
584 	authsize = AUTHSIZE(sav);
585 	ahsize = ah_hdrsiz(sav);
586 	if (hl != ahsize) {
587 		DPRINTF(("%s: bad authenticator length %u (expecting %lu)"
588 		    " for packet in SA %s/%08lx\n", __func__, hl,
589 		    (u_long)ahsize,
590 		    ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
591 		    (u_long) ntohl(sav->spi)));
592 		AHSTAT_INC(ahs_badauthl);
593 		error = EACCES;
594 		goto bad;
595 	}
596 	if (skip + ahsize > m->m_pkthdr.len) {
597 		DPRINTF(("%s: bad mbuf length %u (expecting %lu)"
598 		    " for packet in SA %s/%08lx\n", __func__,
599 		    m->m_pkthdr.len, (u_long)(skip + ahsize),
600 		    ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
601 		    (u_long) ntohl(sav->spi)));
602 		AHSTAT_INC(ahs_badauthl);
603 		error = EACCES;
604 		goto bad;
605 	}
606 	AHSTAT_ADD(ahs_ibytes, m->m_pkthdr.len - skip - hl);
607 
608 	/* Get crypto descriptors. */
609 	crp = crypto_getreq(1);
610 	if (crp == NULL) {
611 		DPRINTF(("%s: failed to acquire crypto descriptor\n",
612 		    __func__));
613 		AHSTAT_INC(ahs_crypto);
614 		error = ENOBUFS;
615 		goto bad;
616 	}
617 
618 	crda = crp->crp_desc;
619 	IPSEC_ASSERT(crda != NULL, ("null crypto descriptor"));
620 
621 	crda->crd_skip = 0;
622 	crda->crd_len = m->m_pkthdr.len;
623 	crda->crd_inject = skip + rplen;
624 
625 	/* Authentication operation. */
626 	crda->crd_alg = ahx->type;
627 	crda->crd_klen = _KEYBITS(sav->key_auth);
628 	crda->crd_key = sav->key_auth->key_data;
629 
630 	/* Allocate IPsec-specific opaque crypto info. */
631 	xd = malloc(sizeof(*xd) + skip + rplen + authsize, M_XDATA,
632 	    M_NOWAIT | M_ZERO);
633 	if (xd == NULL) {
634 		DPRINTF(("%s: failed to allocate xform_data\n", __func__));
635 		AHSTAT_INC(ahs_crypto);
636 		crypto_freereq(crp);
637 		error = ENOBUFS;
638 		goto bad;
639 	}
640 
641 	/*
642 	 * Save the authenticator, the skipped portion of the packet,
643 	 * and the AH header.
644 	 */
645 	m_copydata(m, 0, skip + rplen + authsize, (caddr_t)(xd + 1));
646 
647 	/* Zeroize the authenticator on the packet. */
648 	m_copyback(m, skip + rplen, authsize, ipseczeroes);
649 
650 	/* Save ah_nxt, since ah pointer can become invalid after "massage" */
651 	hl = ah->ah_nxt;
652 
653 	/* "Massage" the packet headers for crypto processing. */
654 	error = ah_massage_headers(&m, sav->sah->saidx.dst.sa.sa_family,
655 	    skip, ahx->type, 0);
656 	if (error != 0) {
657 		/* NB: mbuf is free'd by ah_massage_headers */
658 		AHSTAT_INC(ahs_hdrops);
659 		free(xd, M_XDATA);
660 		crypto_freereq(crp);
661 		key_freesav(&sav);
662 		return (error);
663 	}
664 
665 	/* Crypto operation descriptor. */
666 	crp->crp_ilen = m->m_pkthdr.len; /* Total input length. */
667 	crp->crp_flags = CRYPTO_F_IMBUF | CRYPTO_F_CBIFSYNC;
668 	if (V_async_crypto)
669 		crp->crp_flags |= CRYPTO_F_ASYNC | CRYPTO_F_ASYNC_KEEPORDER;
670 	crp->crp_buf = (caddr_t) m;
671 	crp->crp_callback = ah_input_cb;
672 	crp->crp_sid = cryptoid;
673 	crp->crp_opaque = (caddr_t) xd;
674 
675 	/* These are passed as-is to the callback. */
676 	xd->sav = sav;
677 	xd->nxt = hl;
678 	xd->protoff = protoff;
679 	xd->skip = skip;
680 	xd->cryptoid = cryptoid;
681 	xd->vnet = curvnet;
682 	return (crypto_dispatch(crp));
683 bad:
684 	m_freem(m);
685 	key_freesav(&sav);
686 	return (error);
687 }
688 
689 /*
690  * AH input callback from the crypto driver.
691  */
692 static int
693 ah_input_cb(struct cryptop *crp)
694 {
695 	IPSEC_DEBUG_DECLARE(char buf[IPSEC_ADDRSTRLEN]);
696 	unsigned char calc[AH_ALEN_MAX];
697 	struct mbuf *m;
698 	struct xform_data *xd;
699 	struct secasvar *sav;
700 	struct secasindex *saidx;
701 	caddr_t ptr;
702 	uint64_t cryptoid;
703 	int authsize, rplen, ahsize, error, skip, protoff;
704 	uint8_t nxt;
705 
706 	m = (struct mbuf *) crp->crp_buf;
707 	xd = (struct xform_data *) crp->crp_opaque;
708 	CURVNET_SET(xd->vnet);
709 	sav = xd->sav;
710 	skip = xd->skip;
711 	nxt = xd->nxt;
712 	protoff = xd->protoff;
713 	cryptoid = xd->cryptoid;
714 	saidx = &sav->sah->saidx;
715 	IPSEC_ASSERT(saidx->dst.sa.sa_family == AF_INET ||
716 		saidx->dst.sa.sa_family == AF_INET6,
717 		("unexpected protocol family %u", saidx->dst.sa.sa_family));
718 
719 	/* Check for crypto errors. */
720 	if (crp->crp_etype) {
721 		if (crp->crp_etype == EAGAIN) {
722 			/* Reset the session ID */
723 			if (ipsec_updateid(sav, &crp->crp_sid, &cryptoid) != 0)
724 				crypto_freesession(cryptoid);
725 			xd->cryptoid = crp->crp_sid;
726 			CURVNET_RESTORE();
727 			return (crypto_dispatch(crp));
728 		}
729 		AHSTAT_INC(ahs_noxform);
730 		DPRINTF(("%s: crypto error %d\n", __func__, crp->crp_etype));
731 		error = crp->crp_etype;
732 		goto bad;
733 	} else {
734 		AHSTAT_INC(ahs_hist[sav->alg_auth]);
735 		crypto_freereq(crp);		/* No longer needed. */
736 		crp = NULL;
737 	}
738 
739 	/* Shouldn't happen... */
740 	if (m == NULL) {
741 		AHSTAT_INC(ahs_crypto);
742 		DPRINTF(("%s: bogus returned buffer from crypto\n", __func__));
743 		error = EINVAL;
744 		goto bad;
745 	}
746 
747 	/* Figure out header size. */
748 	rplen = HDRSIZE(sav);
749 	authsize = AUTHSIZE(sav);
750 	ahsize = ah_hdrsiz(sav);
751 
752 	/* Copy authenticator off the packet. */
753 	m_copydata(m, skip + rplen, authsize, calc);
754 
755 	/* Verify authenticator. */
756 	ptr = (caddr_t) (xd + 1);
757 	if (timingsafe_bcmp(ptr + skip + rplen, calc, authsize)) {
758 		DPRINTF(("%s: authentication hash mismatch for packet "
759 		    "in SA %s/%08lx\n", __func__,
760 		    ipsec_address(&saidx->dst, buf, sizeof(buf)),
761 		    (u_long) ntohl(sav->spi)));
762 		AHSTAT_INC(ahs_badauth);
763 		error = EACCES;
764 		goto bad;
765 	}
766 	/* Fix the Next Protocol field. */
767 	((uint8_t *) ptr)[protoff] = nxt;
768 
769 	/* Copyback the saved (uncooked) network headers. */
770 	m_copyback(m, 0, skip, ptr);
771 	free(xd, M_XDATA), xd = NULL;			/* No longer needed */
772 
773 	/*
774 	 * Header is now authenticated.
775 	 */
776 	m->m_flags |= M_AUTHIPHDR|M_AUTHIPDGM;
777 
778 	/*
779 	 * Update replay sequence number, if appropriate.
780 	 */
781 	if (sav->replay) {
782 		u_int32_t seq;
783 
784 		m_copydata(m, skip + offsetof(struct newah, ah_seq),
785 			   sizeof (seq), (caddr_t) &seq);
786 		SECASVAR_LOCK(sav);
787 		if (ipsec_updatereplay(ntohl(seq), sav)) {
788 			SECASVAR_UNLOCK(sav);
789 			AHSTAT_INC(ahs_replay);
790 			error = EACCES;
791 			goto bad;
792 		}
793 		SECASVAR_UNLOCK(sav);
794 	}
795 
796 	/*
797 	 * Remove the AH header and authenticator from the mbuf.
798 	 */
799 	error = m_striphdr(m, skip, ahsize);
800 	if (error) {
801 		DPRINTF(("%s: mangled mbuf chain for SA %s/%08lx\n", __func__,
802 		    ipsec_address(&saidx->dst, buf, sizeof(buf)),
803 		    (u_long) ntohl(sav->spi)));
804 		AHSTAT_INC(ahs_hdrops);
805 		goto bad;
806 	}
807 
808 	switch (saidx->dst.sa.sa_family) {
809 #ifdef INET6
810 	case AF_INET6:
811 		error = ipsec6_common_input_cb(m, sav, skip, protoff);
812 		break;
813 #endif
814 #ifdef INET
815 	case AF_INET:
816 		error = ipsec4_common_input_cb(m, sav, skip, protoff);
817 		break;
818 #endif
819 	default:
820 		panic("%s: Unexpected address family: %d saidx=%p", __func__,
821 		    saidx->dst.sa.sa_family, saidx);
822 	}
823 	CURVNET_RESTORE();
824 	return error;
825 bad:
826 	CURVNET_RESTORE();
827 	if (sav)
828 		key_freesav(&sav);
829 	if (m != NULL)
830 		m_freem(m);
831 	if (xd != NULL)
832 		free(xd, M_XDATA);
833 	if (crp != NULL)
834 		crypto_freereq(crp);
835 	return error;
836 }
837 
838 /*
839  * AH output routine, called by ipsec[46]_perform_request().
840  */
841 static int
842 ah_output(struct mbuf *m, struct secpolicy *sp, struct secasvar *sav,
843     u_int idx, int skip, int protoff)
844 {
845 	IPSEC_DEBUG_DECLARE(char buf[IPSEC_ADDRSTRLEN]);
846 	const struct auth_hash *ahx;
847 	struct cryptodesc *crda;
848 	struct xform_data *xd;
849 	struct mbuf *mi;
850 	struct cryptop *crp;
851 	struct newah *ah;
852 	uint64_t cryptoid;
853 	uint16_t iplen;
854 	int error, rplen, authsize, ahsize, maxpacketsize, roff;
855 	uint8_t prot;
856 
857 	IPSEC_ASSERT(sav != NULL, ("null SA"));
858 	ahx = sav->tdb_authalgxform;
859 	IPSEC_ASSERT(ahx != NULL, ("null authentication xform"));
860 
861 	AHSTAT_INC(ahs_output);
862 
863 	/* Figure out header size. */
864 	rplen = HDRSIZE(sav);
865 	authsize = AUTHSIZE(sav);
866 	ahsize = ah_hdrsiz(sav);
867 
868 	/* Check for maximum packet size violations. */
869 	switch (sav->sah->saidx.dst.sa.sa_family) {
870 #ifdef INET
871 	case AF_INET:
872 		maxpacketsize = IP_MAXPACKET;
873 		break;
874 #endif /* INET */
875 #ifdef INET6
876 	case AF_INET6:
877 		maxpacketsize = IPV6_MAXPACKET;
878 		break;
879 #endif /* INET6 */
880 	default:
881 		DPRINTF(("%s: unknown/unsupported protocol family %u, "
882 		    "SA %s/%08lx\n", __func__,
883 		    sav->sah->saidx.dst.sa.sa_family,
884 		    ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
885 		    (u_long) ntohl(sav->spi)));
886 		AHSTAT_INC(ahs_nopf);
887 		error = EPFNOSUPPORT;
888 		goto bad;
889 	}
890 	if (ahsize + m->m_pkthdr.len > maxpacketsize) {
891 		DPRINTF(("%s: packet in SA %s/%08lx got too big "
892 		    "(len %u, max len %u)\n", __func__,
893 		    ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
894 		    (u_long) ntohl(sav->spi),
895 		    ahsize + m->m_pkthdr.len, maxpacketsize));
896 		AHSTAT_INC(ahs_toobig);
897 		error = EMSGSIZE;
898 		goto bad;
899 	}
900 
901 	/* Update the counters. */
902 	AHSTAT_ADD(ahs_obytes, m->m_pkthdr.len - skip);
903 
904 	m = m_unshare(m, M_NOWAIT);
905 	if (m == NULL) {
906 		DPRINTF(("%s: cannot clone mbuf chain, SA %s/%08lx\n", __func__,
907 		    ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
908 		    (u_long) ntohl(sav->spi)));
909 		AHSTAT_INC(ahs_hdrops);
910 		error = ENOBUFS;
911 		goto bad;
912 	}
913 
914 	/* Inject AH header. */
915 	mi = m_makespace(m, skip, ahsize, &roff);
916 	if (mi == NULL) {
917 		DPRINTF(("%s: failed to inject %u byte AH header for SA "
918 		    "%s/%08lx\n", __func__, ahsize,
919 		    ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
920 		    (u_long) ntohl(sav->spi)));
921 		AHSTAT_INC(ahs_hdrops);		/*XXX differs from openbsd */
922 		error = ENOBUFS;
923 		goto bad;
924 	}
925 
926 	/*
927 	 * The AH header is guaranteed by m_makespace() to be in
928 	 * contiguous memory, at roff bytes offset into the returned mbuf.
929 	 */
930 	ah = (struct newah *)(mtod(mi, caddr_t) + roff);
931 
932 	/* Initialize the AH header. */
933 	m_copydata(m, protoff, sizeof(u_int8_t), (caddr_t) &ah->ah_nxt);
934 	ah->ah_len = (ahsize - sizeof(struct ah)) / sizeof(u_int32_t);
935 	ah->ah_reserve = 0;
936 	ah->ah_spi = sav->spi;
937 
938 	/* Zeroize authenticator. */
939 	m_copyback(m, skip + rplen, authsize, ipseczeroes);
940 
941 	/* Zeroize padding */
942 	m_copyback(m, skip + rplen + authsize, ahsize - (rplen + authsize),
943 	    ipseczeroes);
944 
945 	/* Insert packet replay counter, as requested.  */
946 	SECASVAR_LOCK(sav);
947 	if (sav->replay) {
948 		if (sav->replay->count == ~0 &&
949 		    (sav->flags & SADB_X_EXT_CYCSEQ) == 0) {
950 			SECASVAR_UNLOCK(sav);
951 			DPRINTF(("%s: replay counter wrapped for SA %s/%08lx\n",
952 			    __func__, ipsec_address(&sav->sah->saidx.dst, buf,
953 			    sizeof(buf)), (u_long) ntohl(sav->spi)));
954 			AHSTAT_INC(ahs_wrap);
955 			error = EACCES;
956 			goto bad;
957 		}
958 #ifdef REGRESSION
959 		/* Emulate replay attack when ipsec_replay is TRUE. */
960 		if (!V_ipsec_replay)
961 #endif
962 			sav->replay->count++;
963 		ah->ah_seq = htonl(sav->replay->count);
964 	}
965 	cryptoid = sav->tdb_cryptoid;
966 	SECASVAR_UNLOCK(sav);
967 
968 	/* Get crypto descriptors. */
969 	crp = crypto_getreq(1);
970 	if (crp == NULL) {
971 		DPRINTF(("%s: failed to acquire crypto descriptors\n",
972 			__func__));
973 		AHSTAT_INC(ahs_crypto);
974 		error = ENOBUFS;
975 		goto bad;
976 	}
977 
978 	crda = crp->crp_desc;
979 	crda->crd_skip = 0;
980 	crda->crd_inject = skip + rplen;
981 	crda->crd_len = m->m_pkthdr.len;
982 
983 	/* Authentication operation. */
984 	crda->crd_alg = ahx->type;
985 	crda->crd_key = sav->key_auth->key_data;
986 	crda->crd_klen = _KEYBITS(sav->key_auth);
987 
988 	/* Allocate IPsec-specific opaque crypto info. */
989 	xd =  malloc(sizeof(struct xform_data) + skip, M_XDATA,
990 	    M_NOWAIT | M_ZERO);
991 	if (xd == NULL) {
992 		crypto_freereq(crp);
993 		DPRINTF(("%s: failed to allocate xform_data\n", __func__));
994 		AHSTAT_INC(ahs_crypto);
995 		error = ENOBUFS;
996 		goto bad;
997 	}
998 
999 	/* Save the skipped portion of the packet. */
1000 	m_copydata(m, 0, skip, (caddr_t) (xd + 1));
1001 
1002 	/*
1003 	 * Fix IP header length on the header used for
1004 	 * authentication. We don't need to fix the original
1005 	 * header length as it will be fixed by our caller.
1006 	 */
1007 	switch (sav->sah->saidx.dst.sa.sa_family) {
1008 #ifdef INET
1009 	case AF_INET:
1010 		bcopy(((caddr_t)(xd + 1)) +
1011 		    offsetof(struct ip, ip_len),
1012 		    (caddr_t) &iplen, sizeof(u_int16_t));
1013 		iplen = htons(ntohs(iplen) + ahsize);
1014 		m_copyback(m, offsetof(struct ip, ip_len),
1015 		    sizeof(u_int16_t), (caddr_t) &iplen);
1016 		break;
1017 #endif /* INET */
1018 
1019 #ifdef INET6
1020 	case AF_INET6:
1021 		bcopy(((caddr_t)(xd + 1)) +
1022 		    offsetof(struct ip6_hdr, ip6_plen),
1023 		    (caddr_t) &iplen, sizeof(uint16_t));
1024 		iplen = htons(ntohs(iplen) + ahsize);
1025 		m_copyback(m, offsetof(struct ip6_hdr, ip6_plen),
1026 		    sizeof(uint16_t), (caddr_t) &iplen);
1027 		break;
1028 #endif /* INET6 */
1029 	}
1030 
1031 	/* Fix the Next Header field in saved header. */
1032 	((uint8_t *) (xd + 1))[protoff] = IPPROTO_AH;
1033 
1034 	/* Update the Next Protocol field in the IP header. */
1035 	prot = IPPROTO_AH;
1036 	m_copyback(m, protoff, sizeof(uint8_t), (caddr_t) &prot);
1037 
1038 	/* "Massage" the packet headers for crypto processing. */
1039 	error = ah_massage_headers(&m, sav->sah->saidx.dst.sa.sa_family,
1040 			skip, ahx->type, 1);
1041 	if (error != 0) {
1042 		m = NULL;	/* mbuf was free'd by ah_massage_headers. */
1043 		free(xd, M_XDATA);
1044 		crypto_freereq(crp);
1045 		goto bad;
1046 	}
1047 
1048 	/* Crypto operation descriptor. */
1049 	crp->crp_ilen = m->m_pkthdr.len; /* Total input length. */
1050 	crp->crp_flags = CRYPTO_F_IMBUF | CRYPTO_F_CBIFSYNC;
1051 	if (V_async_crypto)
1052 		crp->crp_flags |= CRYPTO_F_ASYNC | CRYPTO_F_ASYNC_KEEPORDER;
1053 	crp->crp_buf = (caddr_t) m;
1054 	crp->crp_callback = ah_output_cb;
1055 	crp->crp_sid = cryptoid;
1056 	crp->crp_opaque = (caddr_t) xd;
1057 
1058 	/* These are passed as-is to the callback. */
1059 	xd->sp = sp;
1060 	xd->sav = sav;
1061 	xd->skip = skip;
1062 	xd->idx = idx;
1063 	xd->cryptoid = cryptoid;
1064 	xd->vnet = curvnet;
1065 
1066 	return crypto_dispatch(crp);
1067 bad:
1068 	if (m)
1069 		m_freem(m);
1070 	key_freesav(&sav);
1071 	key_freesp(&sp);
1072 	return (error);
1073 }
1074 
1075 /*
1076  * AH output callback from the crypto driver.
1077  */
1078 static int
1079 ah_output_cb(struct cryptop *crp)
1080 {
1081 	struct xform_data *xd;
1082 	struct secpolicy *sp;
1083 	struct secasvar *sav;
1084 	struct mbuf *m;
1085 	uint64_t cryptoid;
1086 	caddr_t ptr;
1087 	u_int idx;
1088 	int skip, error;
1089 
1090 	m = (struct mbuf *) crp->crp_buf;
1091 	xd = (struct xform_data *) crp->crp_opaque;
1092 	CURVNET_SET(xd->vnet);
1093 	sp = xd->sp;
1094 	sav = xd->sav;
1095 	skip = xd->skip;
1096 	idx = xd->idx;
1097 	cryptoid = xd->cryptoid;
1098 	ptr = (caddr_t) (xd + 1);
1099 
1100 	/* Check for crypto errors. */
1101 	if (crp->crp_etype) {
1102 		if (crp->crp_etype == EAGAIN) {
1103 			/* Reset the session ID */
1104 			if (ipsec_updateid(sav, &crp->crp_sid, &cryptoid) != 0)
1105 				crypto_freesession(cryptoid);
1106 			xd->cryptoid = crp->crp_sid;
1107 			CURVNET_RESTORE();
1108 			return (crypto_dispatch(crp));
1109 		}
1110 		AHSTAT_INC(ahs_noxform);
1111 		DPRINTF(("%s: crypto error %d\n", __func__, crp->crp_etype));
1112 		error = crp->crp_etype;
1113 		m_freem(m);
1114 		goto bad;
1115 	}
1116 
1117 	/* Shouldn't happen... */
1118 	if (m == NULL) {
1119 		AHSTAT_INC(ahs_crypto);
1120 		DPRINTF(("%s: bogus returned buffer from crypto\n", __func__));
1121 		error = EINVAL;
1122 		goto bad;
1123 	}
1124 	/*
1125 	 * Copy original headers (with the new protocol number) back
1126 	 * in place.
1127 	 */
1128 	m_copyback(m, 0, skip, ptr);
1129 
1130 	free(xd, M_XDATA);
1131 	crypto_freereq(crp);
1132 	AHSTAT_INC(ahs_hist[sav->alg_auth]);
1133 #ifdef REGRESSION
1134 	/* Emulate man-in-the-middle attack when ipsec_integrity is TRUE. */
1135 	if (V_ipsec_integrity) {
1136 		int alen;
1137 
1138 		/*
1139 		 * Corrupt HMAC if we want to test integrity verification of
1140 		 * the other side.
1141 		 */
1142 		alen = AUTHSIZE(sav);
1143 		m_copyback(m, m->m_pkthdr.len - alen, alen, ipseczeroes);
1144 	}
1145 #endif
1146 
1147 	/* NB: m is reclaimed by ipsec_process_done. */
1148 	error = ipsec_process_done(m, sp, sav, idx);
1149 	CURVNET_RESTORE();
1150 	return (error);
1151 bad:
1152 	CURVNET_RESTORE();
1153 	free(xd, M_XDATA);
1154 	crypto_freereq(crp);
1155 	key_freesav(&sav);
1156 	key_freesp(&sp);
1157 	return (error);
1158 }
1159 
1160 static struct xformsw ah_xformsw = {
1161 	.xf_type =	XF_AH,
1162 	.xf_name =	"IPsec AH",
1163 	.xf_init =	ah_init,
1164 	.xf_zeroize =	ah_zeroize,
1165 	.xf_input =	ah_input,
1166 	.xf_output =	ah_output,
1167 };
1168 
1169 SYSINIT(ah_xform_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE,
1170     xform_attach, &ah_xformsw);
1171 SYSUNINIT(ah_xform_uninit, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE,
1172     xform_detach, &ah_xformsw);
1173