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