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