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