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