xref: /freebsd/sys/netipsec/xform_esp.c (revision 721351876cd4d3a8a700f62d2061331fa951a488)
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 	case SADB_X_EALG_CAMELLIACBC:
117 		return &enc_xform_camellia;
118 	}
119 	return NULL;
120 }
121 
122 size_t
123 esp_hdrsiz(struct secasvar *sav)
124 {
125 	size_t size;
126 
127 	if (sav != NULL) {
128 		/*XXX not right for null algorithm--does it matter??*/
129 		IPSEC_ASSERT(sav->tdb_encalgxform != NULL,
130 			("SA with null xform"));
131 		if (sav->flags & SADB_X_EXT_OLD)
132 			size = sizeof (struct esp);
133 		else
134 			size = sizeof (struct newesp);
135 		size += sav->tdb_encalgxform->blocksize + 9;
136 		/*XXX need alg check???*/
137 		if (sav->tdb_authalgxform != NULL && sav->replay)
138 			size += ah_hdrsiz(sav);
139 	} else {
140 		/*
141 		 *   base header size
142 		 * + max iv length for CBC mode
143 		 * + max pad length
144 		 * + sizeof (pad length field)
145 		 * + sizeof (next header field)
146 		 * + max icv supported.
147 		 */
148 		size = sizeof (struct newesp) + esp_max_ivlen + 9 + 16;
149 	}
150 	return size;
151 }
152 
153 /*
154  * esp_init() is called when an SPI is being set up.
155  */
156 static int
157 esp_init(struct secasvar *sav, struct xformsw *xsp)
158 {
159 	struct enc_xform *txform;
160 	struct cryptoini cria, crie;
161 	int keylen;
162 	int error;
163 
164 	txform = esp_algorithm_lookup(sav->alg_enc);
165 	if (txform == NULL) {
166 		DPRINTF(("%s: unsupported encryption algorithm %d\n",
167 			__func__, sav->alg_enc));
168 		return EINVAL;
169 	}
170 	if (sav->key_enc == NULL) {
171 		DPRINTF(("%s: no encoding key for %s algorithm\n",
172 			 __func__, txform->name));
173 		return EINVAL;
174 	}
175 	if ((sav->flags&(SADB_X_EXT_OLD|SADB_X_EXT_IV4B)) == SADB_X_EXT_IV4B) {
176 		DPRINTF(("%s: 4-byte IV not supported with protocol\n",
177 			__func__));
178 		return EINVAL;
179 	}
180 	keylen = _KEYLEN(sav->key_enc);
181 	if (txform->minkey > keylen || keylen > txform->maxkey) {
182 		DPRINTF(("%s: invalid key length %u, must be in the range "
183 			"[%u..%u] for algorithm %s\n", __func__,
184 			keylen, txform->minkey, txform->maxkey,
185 			txform->name));
186 		return EINVAL;
187 	}
188 
189 	/*
190 	 * NB: The null xform needs a non-zero blocksize to keep the
191 	 *      crypto code happy but if we use it to set ivlen then
192 	 *      the ESP header will be processed incorrectly.  The
193 	 *      compromise is to force it to zero here.
194 	 */
195 	sav->ivlen = (txform == &enc_xform_null ? 0 : txform->blocksize);
196 	sav->iv = (caddr_t) malloc(sav->ivlen, M_XDATA, M_WAITOK);
197 	if (sav->iv == NULL) {
198 		DPRINTF(("%s: no memory for IV\n", __func__));
199 		return EINVAL;
200 	}
201 	key_randomfill(sav->iv, sav->ivlen);	/*XXX*/
202 
203 	/*
204 	 * Setup AH-related state.
205 	 */
206 	if (sav->alg_auth != 0) {
207 		error = ah_init0(sav, xsp, &cria);
208 		if (error)
209 			return error;
210 	}
211 
212 	/* NB: override anything set in ah_init0 */
213 	sav->tdb_xform = xsp;
214 	sav->tdb_encalgxform = txform;
215 
216 	/* Initialize crypto session. */
217 	bzero(&crie, sizeof (crie));
218 	crie.cri_alg = sav->tdb_encalgxform->type;
219 	crie.cri_klen = _KEYBITS(sav->key_enc);
220 	crie.cri_key = sav->key_enc->key_data;
221 	/* XXX Rounds ? */
222 
223 	if (sav->tdb_authalgxform && sav->tdb_encalgxform) {
224 		/* init both auth & enc */
225 		crie.cri_next = &cria;
226 		error = crypto_newsession(&sav->tdb_cryptoid,
227 					  &crie, crypto_support);
228 	} else if (sav->tdb_encalgxform) {
229 		error = crypto_newsession(&sav->tdb_cryptoid,
230 					  &crie, crypto_support);
231 	} else if (sav->tdb_authalgxform) {
232 		error = crypto_newsession(&sav->tdb_cryptoid,
233 					  &cria, crypto_support);
234 	} else {
235 		/* XXX cannot happen? */
236 		DPRINTF(("%s: no encoding OR authentication xform!\n",
237 			__func__));
238 		error = EINVAL;
239 	}
240 	return error;
241 }
242 
243 /*
244  * Paranoia.
245  */
246 static int
247 esp_zeroize(struct secasvar *sav)
248 {
249 	/* NB: ah_zerorize free's the crypto session state */
250 	int error = ah_zeroize(sav);
251 
252 	if (sav->key_enc)
253 		bzero(sav->key_enc->key_data, _KEYLEN(sav->key_enc));
254 	if (sav->iv) {
255 		free(sav->iv, M_XDATA);
256 		sav->iv = NULL;
257 	}
258 	sav->tdb_encalgxform = NULL;
259 	sav->tdb_xform = NULL;
260 	return error;
261 }
262 
263 /*
264  * ESP input processing, called (eventually) through the protocol switch.
265  */
266 static int
267 esp_input(struct mbuf *m, struct secasvar *sav, int skip, int protoff)
268 {
269 	struct auth_hash *esph;
270 	struct enc_xform *espx;
271 	struct tdb_ident *tdbi;
272 	struct tdb_crypto *tc;
273 	int plen, alen, hlen;
274 	struct m_tag *mtag;
275 	struct newesp *esp;
276 
277 	struct cryptodesc *crde;
278 	struct cryptop *crp;
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 = sav->key_auth->key_data;
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 = sav->key_enc->key_data;
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 			error = crypto_dispatch(crp);
500 			return error;
501 		}
502 
503 		espstat.esps_noxform++;
504 		DPRINTF(("%s: crypto error %d\n", __func__, crp->crp_etype));
505 		error = crp->crp_etype;
506 		goto bad;
507 	}
508 
509 	/* Shouldn't happen... */
510 	if (m == NULL) {
511 		espstat.esps_crypto++;
512 		DPRINTF(("%s: bogus returned buffer from crypto\n", __func__));
513 		error = EINVAL;
514 		goto bad;
515 	}
516 	espstat.esps_hist[sav->alg_enc]++;
517 
518 	/* If authentication was performed, check now. */
519 	if (esph != NULL) {
520 		/*
521 		 * If we have a tag, it means an IPsec-aware NIC did
522 		 * the verification for us.  Otherwise we need to
523 		 * check the authentication calculation.
524 		 */
525 		ahstat.ahs_hist[sav->alg_auth]++;
526 		if (mtag == NULL) {
527 			/* Copy the authenticator from the packet */
528 			m_copydata(m, m->m_pkthdr.len - AH_HMAC_HASHLEN,
529 				AH_HMAC_HASHLEN, aalg);
530 
531 			ptr = (caddr_t) (tc + 1);
532 
533 			/* Verify authenticator */
534 			if (bcmp(ptr, aalg, AH_HMAC_HASHLEN) != 0) {
535 				DPRINTF(("%s: "
536 		    "authentication hash mismatch for packet in SA %s/%08lx\n",
537 				    __func__,
538 				    ipsec_address(&saidx->dst),
539 				    (u_long) ntohl(sav->spi)));
540 				espstat.esps_badauth++;
541 				error = EACCES;
542 				goto bad;
543 			}
544 		}
545 
546 		/* Remove trailing authenticator */
547 		m_adj(m, -AH_HMAC_HASHLEN);
548 	}
549 
550 	/* Release the crypto descriptors */
551 	free(tc, M_XDATA), tc = NULL;
552 	crypto_freereq(crp), crp = NULL;
553 
554 	/*
555 	 * Packet is now decrypted.
556 	 */
557 	m->m_flags |= M_DECRYPTED;
558 
559 	/*
560 	 * Update replay sequence number, if appropriate.
561 	 */
562 	if (sav->replay) {
563 		u_int32_t seq;
564 
565 		m_copydata(m, skip + offsetof(struct newesp, esp_seq),
566 			   sizeof (seq), (caddr_t) &seq);
567 		if (ipsec_updatereplay(ntohl(seq), sav)) {
568 			DPRINTF(("%s: packet replay check for %s\n", __func__,
569 			    ipsec_logsastr(sav)));
570 			espstat.esps_replay++;
571 			error = ENOBUFS;
572 			goto bad;
573 		}
574 	}
575 
576 	/* Determine the ESP header length */
577 	if (sav->flags & SADB_X_EXT_OLD)
578 		hlen = sizeof (struct esp) + sav->ivlen;
579 	else
580 		hlen = sizeof (struct newesp) + sav->ivlen;
581 
582 	/* Remove the ESP header and IV from the mbuf. */
583 	error = m_striphdr(m, skip, hlen);
584 	if (error) {
585 		espstat.esps_hdrops++;
586 		DPRINTF(("%s: bad mbuf chain, SA %s/%08lx\n", __func__,
587 		    ipsec_address(&sav->sah->saidx.dst),
588 		    (u_long) ntohl(sav->spi)));
589 		goto bad;
590 	}
591 
592 	/* Save the last three bytes of decrypted data */
593 	m_copydata(m, m->m_pkthdr.len - 3, 3, lastthree);
594 
595 	/* Verify pad length */
596 	if (lastthree[1] + 2 > m->m_pkthdr.len - skip) {
597 		espstat.esps_badilen++;
598 		DPRINTF(("%s: invalid padding length %d for %u byte packet "
599 			"in SA %s/%08lx\n", __func__,
600 			 lastthree[1], m->m_pkthdr.len - skip,
601 			 ipsec_address(&sav->sah->saidx.dst),
602 			 (u_long) ntohl(sav->spi)));
603 		error = EINVAL;
604 		goto bad;
605 	}
606 
607 	/* Verify correct decryption by checking the last padding bytes */
608 	if ((sav->flags & SADB_X_EXT_PMASK) != SADB_X_EXT_PRAND) {
609 		if (lastthree[1] != lastthree[0] && lastthree[1] != 0) {
610 			espstat.esps_badenc++;
611 			DPRINTF(("%s: decryption failed for packet in "
612 				"SA %s/%08lx\n", __func__,
613 				ipsec_address(&sav->sah->saidx.dst),
614 				(u_long) ntohl(sav->spi)));
615 			error = EINVAL;
616 			goto bad;
617 		}
618 	}
619 
620 	/* Trim the mbuf chain to remove trailing authenticator and padding */
621 	m_adj(m, -(lastthree[1] + 2));
622 
623 	/* Restore the Next Protocol field */
624 	m_copyback(m, protoff, sizeof (u_int8_t), lastthree + 2);
625 
626 	IPSEC_COMMON_INPUT_CB(m, sav, skip, protoff, mtag);
627 
628 	KEY_FREESAV(&sav);
629 	return error;
630 bad:
631 	if (sav)
632 		KEY_FREESAV(&sav);
633 	if (m != NULL)
634 		m_freem(m);
635 	if (tc != NULL)
636 		free(tc, M_XDATA);
637 	if (crp != NULL)
638 		crypto_freereq(crp);
639 	return error;
640 }
641 
642 /*
643  * ESP output routine, called by ipsec[46]_process_packet().
644  */
645 static int
646 esp_output(
647 	struct mbuf *m,
648 	struct ipsecrequest *isr,
649 	struct mbuf **mp,
650 	int skip,
651 	int protoff
652 )
653 {
654 	struct enc_xform *espx;
655 	struct auth_hash *esph;
656 	int hlen, rlen, plen, padding, blks, alen, i, roff;
657 	struct mbuf *mo = (struct mbuf *) NULL;
658 	struct tdb_crypto *tc;
659 	struct secasvar *sav;
660 	struct secasindex *saidx;
661 	unsigned char *pad;
662 	u_int8_t prot;
663 	int error, maxpacketsize;
664 
665 	struct cryptodesc *crde = NULL, *crda = NULL;
666 	struct cryptop *crp;
667 
668 	sav = isr->sav;
669 	IPSEC_ASSERT(sav != NULL, ("null SA"));
670 	esph = sav->tdb_authalgxform;
671 	espx = sav->tdb_encalgxform;
672 	IPSEC_ASSERT(espx != NULL, ("null encoding xform"));
673 
674 	if (sav->flags & SADB_X_EXT_OLD)
675 		hlen = sizeof (struct esp) + sav->ivlen;
676 	else
677 		hlen = sizeof (struct newesp) + sav->ivlen;
678 
679 	rlen = m->m_pkthdr.len - skip;	/* Raw payload length. */
680 	/*
681 	 * NB: The null encoding transform has a blocksize of 4
682 	 *     so that headers are properly aligned.
683 	 */
684 	blks = espx->blocksize;		/* IV blocksize */
685 
686 	/* XXX clamp padding length a la KAME??? */
687 	padding = ((blks - ((rlen + 2) % blks)) % blks) + 2;
688 	plen = rlen + padding;		/* Padded payload length. */
689 
690 	if (esph)
691 		alen = AH_HMAC_HASHLEN;
692 	else
693 		alen = 0;
694 
695 	espstat.esps_output++;
696 
697 	saidx = &sav->sah->saidx;
698 	/* Check for maximum packet size violations. */
699 	switch (saidx->dst.sa.sa_family) {
700 #ifdef INET
701 	case AF_INET:
702 		maxpacketsize = IP_MAXPACKET;
703 		break;
704 #endif /* INET */
705 #ifdef INET6
706 	case AF_INET6:
707 		maxpacketsize = IPV6_MAXPACKET;
708 		break;
709 #endif /* INET6 */
710 	default:
711 		DPRINTF(("%s: unknown/unsupported protocol "
712 		    "family %d, SA %s/%08lx\n", __func__,
713 		    saidx->dst.sa.sa_family, ipsec_address(&saidx->dst),
714 		    (u_long) ntohl(sav->spi)));
715 		espstat.esps_nopf++;
716 		error = EPFNOSUPPORT;
717 		goto bad;
718 	}
719 	if (skip + hlen + rlen + padding + alen > maxpacketsize) {
720 		DPRINTF(("%s: packet in SA %s/%08lx got too big "
721 		    "(len %u, max len %u)\n", __func__,
722 		    ipsec_address(&saidx->dst), (u_long) ntohl(sav->spi),
723 		    skip + hlen + rlen + padding + alen, maxpacketsize));
724 		espstat.esps_toobig++;
725 		error = EMSGSIZE;
726 		goto bad;
727 	}
728 
729 	/* Update the counters. */
730 	espstat.esps_obytes += m->m_pkthdr.len - skip;
731 
732 	m = m_unshare(m, M_NOWAIT);
733 	if (m == NULL) {
734 		DPRINTF(("%s: cannot clone mbuf chain, SA %s/%08lx\n", __func__,
735 		    ipsec_address(&saidx->dst), (u_long) ntohl(sav->spi)));
736 		espstat.esps_hdrops++;
737 		error = ENOBUFS;
738 		goto bad;
739 	}
740 
741 	/* Inject ESP header. */
742 	mo = m_makespace(m, skip, hlen, &roff);
743 	if (mo == NULL) {
744 		DPRINTF(("%s: %u byte ESP hdr inject failed for SA %s/%08lx\n",
745 		    __func__, hlen, ipsec_address(&saidx->dst),
746 		    (u_long) ntohl(sav->spi)));
747 		espstat.esps_hdrops++;		/* XXX diffs from openbsd */
748 		error = ENOBUFS;
749 		goto bad;
750 	}
751 
752 	/* Initialize ESP header. */
753 	bcopy((caddr_t) &sav->spi, mtod(mo, caddr_t) + roff, sizeof(u_int32_t));
754 	if (sav->replay) {
755 		u_int32_t replay;
756 
757 #ifdef REGRESSION
758 		/* Emulate replay attack when ipsec_replay is TRUE. */
759 		if (!ipsec_replay)
760 #endif
761 			sav->replay->count++;
762 		replay = htonl(sav->replay->count);
763 		bcopy((caddr_t) &replay,
764 		    mtod(mo, caddr_t) + roff + sizeof(u_int32_t),
765 		    sizeof(u_int32_t));
766 	}
767 
768 	/*
769 	 * Add padding -- better to do it ourselves than use the crypto engine,
770 	 * although if/when we support compression, we'd have to do that.
771 	 */
772 	pad = (u_char *) m_pad(m, padding + alen);
773 	if (pad == NULL) {
774 		DPRINTF(("%s: m_pad failed for SA %s/%08lx\n", __func__,
775 		    ipsec_address(&saidx->dst), (u_long) ntohl(sav->spi)));
776 		m = NULL;		/* NB: free'd by m_pad */
777 		error = ENOBUFS;
778 		goto bad;
779 	}
780 
781 	/*
782 	 * Add padding: random, zero, or self-describing.
783 	 * XXX catch unexpected setting
784 	 */
785 	switch (sav->flags & SADB_X_EXT_PMASK) {
786 	case SADB_X_EXT_PRAND:
787 		(void) read_random(pad, padding - 2);
788 		break;
789 	case SADB_X_EXT_PZERO:
790 		bzero(pad, padding - 2);
791 		break;
792 	case SADB_X_EXT_PSEQ:
793 		for (i = 0; i < padding - 2; i++)
794 			pad[i] = i+1;
795 		break;
796 	}
797 
798 	/* Fix padding length and Next Protocol in padding itself. */
799 	pad[padding - 2] = padding - 2;
800 	m_copydata(m, protoff, sizeof(u_int8_t), pad + padding - 1);
801 
802 	/* Fix Next Protocol in IPv4/IPv6 header. */
803 	prot = IPPROTO_ESP;
804 	m_copyback(m, protoff, sizeof(u_int8_t), (u_char *) &prot);
805 
806 	/* Get crypto descriptors. */
807 	crp = crypto_getreq(esph && espx ? 2 : 1);
808 	if (crp == NULL) {
809 		DPRINTF(("%s: failed to acquire crypto descriptors\n",
810 			__func__));
811 		espstat.esps_crypto++;
812 		error = ENOBUFS;
813 		goto bad;
814 	}
815 
816 	if (espx) {
817 		crde = crp->crp_desc;
818 		crda = crde->crd_next;
819 
820 		/* Encryption descriptor. */
821 		crde->crd_skip = skip + hlen;
822 		crde->crd_len = m->m_pkthdr.len - (skip + hlen + alen);
823 		crde->crd_flags = CRD_F_ENCRYPT;
824 		crde->crd_inject = skip + hlen - sav->ivlen;
825 
826 		/* Encryption operation. */
827 		crde->crd_alg = espx->type;
828 		crde->crd_key = sav->key_enc->key_data;
829 		crde->crd_klen = _KEYBITS(sav->key_enc);
830 		/* XXX Rounds ? */
831 	} else
832 		crda = crp->crp_desc;
833 
834 	/* IPsec-specific opaque crypto info. */
835 	tc = (struct tdb_crypto *) malloc(sizeof(struct tdb_crypto),
836 		M_XDATA, M_NOWAIT|M_ZERO);
837 	if (tc == NULL) {
838 		crypto_freereq(crp);
839 		DPRINTF(("%s: failed to allocate tdb_crypto\n", __func__));
840 		espstat.esps_crypto++;
841 		error = ENOBUFS;
842 		goto bad;
843 	}
844 
845 	/* Callback parameters */
846 	tc->tc_isr = isr;
847 	tc->tc_spi = sav->spi;
848 	tc->tc_dst = saidx->dst;
849 	tc->tc_proto = saidx->proto;
850 
851 	/* Crypto operation descriptor. */
852 	crp->crp_ilen = m->m_pkthdr.len; /* Total input length. */
853 	crp->crp_flags = CRYPTO_F_IMBUF | CRYPTO_F_CBIFSYNC;
854 	crp->crp_buf = (caddr_t) m;
855 	crp->crp_callback = esp_output_cb;
856 	crp->crp_opaque = (caddr_t) tc;
857 	crp->crp_sid = sav->tdb_cryptoid;
858 
859 	if (esph) {
860 		/* Authentication descriptor. */
861 		crda->crd_skip = skip;
862 		crda->crd_len = m->m_pkthdr.len - (skip + alen);
863 		crda->crd_inject = m->m_pkthdr.len - alen;
864 
865 		/* Authentication operation. */
866 		crda->crd_alg = esph->type;
867 		crda->crd_key = sav->key_auth->key_data;
868 		crda->crd_klen = _KEYBITS(sav->key_auth);
869 	}
870 
871 	return crypto_dispatch(crp);
872 bad:
873 	if (m)
874 		m_freem(m);
875 	return (error);
876 }
877 
878 /*
879  * ESP output callback from the crypto driver.
880  */
881 static int
882 esp_output_cb(struct cryptop *crp)
883 {
884 	struct tdb_crypto *tc;
885 	struct ipsecrequest *isr;
886 	struct secasvar *sav;
887 	struct mbuf *m;
888 	int err, error;
889 
890 	tc = (struct tdb_crypto *) crp->crp_opaque;
891 	IPSEC_ASSERT(tc != NULL, ("null opaque data area!"));
892 	m = (struct mbuf *) crp->crp_buf;
893 
894 	isr = tc->tc_isr;
895 	IPSECREQUEST_LOCK(isr);
896 	sav = KEY_ALLOCSA(&tc->tc_dst, tc->tc_proto, tc->tc_spi);
897 	if (sav == NULL) {
898 		espstat.esps_notdb++;
899 		DPRINTF(("%s: SA gone during crypto (SA %s/%08lx proto %u)\n",
900 		    __func__, ipsec_address(&tc->tc_dst),
901 		    (u_long) ntohl(tc->tc_spi), tc->tc_proto));
902 		error = ENOBUFS;		/*XXX*/
903 		goto bad;
904 	}
905 	IPSEC_ASSERT(isr->sav == sav,
906 		("SA changed was %p now %p\n", isr->sav, sav));
907 
908 	/* Check for crypto errors. */
909 	if (crp->crp_etype) {
910 		/* Reset session ID. */
911 		if (sav->tdb_cryptoid != 0)
912 			sav->tdb_cryptoid = crp->crp_sid;
913 
914 		if (crp->crp_etype == EAGAIN) {
915 			KEY_FREESAV(&sav);
916 			IPSECREQUEST_UNLOCK(isr);
917 			error = crypto_dispatch(crp);
918 			return error;
919 		}
920 
921 		espstat.esps_noxform++;
922 		DPRINTF(("%s: crypto error %d\n", __func__, crp->crp_etype));
923 		error = crp->crp_etype;
924 		goto bad;
925 	}
926 
927 	/* Shouldn't happen... */
928 	if (m == NULL) {
929 		espstat.esps_crypto++;
930 		DPRINTF(("%s: bogus returned buffer from crypto\n", __func__));
931 		error = EINVAL;
932 		goto bad;
933 	}
934 	espstat.esps_hist[sav->alg_enc]++;
935 	if (sav->tdb_authalgxform != NULL)
936 		ahstat.ahs_hist[sav->alg_auth]++;
937 
938 	/* Release crypto descriptors. */
939 	free(tc, M_XDATA);
940 	crypto_freereq(crp);
941 
942 #ifdef REGRESSION
943 	/* Emulate man-in-the-middle attack when ipsec_integrity is TRUE. */
944 	if (ipsec_integrity) {
945 		static unsigned char ipseczeroes[AH_HMAC_HASHLEN];
946 		struct auth_hash *esph;
947 
948 		/*
949 		 * Corrupt HMAC if we want to test integrity verification of
950 		 * the other side.
951 		 */
952 		esph = sav->tdb_authalgxform;
953 		if (esph !=  NULL) {
954 			m_copyback(m, m->m_pkthdr.len - AH_HMAC_HASHLEN,
955 			    AH_HMAC_HASHLEN, ipseczeroes);
956 		}
957 	}
958 #endif
959 
960 	/* NB: m is reclaimed by ipsec_process_done. */
961 	err = ipsec_process_done(m, isr);
962 	KEY_FREESAV(&sav);
963 	IPSECREQUEST_UNLOCK(isr);
964 	return err;
965 bad:
966 	if (sav)
967 		KEY_FREESAV(&sav);
968 	IPSECREQUEST_UNLOCK(isr);
969 	if (m)
970 		m_freem(m);
971 	free(tc, M_XDATA);
972 	crypto_freereq(crp);
973 	return error;
974 }
975 
976 static struct xformsw esp_xformsw = {
977 	XF_ESP,		XFT_CONF|XFT_AUTH,	"IPsec ESP",
978 	esp_init,	esp_zeroize,		esp_input,
979 	esp_output
980 };
981 
982 static void
983 esp_attach(void)
984 {
985 #define	MAXIV(xform)					\
986 	if (xform.blocksize > esp_max_ivlen)		\
987 		esp_max_ivlen = xform.blocksize		\
988 
989 	esp_max_ivlen = 0;
990 	MAXIV(enc_xform_des);		/* SADB_EALG_DESCBC */
991 	MAXIV(enc_xform_3des);		/* SADB_EALG_3DESCBC */
992 	MAXIV(enc_xform_rijndael128);	/* SADB_X_EALG_AES */
993 	MAXIV(enc_xform_blf);		/* SADB_X_EALG_BLOWFISHCBC */
994 	MAXIV(enc_xform_cast5);		/* SADB_X_EALG_CAST128CBC */
995 	MAXIV(enc_xform_skipjack);	/* SADB_X_EALG_SKIPJACK */
996 	MAXIV(enc_xform_null);		/* SADB_EALG_NULL */
997 	MAXIV(enc_xform_camellia);	/* SADB_X_EALG_CAMELLIACBC */
998 
999 	xform_register(&esp_xformsw);
1000 #undef MAXIV
1001 }
1002 SYSINIT(esp_xform_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE, esp_attach, NULL);
1003