xref: /netbsd-src/sys/netipsec/xform_esp.c (revision ce2c90c7c172d95d2402a5b3d96d8f8e6d138a21)
1 /*	$NetBSD: xform_esp.c,v 1.11 2006/10/13 20:53:59 christos 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.11 2006/10/13 20:53:59 christos 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_SECA, 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 	/*
572 	 * Update replay sequence number, if appropriate.
573 	 */
574 	if (sav->replay) {
575 		u_int32_t seq;
576 
577 		m_copydata(m, skip + offsetof(struct newesp, esp_seq),
578 		    sizeof (seq), (caddr_t) &seq);
579 		if (ipsec_updatereplay(ntohl(seq), sav)) {
580 			DPRINTF(("%s: packet replay check for %s\n", __func__,
581 			    ipsec_logsastr(sav)));
582 			espstat.esps_replay++;
583 			error = ENOBUFS;
584 			goto bad;
585 		}
586 	}
587 
588 	/* Determine the ESP header length */
589 	if (sav->flags & SADB_X_EXT_OLD)
590 		hlen = sizeof (struct esp) + sav->ivlen;
591 	else
592 		hlen = sizeof (struct newesp) + sav->ivlen;
593 
594 	/* Remove the ESP header and IV from the mbuf. */
595 	error = m_striphdr(m, skip, hlen);
596 	if (error) {
597 		espstat.esps_hdrops++;
598 		DPRINTF(("esp_input_cb: bad mbuf chain, SA %s/%08lx\n",
599 		    ipsec_address(&sav->sah->saidx.dst),
600 		    (u_long) ntohl(sav->spi)));
601 		goto bad;
602 	}
603 
604 	/* Save the last three bytes of decrypted data */
605 	m_copydata(m, m->m_pkthdr.len - 3, 3, lastthree);
606 
607 	/* Verify pad length */
608 	if (lastthree[1] + 2 > m->m_pkthdr.len - skip) {
609 		espstat.esps_badilen++;
610 		DPRINTF(("esp_input_cb: invalid padding length %d "
611 			 "for %u byte packet in SA %s/%08lx\n",
612 			 lastthree[1], m->m_pkthdr.len - skip,
613 			 ipsec_address(&sav->sah->saidx.dst),
614 			 (u_long) ntohl(sav->spi)));
615 		error = EINVAL;
616 		goto bad;
617 	}
618 
619 	/* Verify correct decryption by checking the last padding bytes */
620 	if ((sav->flags & SADB_X_EXT_PMASK) != SADB_X_EXT_PRAND) {
621 		if (lastthree[1] != lastthree[0] && lastthree[1] != 0) {
622 			espstat.esps_badenc++;
623 			DPRINTF(("esp_input_cb: decryption failed "
624 				"for packet in SA %s/%08lx\n",
625 				ipsec_address(&sav->sah->saidx.dst),
626 				(u_long) ntohl(sav->spi)));
627 DPRINTF(("esp_input_cb: %x %x\n", lastthree[0], lastthree[1]));
628 			error = EINVAL;
629 			goto bad;
630 		}
631 	}
632 
633 	/* Trim the mbuf chain to remove trailing authenticator and padding */
634 	m_adj(m, -(lastthree[1] + 2));
635 
636 	/* Restore the Next Protocol field */
637 	m = m_copyback_cow(m, protoff, sizeof (u_int8_t), lastthree + 2,
638 			   M_DONTWAIT);
639 
640 	if (m == NULL) {
641 		espstat.esps_crypto++;
642 		DPRINTF(("esp_input_cb: failed to allocate mbuf\n"));
643 		error = ENOBUFS;
644 		goto bad;
645 	}
646 
647 	IPSEC_COMMON_INPUT_CB(m, sav, skip, protoff, mtag);
648 
649 	KEY_FREESAV(&sav);
650 	splx(s);
651 	return error;
652 bad:
653 	if (sav)
654 		KEY_FREESAV(&sav);
655 	splx(s);
656 	if (m != NULL)
657 		m_freem(m);
658 	if (tc != NULL)
659 		free(tc, M_XDATA);
660 	if (crp != NULL)
661 		crypto_freereq(crp);
662 	return error;
663 }
664 
665 /*
666  * ESP output routine, called by ipsec[46]_process_packet().
667  */
668 static int
669 esp_output(
670     struct mbuf *m,
671     struct ipsecrequest *isr,
672     struct mbuf **mp __unused,
673     int skip,
674     int protoff
675 )
676 {
677 	struct enc_xform *espx;
678 	struct auth_hash *esph;
679 	int hlen, rlen, plen, padding, blks, alen, i, roff;
680 	struct mbuf *mo = (struct mbuf *) NULL;
681 	struct tdb_crypto *tc;
682 	struct secasvar *sav;
683 	struct secasindex *saidx;
684 	unsigned char *pad;
685 	u_int8_t prot;
686 	int error, maxpacketsize;
687 
688 	struct cryptodesc *crde = NULL, *crda = NULL;
689 	struct cryptop *crp;
690 
691 	IPSEC_SPLASSERT_SOFTNET("esp_output");
692 
693 	sav = isr->sav;
694 	IPSEC_ASSERT(sav != NULL, ("esp_output: null SA"));
695 	esph = sav->tdb_authalgxform;
696 	espx = sav->tdb_encalgxform;
697 	IPSEC_ASSERT(espx != NULL, ("esp_output: null encoding xform"));
698 
699 	if (sav->flags & SADB_X_EXT_OLD)
700 		hlen = sizeof (struct esp) + sav->ivlen;
701 	else
702 		hlen = sizeof (struct newesp) + sav->ivlen;
703 
704 	rlen = m->m_pkthdr.len - skip;	/* Raw payload length. */
705 	/*
706 	 * NB: The null encoding transform has a blocksize of 4
707 	 *     so that headers are properly aligned.
708 	 */
709 	blks = espx->blocksize;		/* IV blocksize */
710 
711 	/* XXX clamp padding length a la KAME??? */
712 	padding = ((blks - ((rlen + 2) % blks)) % blks) + 2;
713 	plen = rlen + padding;		/* Padded payload length. */
714 
715 	if (esph)
716 		alen = AH_HMAC_HASHLEN;
717 	else
718 		alen = 0;
719 
720 	espstat.esps_output++;
721 
722 	saidx = &sav->sah->saidx;
723 	/* Check for maximum packet size violations. */
724 	switch (saidx->dst.sa.sa_family) {
725 #ifdef INET
726 	case AF_INET:
727 		maxpacketsize = IP_MAXPACKET;
728 		break;
729 #endif /* INET */
730 #ifdef INET6
731 	case AF_INET6:
732 		maxpacketsize = IPV6_MAXPACKET;
733 		break;
734 #endif /* INET6 */
735 	default:
736 		DPRINTF(("esp_output: unknown/unsupported protocol "
737 		    "family %d, SA %s/%08lx\n",
738 		    saidx->dst.sa.sa_family, ipsec_address(&saidx->dst),
739 		    (u_long) ntohl(sav->spi)));
740 		espstat.esps_nopf++;
741 		error = EPFNOSUPPORT;
742 		goto bad;
743 	}
744 	if (skip + hlen + rlen + padding + alen > maxpacketsize) {
745 		DPRINTF(("esp_output: packet in SA %s/%08lx got too big "
746 		    "(len %u, max len %u)\n",
747 		    ipsec_address(&saidx->dst), (u_long) ntohl(sav->spi),
748 		    skip + hlen + rlen + padding + alen, maxpacketsize));
749 		espstat.esps_toobig++;
750 		error = EMSGSIZE;
751 		goto bad;
752 	}
753 
754 	/* Update the counters. */
755 	espstat.esps_obytes += m->m_pkthdr.len - skip;
756 
757 	m = m_clone(m);
758 	if (m == NULL) {
759 		DPRINTF(("esp_output: cannot clone mbuf chain, SA %s/%08lx\n",
760 		    ipsec_address(&saidx->dst), (u_long) ntohl(sav->spi)));
761 		espstat.esps_hdrops++;
762 		error = ENOBUFS;
763 		goto bad;
764 	}
765 
766 	/* Inject ESP header. */
767 	mo = m_makespace(m, skip, hlen, &roff);
768 	if (mo == NULL) {
769 		DPRINTF(("esp_output: failed to inject %u byte ESP hdr for SA "
770 		    "%s/%08lx\n",
771 		    hlen, ipsec_address(&saidx->dst),
772 		    (u_long) ntohl(sav->spi)));
773 		espstat.esps_hdrops++;		/* XXX diffs from openbsd */
774 		error = ENOBUFS;
775 		goto bad;
776 	}
777 
778 	/* Initialize ESP header. */
779 	bcopy((caddr_t) &sav->spi, mtod(mo, caddr_t) + roff, sizeof(u_int32_t));
780 	if (sav->replay) {
781 		u_int32_t replay;
782 
783 #ifdef IPSEC_DEBUG
784 		/* Emulate replay attack when ipsec_replay is TRUE. */
785 		if (!ipsec_replay)
786 #endif
787 			sav->replay->count++;
788 
789 		replay = htonl(sav->replay->count);
790 		bcopy((caddr_t) &replay,
791 		    mtod(mo, caddr_t) + roff + sizeof(u_int32_t),
792 		    sizeof(u_int32_t));
793 	}
794 
795 	/*
796 	 * Add padding -- better to do it ourselves than use the crypto engine,
797 	 * although if/when we support compression, we'd have to do that.
798 	 */
799 	pad = (u_char *) m_pad(m, padding + alen);
800 	if (pad == NULL) {
801 		DPRINTF(("esp_output: m_pad failed for SA %s/%08lx\n",
802 		    ipsec_address(&saidx->dst), (u_long) ntohl(sav->spi)));
803 		m = NULL;		/* NB: free'd by m_pad */
804 		error = ENOBUFS;
805 		goto bad;
806 	}
807 
808 	/*
809 	 * Add padding: random, zero, or self-describing.
810 	 * XXX catch unexpected setting
811 	 */
812 	switch (sav->flags & SADB_X_EXT_PMASK) {
813 	case SADB_X_EXT_PRAND:
814 		(void) read_random(pad, padding - 2);
815 		break;
816 	case SADB_X_EXT_PZERO:
817 		bzero(pad, padding - 2);
818 		break;
819 	case SADB_X_EXT_PSEQ:
820 		for (i = 0; i < padding - 2; i++)
821 			pad[i] = i+1;
822 		break;
823 	}
824 
825 	/* Fix padding length and Next Protocol in padding itself. */
826 	pad[padding - 2] = padding - 2;
827 	m_copydata(m, protoff, sizeof(u_int8_t), pad + padding - 1);
828 
829 	/* Fix Next Protocol in IPv4/IPv6 header. */
830 	prot = IPPROTO_ESP;
831 	m_copyback(m, protoff, sizeof(u_int8_t), (u_char *) &prot);
832 
833 	/* Get crypto descriptors. */
834 	crp = crypto_getreq(esph && espx ? 2 : 1);
835 	if (crp == NULL) {
836 		DPRINTF(("esp_output: failed to acquire crypto descriptors\n"));
837 		espstat.esps_crypto++;
838 		error = ENOBUFS;
839 		goto bad;
840 	}
841 
842 	if (espx) {
843 		crde = crp->crp_desc;
844 		crda = crde->crd_next;
845 
846 		/* Encryption descriptor. */
847 		crde->crd_skip = skip + hlen;
848 		crde->crd_len = m->m_pkthdr.len - (skip + hlen + alen);
849 		crde->crd_flags = CRD_F_ENCRYPT;
850 		crde->crd_inject = skip + hlen - sav->ivlen;
851 
852 		/* Encryption operation. */
853 		crde->crd_alg = espx->type;
854 		crde->crd_key = _KEYBUF(sav->key_enc);
855 		crde->crd_klen = _KEYBITS(sav->key_enc);
856 		/* XXX Rounds ? */
857 	} else
858 		crda = crp->crp_desc;
859 
860 	/* IPsec-specific opaque crypto info. */
861 	tc = (struct tdb_crypto *) malloc(sizeof(struct tdb_crypto),
862 		M_XDATA, M_NOWAIT|M_ZERO);
863 	if (tc == NULL) {
864 		crypto_freereq(crp);
865 		DPRINTF(("esp_output: failed to allocate tdb_crypto\n"));
866 		espstat.esps_crypto++;
867 		error = ENOBUFS;
868 		goto bad;
869 	}
870 
871 	/* Callback parameters */
872 	tc->tc_isr = isr;
873 	tc->tc_spi = sav->spi;
874 	tc->tc_dst = saidx->dst;
875 	tc->tc_proto = saidx->proto;
876 
877 	/* Crypto operation descriptor. */
878 	crp->crp_ilen = m->m_pkthdr.len; /* Total input length. */
879 	crp->crp_flags = CRYPTO_F_IMBUF;
880 	crp->crp_buf = (caddr_t) m;
881 	crp->crp_callback = esp_output_cb;
882 	crp->crp_opaque = (caddr_t) tc;
883 	crp->crp_sid = sav->tdb_cryptoid;
884 
885 	if (esph) {
886 		/* Authentication descriptor. */
887 		crda->crd_skip = skip;
888 		crda->crd_len = m->m_pkthdr.len - (skip + alen);
889 		crda->crd_inject = m->m_pkthdr.len - alen;
890 
891 		/* Authentication operation. */
892 		crda->crd_alg = esph->type;
893 		crda->crd_key = _KEYBUF(sav->key_auth);
894 		crda->crd_klen = _KEYBITS(sav->key_auth);
895 	}
896 
897 	return crypto_dispatch(crp);
898 bad:
899 	if (m)
900 		m_freem(m);
901 	return (error);
902 }
903 
904 /*
905  * ESP output callback from the crypto driver.
906  */
907 static int
908 esp_output_cb(struct cryptop *crp)
909 {
910 	struct tdb_crypto *tc;
911 	struct ipsecrequest *isr;
912 	struct secasvar *sav;
913 	struct mbuf *m;
914 	int s, err, error;
915 
916 	tc = (struct tdb_crypto *) crp->crp_opaque;
917 	IPSEC_ASSERT(tc != NULL, ("esp_output_cb: null opaque data area!"));
918 	m = (struct mbuf *) crp->crp_buf;
919 
920 	s = splsoftnet();
921 
922 	isr = tc->tc_isr;
923 	sav = KEY_ALLOCSA(&tc->tc_dst, tc->tc_proto, tc->tc_spi);
924 	if (sav == NULL) {
925 		espstat.esps_notdb++;
926 		DPRINTF(("esp_output_cb: SA expired while in crypto "
927 		    "(SA %s/%08lx proto %u)\n", ipsec_address(&tc->tc_dst),
928 		    (u_long) ntohl(tc->tc_spi), tc->tc_proto));
929 		error = ENOBUFS;		/*XXX*/
930 		goto bad;
931 	}
932 	IPSEC_ASSERT(isr->sav == sav,
933 		("esp_output_cb: SA changed was %p now %p\n", isr->sav, sav));
934 
935 	/* Check for crypto errors. */
936 	if (crp->crp_etype) {
937 		/* Reset session ID. */
938 		if (sav->tdb_cryptoid != 0)
939 			sav->tdb_cryptoid = crp->crp_sid;
940 
941 		if (crp->crp_etype == EAGAIN) {
942 			KEY_FREESAV(&sav);
943 			splx(s);
944 			return crypto_dispatch(crp);
945 		}
946 
947 		espstat.esps_noxform++;
948 		DPRINTF(("esp_output_cb: crypto error %d\n", crp->crp_etype));
949 		error = crp->crp_etype;
950 		goto bad;
951 	}
952 
953 	/* Shouldn't happen... */
954 	if (m == NULL) {
955 		espstat.esps_crypto++;
956 		DPRINTF(("esp_output_cb: bogus returned buffer from crypto\n"));
957 		error = EINVAL;
958 		goto bad;
959 	}
960 	espstat.esps_hist[sav->alg_enc]++;
961 	if (sav->tdb_authalgxform != NULL)
962 		ahstat.ahs_hist[sav->alg_auth]++;
963 
964 	/* Release crypto descriptors. */
965 	free(tc, M_XDATA);
966 	crypto_freereq(crp);
967 
968 #ifdef IPSEC_DEBUG
969 	/* Emulate man-in-the-middle attack when ipsec_integrity is TRUE. */
970 	if (ipsec_integrity) {
971 		static unsigned char ipseczeroes[AH_HMAC_HASHLEN];
972 		struct auth_hash *esph;
973 
974 		/*
975 		 * Corrupt HMAC if we want to test integrity verification of
976 		 * the other side.
977 		 */
978 		esph = sav->tdb_authalgxform;
979 		if (esph !=  NULL) {
980 			m_copyback(m, m->m_pkthdr.len - AH_HMAC_HASHLEN,
981 			    AH_HMAC_HASHLEN, ipseczeroes);
982 		}
983 	}
984 #endif
985 
986 	/* NB: m is reclaimed by ipsec_process_done. */
987 	err = ipsec_process_done(m, isr);
988 	KEY_FREESAV(&sav);
989 	splx(s);
990 	return err;
991 bad:
992 	if (sav)
993 		KEY_FREESAV(&sav);
994 	splx(s);
995 	if (m)
996 		m_freem(m);
997 	free(tc, M_XDATA);
998 	crypto_freereq(crp);
999 	return error;
1000 }
1001 
1002 static struct xformsw esp_xformsw = {
1003 	XF_ESP,		XFT_CONF|XFT_AUTH,	"IPsec ESP",
1004 	esp_init,	esp_zeroize,		esp_input,
1005 	esp_output,
1006 	NULL,
1007 };
1008 
1009 INITFN void
1010 esp_attach(void)
1011 {
1012 #define	MAXIV(xform)					\
1013 	if (xform.blocksize > esp_max_ivlen)		\
1014 		esp_max_ivlen = xform.blocksize		\
1015 
1016 	esp_max_ivlen = 0;
1017 	MAXIV(enc_xform_des);		/* SADB_EALG_DESCBC */
1018 	MAXIV(enc_xform_3des);		/* SADB_EALG_3DESCBC */
1019 	MAXIV(enc_xform_rijndael128);	/* SADB_X_EALG_AES */
1020 	MAXIV(enc_xform_blf);		/* SADB_X_EALG_BLOWFISHCBC */
1021 	MAXIV(enc_xform_cast5);		/* SADB_X_EALG_CAST128CBC */
1022 	MAXIV(enc_xform_skipjack);	/* SADB_X_EALG_SKIPJACK */
1023 	MAXIV(enc_xform_null);		/* SADB_EALG_NULL */
1024 
1025 	xform_register(&esp_xformsw);
1026 #undef MAXIV
1027 }
1028 #ifdef __FreeBSD__
1029 SYSINIT(esp_xform_init, SI_SUB_DRIVERS, SI_ORDER_FIRST, esp_attach, NULL)
1030 #else
1031 #endif
1032