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