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