xform_esp.c revision 190909
1/*	$FreeBSD: head/sys/netipsec/xform_esp.c 190909 2009-04-11 05:58:58Z zec $	*/
2/*	$OpenBSD: ip_esp.c,v 1.69 2001/06/26 06:18:59 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.
18 *
19 * Copyright (C) 1995, 1996, 1997, 1998, 1999 by John Ioannidis,
20 * Angelos D. Keromytis and Niels Provos.
21 * Copyright (c) 2001 Angelos D. Keromytis.
22 *
23 * Permission to use, copy, and modify this software with or without fee
24 * is hereby granted, provided that this entire notice is included in
25 * all copies of any software which is or includes a copy or
26 * modification of this software.
27 * You may use this code under the GNU public license if you so wish. Please
28 * contribute changes back to the authors under this freer than GPL license
29 * so that we may further the use of strong encryption without limitations to
30 * all.
31 *
32 * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR
33 * IMPLIED WARRANTY. IN PARTICULAR, NONE OF THE AUTHORS MAKES ANY
34 * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE
35 * MERCHANTABILITY OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR
36 * PURPOSE.
37 */
38#include "opt_inet.h"
39#include "opt_inet6.h"
40
41#include <sys/param.h>
42#include <sys/systm.h>
43#include <sys/mbuf.h>
44#include <sys/socket.h>
45#include <sys/syslog.h>
46#include <sys/kernel.h>
47#include <sys/random.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/esp.h>
64#include <netipsec/esp_var.h>
65#include <netipsec/xform.h>
66
67#ifdef INET6
68#include <netinet6/ip6_var.h>
69#include <netipsec/ipsec6.h>
70#include <netinet6/ip6_ecn.h>
71#endif
72
73#include <netipsec/key.h>
74#include <netipsec/key_debug.h>
75
76#include <opencrypto/cryptodev.h>
77#include <opencrypto/xform.h>
78
79#ifdef VIMAGE_GLOBALS
80struct	espstat espstat;
81static	int esp_max_ivlen;		/* max iv length over all algorithms */
82int	esp_enable;
83#endif
84
85SYSCTL_DECL(_net_inet_esp);
86SYSCTL_V_INT(V_NET, vnet_ipsec,_net_inet_esp, OID_AUTO,
87	esp_enable,	CTLFLAG_RW,	esp_enable,	0, "");
88SYSCTL_V_STRUCT(V_NET, vnet_ipsec, _net_inet_esp, IPSECCTL_STATS,
89	stats,		CTLFLAG_RD,	espstat,	espstat, "");
90
91static int esp_input_cb(struct cryptop *op);
92static int esp_output_cb(struct cryptop *crp);
93static int esp_iattach(const void *);
94
95#ifndef VIMAGE_GLOBALS
96static const vnet_modinfo_t vnet_esp_modinfo = {
97	.vmi_id		= VNET_MOD_ESP,
98	.vmi_name	= "ipsec_esp",
99	.vmi_dependson	= VNET_MOD_IPSEC,
100	.vmi_iattach	= esp_iattach
101};
102#endif /* !VIMAGE_GLOBALS */
103
104/*
105 * NB: this is public for use by the PF_KEY support.
106 * NB: if you add support here; be sure to add code to esp_attach below!
107 */
108struct enc_xform *
109esp_algorithm_lookup(int alg)
110{
111	if (alg >= ESP_ALG_MAX)
112		return NULL;
113	switch (alg) {
114	case SADB_EALG_DESCBC:
115		return &enc_xform_des;
116	case SADB_EALG_3DESCBC:
117		return &enc_xform_3des;
118	case SADB_X_EALG_AES:
119		return &enc_xform_rijndael128;
120	case SADB_X_EALG_BLOWFISHCBC:
121		return &enc_xform_blf;
122	case SADB_X_EALG_CAST128CBC:
123		return &enc_xform_cast5;
124	case SADB_X_EALG_SKIPJACK:
125		return &enc_xform_skipjack;
126	case SADB_EALG_NULL:
127		return &enc_xform_null;
128	case SADB_X_EALG_CAMELLIACBC:
129		return &enc_xform_camellia;
130	}
131	return NULL;
132}
133
134size_t
135esp_hdrsiz(struct secasvar *sav)
136{
137	INIT_VNET_IPSEC(curvnet);
138	size_t size;
139
140	if (sav != NULL) {
141		/*XXX not right for null algorithm--does it matter??*/
142		IPSEC_ASSERT(sav->tdb_encalgxform != NULL,
143			("SA with null xform"));
144		if (sav->flags & SADB_X_EXT_OLD)
145			size = sizeof (struct esp);
146		else
147			size = sizeof (struct newesp);
148		size += sav->tdb_encalgxform->blocksize + 9;
149		/*XXX need alg check???*/
150		if (sav->tdb_authalgxform != NULL && sav->replay)
151			size += ah_hdrsiz(sav);
152	} else {
153		/*
154		 *   base header size
155		 * + max iv length for CBC mode
156		 * + max pad length
157		 * + sizeof (pad length field)
158		 * + sizeof (next header field)
159		 * + max icv supported.
160		 */
161		size = sizeof (struct newesp) + V_esp_max_ivlen + 9 + 16;
162	}
163	return size;
164}
165
166/*
167 * esp_init() is called when an SPI is being set up.
168 */
169static int
170esp_init(struct secasvar *sav, struct xformsw *xsp)
171{
172	INIT_VNET_IPSEC(curvnet);
173	struct enc_xform *txform;
174	struct cryptoini cria, crie;
175	int keylen;
176	int error;
177
178	txform = esp_algorithm_lookup(sav->alg_enc);
179	if (txform == NULL) {
180		DPRINTF(("%s: unsupported encryption algorithm %d\n",
181			__func__, sav->alg_enc));
182		return EINVAL;
183	}
184	if (sav->key_enc == NULL) {
185		DPRINTF(("%s: no encoding key for %s algorithm\n",
186			 __func__, txform->name));
187		return EINVAL;
188	}
189	if ((sav->flags&(SADB_X_EXT_OLD|SADB_X_EXT_IV4B)) == SADB_X_EXT_IV4B) {
190		DPRINTF(("%s: 4-byte IV not supported with protocol\n",
191			__func__));
192		return EINVAL;
193	}
194	keylen = _KEYLEN(sav->key_enc);
195	if (txform->minkey > keylen || keylen > txform->maxkey) {
196		DPRINTF(("%s: invalid key length %u, must be in the range "
197			"[%u..%u] for algorithm %s\n", __func__,
198			keylen, txform->minkey, txform->maxkey,
199			txform->name));
200		return EINVAL;
201	}
202
203	/*
204	 * NB: The null xform needs a non-zero blocksize to keep the
205	 *      crypto code happy but if we use it to set ivlen then
206	 *      the ESP header will be processed incorrectly.  The
207	 *      compromise is to force it to zero here.
208	 */
209	sav->ivlen = (txform == &enc_xform_null ? 0 : txform->blocksize);
210	sav->iv = (caddr_t) malloc(sav->ivlen, M_XDATA, M_WAITOK);
211	if (sav->iv == NULL) {
212		DPRINTF(("%s: no memory for IV\n", __func__));
213		return EINVAL;
214	}
215	key_randomfill(sav->iv, sav->ivlen);	/*XXX*/
216
217	/*
218	 * Setup AH-related state.
219	 */
220	if (sav->alg_auth != 0) {
221		error = ah_init0(sav, xsp, &cria);
222		if (error)
223			return error;
224	}
225
226	/* NB: override anything set in ah_init0 */
227	sav->tdb_xform = xsp;
228	sav->tdb_encalgxform = txform;
229
230	/* Initialize crypto session. */
231	bzero(&crie, sizeof (crie));
232	crie.cri_alg = sav->tdb_encalgxform->type;
233	crie.cri_klen = _KEYBITS(sav->key_enc);
234	crie.cri_key = sav->key_enc->key_data;
235	/* XXX Rounds ? */
236
237	if (sav->tdb_authalgxform && sav->tdb_encalgxform) {
238		/* init both auth & enc */
239		crie.cri_next = &cria;
240		error = crypto_newsession(&sav->tdb_cryptoid,
241					  &crie, V_crypto_support);
242	} else if (sav->tdb_encalgxform) {
243		error = crypto_newsession(&sav->tdb_cryptoid,
244					  &crie, V_crypto_support);
245	} else if (sav->tdb_authalgxform) {
246		error = crypto_newsession(&sav->tdb_cryptoid,
247					  &cria, V_crypto_support);
248	} else {
249		/* XXX cannot happen? */
250		DPRINTF(("%s: no encoding OR authentication xform!\n",
251			__func__));
252		error = EINVAL;
253	}
254	return error;
255}
256
257/*
258 * Paranoia.
259 */
260static int
261esp_zeroize(struct secasvar *sav)
262{
263	/* NB: ah_zerorize free's the crypto session state */
264	int error = ah_zeroize(sav);
265
266	if (sav->key_enc)
267		bzero(sav->key_enc->key_data, _KEYLEN(sav->key_enc));
268	if (sav->iv) {
269		free(sav->iv, M_XDATA);
270		sav->iv = NULL;
271	}
272	sav->tdb_encalgxform = NULL;
273	sav->tdb_xform = NULL;
274	return error;
275}
276
277/*
278 * ESP input processing, called (eventually) through the protocol switch.
279 */
280static int
281esp_input(struct mbuf *m, struct secasvar *sav, int skip, int protoff)
282{
283	INIT_VNET_IPSEC(curvnet);
284	struct auth_hash *esph;
285	struct enc_xform *espx;
286	struct tdb_ident *tdbi;
287	struct tdb_crypto *tc;
288	int plen, alen, hlen;
289	struct m_tag *mtag;
290	struct newesp *esp;
291
292	struct cryptodesc *crde;
293	struct cryptop *crp;
294
295	IPSEC_ASSERT(sav != NULL, ("null SA"));
296	IPSEC_ASSERT(sav->tdb_encalgxform != NULL, ("null encoding xform"));
297	IPSEC_ASSERT((skip&3) == 0 && (m->m_pkthdr.len&3) == 0,
298		("misaligned packet, skip %u pkt len %u",
299			skip, m->m_pkthdr.len));
300
301	/* XXX don't pullup, just copy header */
302	IP6_EXTHDR_GET(esp, struct newesp *, m, skip, sizeof (struct newesp));
303
304	esph = sav->tdb_authalgxform;
305	espx = sav->tdb_encalgxform;
306
307	/* Determine the ESP header length */
308	if (sav->flags & SADB_X_EXT_OLD)
309		hlen = sizeof (struct esp) + sav->ivlen;
310	else
311		hlen = sizeof (struct newesp) + sav->ivlen;
312	/* Authenticator hash size */
313	alen = esph ? AH_HMAC_HASHLEN : 0;
314
315	/*
316	 * Verify payload length is multiple of encryption algorithm
317	 * block size.
318	 *
319	 * NB: This works for the null algorithm because the blocksize
320	 *     is 4 and all packets must be 4-byte aligned regardless
321	 *     of the algorithm.
322	 */
323	plen = m->m_pkthdr.len - (skip + hlen + alen);
324	if ((plen & (espx->blocksize - 1)) || (plen <= 0)) {
325		DPRINTF(("%s: payload of %d octets not a multiple of %d octets,"
326		    "  SA %s/%08lx\n", __func__,
327		    plen, espx->blocksize,
328		    ipsec_address(&sav->sah->saidx.dst),
329		    (u_long) ntohl(sav->spi)));
330		V_espstat.esps_badilen++;
331		m_freem(m);
332		return EINVAL;
333	}
334
335	/*
336	 * Check sequence number.
337	 */
338	if (esph && sav->replay && !ipsec_chkreplay(ntohl(esp->esp_seq), sav)) {
339		DPRINTF(("%s: packet replay check for %s\n", __func__,
340		    ipsec_logsastr(sav)));	/*XXX*/
341		V_espstat.esps_replay++;
342		m_freem(m);
343		return ENOBUFS;		/*XXX*/
344	}
345
346	/* Update the counters */
347	V_espstat.esps_ibytes += m->m_pkthdr.len - (skip + hlen + alen);
348
349	/* Find out if we've already done crypto */
350	for (mtag = m_tag_find(m, PACKET_TAG_IPSEC_IN_CRYPTO_DONE, NULL);
351	     mtag != NULL;
352	     mtag = m_tag_find(m, PACKET_TAG_IPSEC_IN_CRYPTO_DONE, mtag)) {
353		tdbi = (struct tdb_ident *) (mtag + 1);
354		if (tdbi->proto == sav->sah->saidx.proto &&
355		    tdbi->spi == sav->spi &&
356		    !bcmp(&tdbi->dst, &sav->sah->saidx.dst,
357			  sizeof(union sockaddr_union)))
358			break;
359	}
360
361	/* Get crypto descriptors */
362	crp = crypto_getreq(esph && espx ? 2 : 1);
363	if (crp == NULL) {
364		DPRINTF(("%s: failed to acquire crypto descriptors\n",
365			__func__));
366		V_espstat.esps_crypto++;
367		m_freem(m);
368		return ENOBUFS;
369	}
370
371	/* Get IPsec-specific opaque pointer */
372	if (esph == NULL || mtag != NULL)
373		tc = (struct tdb_crypto *) malloc(sizeof(struct tdb_crypto),
374		    M_XDATA, M_NOWAIT|M_ZERO);
375	else
376		tc = (struct tdb_crypto *) malloc(sizeof(struct tdb_crypto) + alen,
377		    M_XDATA, M_NOWAIT|M_ZERO);
378	if (tc == NULL) {
379		crypto_freereq(crp);
380		DPRINTF(("%s: failed to allocate tdb_crypto\n", __func__));
381		V_espstat.esps_crypto++;
382		m_freem(m);
383		return ENOBUFS;
384	}
385
386	tc->tc_ptr = (caddr_t) mtag;
387
388	if (esph) {
389		struct cryptodesc *crda = crp->crp_desc;
390
391		IPSEC_ASSERT(crda != NULL, ("null ah crypto descriptor"));
392
393		/* Authentication descriptor */
394		crda->crd_skip = skip;
395		crda->crd_len = m->m_pkthdr.len - (skip + alen);
396		crda->crd_inject = m->m_pkthdr.len - alen;
397
398		crda->crd_alg = esph->type;
399		crda->crd_key = sav->key_auth->key_data;
400		crda->crd_klen = _KEYBITS(sav->key_auth);
401
402		/* Copy the authenticator */
403		if (mtag == NULL)
404			m_copydata(m, m->m_pkthdr.len - alen, alen,
405				   (caddr_t) (tc + 1));
406
407		/* Chain authentication request */
408		crde = crda->crd_next;
409	} else {
410		crde = crp->crp_desc;
411	}
412
413	/* Crypto operation descriptor */
414	crp->crp_ilen = m->m_pkthdr.len; /* Total input length */
415	crp->crp_flags = CRYPTO_F_IMBUF | CRYPTO_F_CBIFSYNC;
416	crp->crp_buf = (caddr_t) m;
417	crp->crp_callback = esp_input_cb;
418	crp->crp_sid = sav->tdb_cryptoid;
419	crp->crp_opaque = (caddr_t) tc;
420
421	/* These are passed as-is to the callback */
422	tc->tc_spi = sav->spi;
423	tc->tc_dst = sav->sah->saidx.dst;
424	tc->tc_proto = sav->sah->saidx.proto;
425	tc->tc_protoff = protoff;
426	tc->tc_skip = skip;
427
428	/* Decryption descriptor */
429	if (espx) {
430		IPSEC_ASSERT(crde != NULL, ("null esp crypto descriptor"));
431		crde->crd_skip = skip + hlen;
432		crde->crd_len = m->m_pkthdr.len - (skip + hlen + alen);
433		crde->crd_inject = skip + hlen - sav->ivlen;
434
435		crde->crd_alg = espx->type;
436		crde->crd_key = sav->key_enc->key_data;
437		crde->crd_klen = _KEYBITS(sav->key_enc);
438		/* XXX Rounds ? */
439	}
440
441	if (mtag == NULL)
442		return crypto_dispatch(crp);
443	else
444		return esp_input_cb(crp);
445}
446
447#ifdef INET6
448#define	IPSEC_COMMON_INPUT_CB(m, sav, skip, protoff, mtag) do {		     \
449	if (saidx->dst.sa.sa_family == AF_INET6) {			     \
450		error = ipsec6_common_input_cb(m, sav, skip, protoff, mtag); \
451	} else {							     \
452		error = ipsec4_common_input_cb(m, sav, skip, protoff, mtag); \
453	}								     \
454} while (0)
455#else
456#define	IPSEC_COMMON_INPUT_CB(m, sav, skip, protoff, mtag)		     \
457	(error = ipsec4_common_input_cb(m, sav, skip, protoff, mtag))
458#endif
459
460/*
461 * ESP input callback from the crypto driver.
462 */
463static int
464esp_input_cb(struct cryptop *crp)
465{
466	INIT_VNET_IPSEC(curvnet);
467	u_int8_t lastthree[3], aalg[AH_HMAC_HASHLEN];
468	int hlen, skip, protoff, error;
469	struct mbuf *m;
470	struct cryptodesc *crd;
471	struct auth_hash *esph;
472	struct enc_xform *espx;
473	struct tdb_crypto *tc;
474	struct m_tag *mtag;
475	struct secasvar *sav;
476	struct secasindex *saidx;
477	caddr_t ptr;
478
479	crd = crp->crp_desc;
480	IPSEC_ASSERT(crd != NULL, ("null crypto descriptor!"));
481
482	tc = (struct tdb_crypto *) crp->crp_opaque;
483	IPSEC_ASSERT(tc != NULL, ("null opaque crypto data area!"));
484	skip = tc->tc_skip;
485	protoff = tc->tc_protoff;
486	mtag = (struct m_tag *) tc->tc_ptr;
487	m = (struct mbuf *) crp->crp_buf;
488
489	sav = KEY_ALLOCSA(&tc->tc_dst, tc->tc_proto, tc->tc_spi);
490	if (sav == NULL) {
491		V_espstat.esps_notdb++;
492		DPRINTF(("%s: SA gone during crypto (SA %s/%08lx proto %u)\n",
493		    __func__, ipsec_address(&tc->tc_dst),
494		    (u_long) ntohl(tc->tc_spi), tc->tc_proto));
495		error = ENOBUFS;		/*XXX*/
496		goto bad;
497	}
498
499	saidx = &sav->sah->saidx;
500	IPSEC_ASSERT(saidx->dst.sa.sa_family == AF_INET ||
501		saidx->dst.sa.sa_family == AF_INET6,
502		("unexpected protocol family %u", saidx->dst.sa.sa_family));
503
504	esph = sav->tdb_authalgxform;
505	espx = sav->tdb_encalgxform;
506
507	/* Check for crypto errors */
508	if (crp->crp_etype) {
509		/* Reset the session ID */
510		if (sav->tdb_cryptoid != 0)
511			sav->tdb_cryptoid = crp->crp_sid;
512
513		if (crp->crp_etype == EAGAIN) {
514			KEY_FREESAV(&sav);
515			error = crypto_dispatch(crp);
516			return error;
517		}
518
519		V_espstat.esps_noxform++;
520		DPRINTF(("%s: crypto error %d\n", __func__, crp->crp_etype));
521		error = crp->crp_etype;
522		goto bad;
523	}
524
525	/* Shouldn't happen... */
526	if (m == NULL) {
527		V_espstat.esps_crypto++;
528		DPRINTF(("%s: bogus returned buffer from crypto\n", __func__));
529		error = EINVAL;
530		goto bad;
531	}
532	V_espstat.esps_hist[sav->alg_enc]++;
533
534	/* If authentication was performed, check now. */
535	if (esph != NULL) {
536		/*
537		 * If we have a tag, it means an IPsec-aware NIC did
538		 * the verification for us.  Otherwise we need to
539		 * check the authentication calculation.
540		 */
541		V_ahstat.ahs_hist[sav->alg_auth]++;
542		if (mtag == NULL) {
543			/* Copy the authenticator from the packet */
544			m_copydata(m, m->m_pkthdr.len - AH_HMAC_HASHLEN,
545				AH_HMAC_HASHLEN, aalg);
546
547			ptr = (caddr_t) (tc + 1);
548
549			/* Verify authenticator */
550			if (bcmp(ptr, aalg, AH_HMAC_HASHLEN) != 0) {
551				DPRINTF(("%s: "
552		    "authentication hash mismatch for packet in SA %s/%08lx\n",
553				    __func__,
554				    ipsec_address(&saidx->dst),
555				    (u_long) ntohl(sav->spi)));
556				V_espstat.esps_badauth++;
557				error = EACCES;
558				goto bad;
559			}
560		}
561
562		/* Remove trailing authenticator */
563		m_adj(m, -AH_HMAC_HASHLEN);
564	}
565
566	/* Release the crypto descriptors */
567	free(tc, M_XDATA), tc = NULL;
568	crypto_freereq(crp), crp = NULL;
569
570	/*
571	 * Packet is now decrypted.
572	 */
573	m->m_flags |= M_DECRYPTED;
574
575	/*
576	 * Update replay sequence number, if appropriate.
577	 */
578	if (sav->replay) {
579		u_int32_t seq;
580
581		m_copydata(m, skip + offsetof(struct newesp, esp_seq),
582			   sizeof (seq), (caddr_t) &seq);
583		if (ipsec_updatereplay(ntohl(seq), sav)) {
584			DPRINTF(("%s: packet replay check for %s\n", __func__,
585			    ipsec_logsastr(sav)));
586			V_espstat.esps_replay++;
587			error = ENOBUFS;
588			goto bad;
589		}
590	}
591
592	/* Determine the ESP header length */
593	if (sav->flags & SADB_X_EXT_OLD)
594		hlen = sizeof (struct esp) + sav->ivlen;
595	else
596		hlen = sizeof (struct newesp) + sav->ivlen;
597
598	/* Remove the ESP header and IV from the mbuf. */
599	error = m_striphdr(m, skip, hlen);
600	if (error) {
601		V_espstat.esps_hdrops++;
602		DPRINTF(("%s: bad mbuf chain, SA %s/%08lx\n", __func__,
603		    ipsec_address(&sav->sah->saidx.dst),
604		    (u_long) ntohl(sav->spi)));
605		goto bad;
606	}
607
608	/* Save the last three bytes of decrypted data */
609	m_copydata(m, m->m_pkthdr.len - 3, 3, lastthree);
610
611	/* Verify pad length */
612	if (lastthree[1] + 2 > m->m_pkthdr.len - skip) {
613		V_espstat.esps_badilen++;
614		DPRINTF(("%s: invalid padding length %d for %u byte packet "
615			"in SA %s/%08lx\n", __func__,
616			 lastthree[1], m->m_pkthdr.len - skip,
617			 ipsec_address(&sav->sah->saidx.dst),
618			 (u_long) ntohl(sav->spi)));
619		error = EINVAL;
620		goto bad;
621	}
622
623	/* Verify correct decryption by checking the last padding bytes */
624	if ((sav->flags & SADB_X_EXT_PMASK) != SADB_X_EXT_PRAND) {
625		if (lastthree[1] != lastthree[0] && lastthree[1] != 0) {
626			V_espstat.esps_badenc++;
627			DPRINTF(("%s: decryption failed for packet in "
628				"SA %s/%08lx\n", __func__,
629				ipsec_address(&sav->sah->saidx.dst),
630				(u_long) ntohl(sav->spi)));
631			error = EINVAL;
632			goto bad;
633		}
634	}
635
636	/* Trim the mbuf chain to remove trailing authenticator and padding */
637	m_adj(m, -(lastthree[1] + 2));
638
639	/* Restore the Next Protocol field */
640	m_copyback(m, protoff, sizeof (u_int8_t), lastthree + 2);
641
642	IPSEC_COMMON_INPUT_CB(m, sav, skip, protoff, mtag);
643
644	KEY_FREESAV(&sav);
645	return error;
646bad:
647	if (sav)
648		KEY_FREESAV(&sav);
649	if (m != NULL)
650		m_freem(m);
651	if (tc != NULL)
652		free(tc, M_XDATA);
653	if (crp != NULL)
654		crypto_freereq(crp);
655	return error;
656}
657
658/*
659 * ESP output routine, called by ipsec[46]_process_packet().
660 */
661static int
662esp_output(
663	struct mbuf *m,
664	struct ipsecrequest *isr,
665	struct mbuf **mp,
666	int skip,
667	int protoff
668)
669{
670	INIT_VNET_IPSEC(curvnet);
671	struct enc_xform *espx;
672	struct auth_hash *esph;
673	int hlen, rlen, plen, padding, blks, alen, i, roff;
674	struct mbuf *mo = (struct mbuf *) NULL;
675	struct tdb_crypto *tc;
676	struct secasvar *sav;
677	struct secasindex *saidx;
678	unsigned char *pad;
679	u_int8_t prot;
680	int error, maxpacketsize;
681
682	struct cryptodesc *crde = NULL, *crda = NULL;
683	struct cryptop *crp;
684
685	sav = isr->sav;
686	IPSEC_ASSERT(sav != NULL, ("null SA"));
687	esph = sav->tdb_authalgxform;
688	espx = sav->tdb_encalgxform;
689	IPSEC_ASSERT(espx != NULL, ("null encoding xform"));
690
691	if (sav->flags & SADB_X_EXT_OLD)
692		hlen = sizeof (struct esp) + sav->ivlen;
693	else
694		hlen = sizeof (struct newesp) + sav->ivlen;
695
696	rlen = m->m_pkthdr.len - skip;	/* Raw payload length. */
697	/*
698	 * NB: The null encoding transform has a blocksize of 4
699	 *     so that headers are properly aligned.
700	 */
701	blks = espx->blocksize;		/* IV blocksize */
702
703	/* XXX clamp padding length a la KAME??? */
704	padding = ((blks - ((rlen + 2) % blks)) % blks) + 2;
705	plen = rlen + padding;		/* Padded payload length. */
706
707	if (esph)
708		alen = AH_HMAC_HASHLEN;
709	else
710		alen = 0;
711
712	V_espstat.esps_output++;
713
714	saidx = &sav->sah->saidx;
715	/* Check for maximum packet size violations. */
716	switch (saidx->dst.sa.sa_family) {
717#ifdef INET
718	case AF_INET:
719		maxpacketsize = IP_MAXPACKET;
720		break;
721#endif /* INET */
722#ifdef INET6
723	case AF_INET6:
724		maxpacketsize = IPV6_MAXPACKET;
725		break;
726#endif /* INET6 */
727	default:
728		DPRINTF(("%s: unknown/unsupported protocol "
729		    "family %d, SA %s/%08lx\n", __func__,
730		    saidx->dst.sa.sa_family, ipsec_address(&saidx->dst),
731		    (u_long) ntohl(sav->spi)));
732		V_espstat.esps_nopf++;
733		error = EPFNOSUPPORT;
734		goto bad;
735	}
736	if (skip + hlen + rlen + padding + alen > maxpacketsize) {
737		DPRINTF(("%s: packet in SA %s/%08lx got too big "
738		    "(len %u, max len %u)\n", __func__,
739		    ipsec_address(&saidx->dst), (u_long) ntohl(sav->spi),
740		    skip + hlen + rlen + padding + alen, maxpacketsize));
741		V_espstat.esps_toobig++;
742		error = EMSGSIZE;
743		goto bad;
744	}
745
746	/* Update the counters. */
747	V_espstat.esps_obytes += m->m_pkthdr.len - skip;
748
749	m = m_unshare(m, M_NOWAIT);
750	if (m == NULL) {
751		DPRINTF(("%s: cannot clone mbuf chain, SA %s/%08lx\n", __func__,
752		    ipsec_address(&saidx->dst), (u_long) ntohl(sav->spi)));
753		V_espstat.esps_hdrops++;
754		error = ENOBUFS;
755		goto bad;
756	}
757
758	/* Inject ESP header. */
759	mo = m_makespace(m, skip, hlen, &roff);
760	if (mo == NULL) {
761		DPRINTF(("%s: %u byte ESP hdr inject failed for SA %s/%08lx\n",
762		    __func__, hlen, ipsec_address(&saidx->dst),
763		    (u_long) ntohl(sav->spi)));
764		V_espstat.esps_hdrops++;		/* XXX diffs from openbsd */
765		error = ENOBUFS;
766		goto bad;
767	}
768
769	/* Initialize ESP header. */
770	bcopy((caddr_t) &sav->spi, mtod(mo, caddr_t) + roff, sizeof(u_int32_t));
771	if (sav->replay) {
772		u_int32_t replay;
773
774#ifdef REGRESSION
775		/* Emulate replay attack when ipsec_replay is TRUE. */
776		if (!V_ipsec_replay)
777#endif
778			sav->replay->count++;
779		replay = htonl(sav->replay->count);
780		bcopy((caddr_t) &replay,
781		    mtod(mo, caddr_t) + roff + sizeof(u_int32_t),
782		    sizeof(u_int32_t));
783	}
784
785	/*
786	 * Add padding -- better to do it ourselves than use the crypto engine,
787	 * although if/when we support compression, we'd have to do that.
788	 */
789	pad = (u_char *) m_pad(m, padding + alen);
790	if (pad == NULL) {
791		DPRINTF(("%s: m_pad failed for SA %s/%08lx\n", __func__,
792		    ipsec_address(&saidx->dst), (u_long) ntohl(sav->spi)));
793		m = NULL;		/* NB: free'd by m_pad */
794		error = ENOBUFS;
795		goto bad;
796	}
797
798	/*
799	 * Add padding: random, zero, or self-describing.
800	 * XXX catch unexpected setting
801	 */
802	switch (sav->flags & SADB_X_EXT_PMASK) {
803	case SADB_X_EXT_PRAND:
804		(void) read_random(pad, padding - 2);
805		break;
806	case SADB_X_EXT_PZERO:
807		bzero(pad, padding - 2);
808		break;
809	case SADB_X_EXT_PSEQ:
810		for (i = 0; i < padding - 2; i++)
811			pad[i] = i+1;
812		break;
813	}
814
815	/* Fix padding length and Next Protocol in padding itself. */
816	pad[padding - 2] = padding - 2;
817	m_copydata(m, protoff, sizeof(u_int8_t), pad + padding - 1);
818
819	/* Fix Next Protocol in IPv4/IPv6 header. */
820	prot = IPPROTO_ESP;
821	m_copyback(m, protoff, sizeof(u_int8_t), (u_char *) &prot);
822
823	/* Get crypto descriptors. */
824	crp = crypto_getreq(esph && espx ? 2 : 1);
825	if (crp == NULL) {
826		DPRINTF(("%s: failed to acquire crypto descriptors\n",
827			__func__));
828		V_espstat.esps_crypto++;
829		error = ENOBUFS;
830		goto bad;
831	}
832
833	if (espx) {
834		crde = crp->crp_desc;
835		crda = crde->crd_next;
836
837		/* Encryption descriptor. */
838		crde->crd_skip = skip + hlen;
839		crde->crd_len = m->m_pkthdr.len - (skip + hlen + alen);
840		crde->crd_flags = CRD_F_ENCRYPT;
841		crde->crd_inject = skip + hlen - sav->ivlen;
842
843		/* Encryption operation. */
844		crde->crd_alg = espx->type;
845		crde->crd_key = sav->key_enc->key_data;
846		crde->crd_klen = _KEYBITS(sav->key_enc);
847		/* XXX Rounds ? */
848	} else
849		crda = crp->crp_desc;
850
851	/* IPsec-specific opaque crypto info. */
852	tc = (struct tdb_crypto *) malloc(sizeof(struct tdb_crypto),
853		M_XDATA, M_NOWAIT|M_ZERO);
854	if (tc == NULL) {
855		crypto_freereq(crp);
856		DPRINTF(("%s: failed to allocate tdb_crypto\n", __func__));
857		V_espstat.esps_crypto++;
858		error = ENOBUFS;
859		goto bad;
860	}
861
862	/* Callback parameters */
863	tc->tc_isr = isr;
864	tc->tc_spi = sav->spi;
865	tc->tc_dst = saidx->dst;
866	tc->tc_proto = saidx->proto;
867
868	/* Crypto operation descriptor. */
869	crp->crp_ilen = m->m_pkthdr.len; /* Total input length. */
870	crp->crp_flags = CRYPTO_F_IMBUF | CRYPTO_F_CBIFSYNC;
871	crp->crp_buf = (caddr_t) m;
872	crp->crp_callback = esp_output_cb;
873	crp->crp_opaque = (caddr_t) tc;
874	crp->crp_sid = sav->tdb_cryptoid;
875
876	if (esph) {
877		/* Authentication descriptor. */
878		crda->crd_skip = skip;
879		crda->crd_len = m->m_pkthdr.len - (skip + alen);
880		crda->crd_inject = m->m_pkthdr.len - alen;
881
882		/* Authentication operation. */
883		crda->crd_alg = esph->type;
884		crda->crd_key = sav->key_auth->key_data;
885		crda->crd_klen = _KEYBITS(sav->key_auth);
886	}
887
888	return crypto_dispatch(crp);
889bad:
890	if (m)
891		m_freem(m);
892	return (error);
893}
894
895/*
896 * ESP output callback from the crypto driver.
897 */
898static int
899esp_output_cb(struct cryptop *crp)
900{
901	INIT_VNET_IPSEC(curvnet);
902	struct tdb_crypto *tc;
903	struct ipsecrequest *isr;
904	struct secasvar *sav;
905	struct mbuf *m;
906	int err, error;
907
908	tc = (struct tdb_crypto *) crp->crp_opaque;
909	IPSEC_ASSERT(tc != NULL, ("null opaque data area!"));
910	m = (struct mbuf *) crp->crp_buf;
911
912	isr = tc->tc_isr;
913	IPSECREQUEST_LOCK(isr);
914	sav = KEY_ALLOCSA(&tc->tc_dst, tc->tc_proto, tc->tc_spi);
915	if (sav == NULL) {
916		V_espstat.esps_notdb++;
917		DPRINTF(("%s: SA gone during crypto (SA %s/%08lx proto %u)\n",
918		    __func__, ipsec_address(&tc->tc_dst),
919		    (u_long) ntohl(tc->tc_spi), tc->tc_proto));
920		error = ENOBUFS;		/*XXX*/
921		goto bad;
922	}
923	IPSEC_ASSERT(isr->sav == sav,
924		("SA changed was %p now %p\n", isr->sav, sav));
925
926	/* Check for crypto errors. */
927	if (crp->crp_etype) {
928		/* Reset session ID. */
929		if (sav->tdb_cryptoid != 0)
930			sav->tdb_cryptoid = crp->crp_sid;
931
932		if (crp->crp_etype == EAGAIN) {
933			KEY_FREESAV(&sav);
934			IPSECREQUEST_UNLOCK(isr);
935			error = crypto_dispatch(crp);
936			return error;
937		}
938
939		V_espstat.esps_noxform++;
940		DPRINTF(("%s: crypto error %d\n", __func__, crp->crp_etype));
941		error = crp->crp_etype;
942		goto bad;
943	}
944
945	/* Shouldn't happen... */
946	if (m == NULL) {
947		V_espstat.esps_crypto++;
948		DPRINTF(("%s: bogus returned buffer from crypto\n", __func__));
949		error = EINVAL;
950		goto bad;
951	}
952	V_espstat.esps_hist[sav->alg_enc]++;
953	if (sav->tdb_authalgxform != NULL)
954		V_ahstat.ahs_hist[sav->alg_auth]++;
955
956	/* Release crypto descriptors. */
957	free(tc, M_XDATA);
958	crypto_freereq(crp);
959
960#ifdef REGRESSION
961	/* Emulate man-in-the-middle attack when ipsec_integrity is TRUE. */
962	if (V_ipsec_integrity) {
963		static unsigned char ipseczeroes[AH_HMAC_HASHLEN];
964		struct auth_hash *esph;
965
966		/*
967		 * Corrupt HMAC if we want to test integrity verification of
968		 * the other side.
969		 */
970		esph = sav->tdb_authalgxform;
971		if (esph !=  NULL) {
972			m_copyback(m, m->m_pkthdr.len - AH_HMAC_HASHLEN,
973			    AH_HMAC_HASHLEN, ipseczeroes);
974		}
975	}
976#endif
977
978	/* NB: m is reclaimed by ipsec_process_done. */
979	err = ipsec_process_done(m, isr);
980	KEY_FREESAV(&sav);
981	IPSECREQUEST_UNLOCK(isr);
982	return err;
983bad:
984	if (sav)
985		KEY_FREESAV(&sav);
986	IPSECREQUEST_UNLOCK(isr);
987	if (m)
988		m_freem(m);
989	free(tc, M_XDATA);
990	crypto_freereq(crp);
991	return error;
992}
993
994static struct xformsw esp_xformsw = {
995	XF_ESP,		XFT_CONF|XFT_AUTH,	"IPsec ESP",
996	esp_init,	esp_zeroize,		esp_input,
997	esp_output
998};
999
1000static void
1001esp_attach(void)
1002{
1003
1004	xform_register(&esp_xformsw);
1005#ifndef VIMAGE_GLOBALS
1006	vnet_mod_register(&vnet_esp_modinfo);
1007#else
1008	esp_iattach(NULL);
1009#endif
1010}
1011
1012static int
1013esp_iattach(const void *unused __unused)
1014{
1015	INIT_VNET_IPSEC(curvnet);
1016
1017#define	MAXIV(xform)					\
1018	if (xform.blocksize > V_esp_max_ivlen)		\
1019		V_esp_max_ivlen = xform.blocksize	\
1020
1021	V_esp_enable = 1;
1022	V_esp_max_ivlen = 0;
1023
1024	MAXIV(enc_xform_des);		/* SADB_EALG_DESCBC */
1025	MAXIV(enc_xform_3des);		/* SADB_EALG_3DESCBC */
1026	MAXIV(enc_xform_rijndael128);	/* SADB_X_EALG_AES */
1027	MAXIV(enc_xform_blf);		/* SADB_X_EALG_BLOWFISHCBC */
1028	MAXIV(enc_xform_cast5);		/* SADB_X_EALG_CAST128CBC */
1029	MAXIV(enc_xform_skipjack);	/* SADB_X_EALG_SKIPJACK */
1030	MAXIV(enc_xform_null);		/* SADB_EALG_NULL */
1031	MAXIV(enc_xform_camellia);	/* SADB_X_EALG_CAMELLIACBC */
1032#undef MAXIV
1033
1034	return (0);
1035}
1036SYSINIT(esp_xform_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE, esp_attach, NULL);
1037