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