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