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