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