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