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