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