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