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