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