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