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