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