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