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