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