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