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