xref: /freebsd/sys/netipsec/xform_esp.c (revision 0b3105a37d7adcadcb720112fed4dc4e8040be99)
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 #ifdef REGRESSION
766 		/* Emulate replay attack when ipsec_replay is TRUE. */
767 		if (!V_ipsec_replay)
768 #endif
769 			sav->replay->count++;
770 		replay = htonl(sav->replay->count);
771 		bcopy((caddr_t) &replay,
772 		    mtod(mo, caddr_t) + roff + sizeof(u_int32_t),
773 		    sizeof(u_int32_t));
774 	}
775 
776 	/*
777 	 * Add padding -- better to do it ourselves than use the crypto engine,
778 	 * although if/when we support compression, we'd have to do that.
779 	 */
780 	pad = (u_char *) m_pad(m, padding + alen);
781 	if (pad == NULL) {
782 		DPRINTF(("%s: m_pad failed for SA %s/%08lx\n", __func__,
783 		    ipsec_address(&saidx->dst, buf, sizeof(buf)),
784 		    (u_long) ntohl(sav->spi)));
785 		m = NULL;		/* NB: free'd by m_pad */
786 		error = ENOBUFS;
787 		goto bad;
788 	}
789 
790 	/*
791 	 * Add padding: random, zero, or self-describing.
792 	 * XXX catch unexpected setting
793 	 */
794 	switch (sav->flags & SADB_X_EXT_PMASK) {
795 	case SADB_X_EXT_PRAND:
796 		(void) read_random(pad, padding - 2);
797 		break;
798 	case SADB_X_EXT_PZERO:
799 		bzero(pad, padding - 2);
800 		break;
801 	case SADB_X_EXT_PSEQ:
802 		for (i = 0; i < padding - 2; i++)
803 			pad[i] = i+1;
804 		break;
805 	}
806 
807 	/* Fix padding length and Next Protocol in padding itself. */
808 	pad[padding - 2] = padding - 2;
809 	m_copydata(m, protoff, sizeof(u_int8_t), pad + padding - 1);
810 
811 	/* Fix Next Protocol in IPv4/IPv6 header. */
812 	prot = IPPROTO_ESP;
813 	m_copyback(m, protoff, sizeof(u_int8_t), (u_char *) &prot);
814 
815 	/* Get crypto descriptors. */
816 	crp = crypto_getreq(esph != NULL ? 2 : 1);
817 	if (crp == NULL) {
818 		DPRINTF(("%s: failed to acquire crypto descriptors\n",
819 			__func__));
820 		ESPSTAT_INC(esps_crypto);
821 		error = ENOBUFS;
822 		goto bad;
823 	}
824 
825 	/* IPsec-specific opaque crypto info. */
826 	tc = (struct tdb_crypto *) malloc(sizeof(struct tdb_crypto),
827 	    M_XDATA, M_NOWAIT|M_ZERO);
828 	if (tc == NULL) {
829 		crypto_freereq(crp);
830 		DPRINTF(("%s: failed to allocate tdb_crypto\n", __func__));
831 		ESPSTAT_INC(esps_crypto);
832 		error = ENOBUFS;
833 		goto bad;
834 	}
835 
836 	crde = crp->crp_desc;
837 	crda = crde->crd_next;
838 
839 	/* Encryption descriptor. */
840 	crde->crd_skip = skip + hlen;
841 	crde->crd_len = m->m_pkthdr.len - (skip + hlen + alen);
842 	crde->crd_flags = CRD_F_ENCRYPT;
843 	crde->crd_inject = skip + hlen - sav->ivlen;
844 
845 	/* Encryption operation. */
846 	crde->crd_alg = espx->type;
847 	if (SAV_ISCTRORGCM(sav)) {
848 		ivp = &crde->crd_iv[0];
849 
850 		/* GCM IV Format: RFC4106 4 */
851 		/* CTR IV Format: RFC3686 4 */
852 		/* Salt is last four bytes of key, RFC4106 8.1 */
853 		/* Nonce is last four bytes of key, RFC3686 5.1 */
854 		memcpy(ivp, sav->key_enc->key_data +
855 		    _KEYLEN(sav->key_enc) - 4, 4);
856 		SECASVAR_LOCK(sav);
857 		cntr = sav->cntr++;
858 		SECASVAR_UNLOCK(sav);
859 		be64enc(&ivp[4], cntr);
860 
861 		if (SAV_ISCTR(sav)) {
862 			/* Initial block counter is 1, RFC3686 4 */
863 			be32enc(&ivp[sav->ivlen + 4], 1);
864 		}
865 
866 		m_copyback(m, skip + hlen - sav->ivlen, sav->ivlen, &ivp[4]);
867 		crde->crd_flags |= CRD_F_IV_EXPLICIT|CRD_F_IV_PRESENT;
868 	}
869 
870 	/* Callback parameters */
871 	key_addref(isr->sp);
872 	tc->tc_isr = isr;
873 	KEY_ADDREFSA(sav);
874 	tc->tc_sav = sav;
875 	tc->tc_spi = sav->spi;
876 	tc->tc_dst = saidx->dst;
877 	tc->tc_proto = saidx->proto;
878 
879 	/* Crypto operation descriptor. */
880 	crp->crp_ilen = m->m_pkthdr.len; /* Total input length. */
881 	crp->crp_flags = CRYPTO_F_IMBUF | CRYPTO_F_CBIFSYNC;
882 	crp->crp_buf = (caddr_t) m;
883 	crp->crp_callback = esp_output_cb;
884 	crp->crp_opaque = (caddr_t) tc;
885 	crp->crp_sid = sav->tdb_cryptoid;
886 
887 	if (esph) {
888 		/* Authentication descriptor. */
889 		crda->crd_alg = esph->type;
890 		crda->crd_skip = skip;
891 		if (SAV_ISGCM(sav))
892 			crda->crd_len = 8;	/* RFC4106 5, SPI + SN */
893 		else
894 			crda->crd_len = m->m_pkthdr.len - (skip + alen);
895 		crda->crd_inject = m->m_pkthdr.len - alen;
896 	}
897 
898 	return crypto_dispatch(crp);
899 bad:
900 	if (m)
901 		m_freem(m);
902 	return (error);
903 }
904 
905 /*
906  * ESP output callback from the crypto driver.
907  */
908 static int
909 esp_output_cb(struct cryptop *crp)
910 {
911 	char buf[INET6_ADDRSTRLEN];
912 	struct tdb_crypto *tc;
913 	struct ipsecrequest *isr;
914 	struct secasvar *sav;
915 	struct mbuf *m;
916 	int error;
917 
918 	tc = (struct tdb_crypto *) crp->crp_opaque;
919 	IPSEC_ASSERT(tc != NULL, ("null opaque data area!"));
920 	m = (struct mbuf *) crp->crp_buf;
921 
922 	isr = tc->tc_isr;
923 	IPSEC_ASSERT(isr->sp != NULL, ("NULL isr->sp"));
924 	IPSECREQUEST_LOCK(isr);
925 	sav = tc->tc_sav;
926 
927 	/* With the isr lock released, SA pointer may have changed. */
928 	if (sav != isr->sav) {
929 		ESPSTAT_INC(esps_notdb);
930 		DPRINTF(("%s: SA gone during crypto (SA %s/%08lx proto %u)\n",
931 		    __func__, ipsec_address(&tc->tc_dst, buf, sizeof(buf)),
932 		    (u_long) ntohl(tc->tc_spi), tc->tc_proto));
933 		error = ENOBUFS;		/*XXX*/
934 		goto bad;
935 	}
936 
937 	/* Check for crypto errors. */
938 	if (crp->crp_etype) {
939 		/* Reset session ID. */
940 		if (sav->tdb_cryptoid != 0)
941 			sav->tdb_cryptoid = crp->crp_sid;
942 
943 		if (crp->crp_etype == EAGAIN) {
944 			IPSECREQUEST_UNLOCK(isr);
945 			return (crypto_dispatch(crp));
946 		}
947 
948 		ESPSTAT_INC(esps_noxform);
949 		DPRINTF(("%s: crypto error %d\n", __func__, crp->crp_etype));
950 		error = crp->crp_etype;
951 		goto bad;
952 	}
953 
954 	/* Shouldn't happen... */
955 	if (m == NULL) {
956 		ESPSTAT_INC(esps_crypto);
957 		DPRINTF(("%s: bogus returned buffer from crypto\n", __func__));
958 		error = EINVAL;
959 		goto bad;
960 	}
961 	ESPSTAT_INC(esps_hist[sav->alg_enc]);
962 	if (sav->tdb_authalgxform != NULL)
963 		AHSTAT_INC(ahs_hist[sav->alg_auth]);
964 
965 	/* Release crypto descriptors. */
966 	free(tc, M_XDATA);
967 	crypto_freereq(crp);
968 
969 #ifdef REGRESSION
970 	/* Emulate man-in-the-middle attack when ipsec_integrity is TRUE. */
971 	if (V_ipsec_integrity) {
972 		static unsigned char ipseczeroes[AH_HMAC_MAXHASHLEN];
973 		struct auth_hash *esph;
974 
975 		/*
976 		 * Corrupt HMAC if we want to test integrity verification of
977 		 * the other side.
978 		 */
979 		esph = sav->tdb_authalgxform;
980 		if (esph !=  NULL) {
981 			int alen;
982 
983 			alen = xform_ah_authsize(esph);
984 			m_copyback(m, m->m_pkthdr.len - alen,
985 			    alen, ipseczeroes);
986 		}
987 	}
988 #endif
989 
990 	/* NB: m is reclaimed by ipsec_process_done. */
991 	error = ipsec_process_done(m, isr);
992 	KEY_FREESAV(&sav);
993 	IPSECREQUEST_UNLOCK(isr);
994 	KEY_FREESP(&isr->sp);
995 	return (error);
996 bad:
997 	if (sav)
998 		KEY_FREESAV(&sav);
999 	IPSECREQUEST_UNLOCK(isr);
1000 	KEY_FREESP(&isr->sp);
1001 	if (m)
1002 		m_freem(m);
1003 	free(tc, M_XDATA);
1004 	crypto_freereq(crp);
1005 	return (error);
1006 }
1007 
1008 static struct xformsw esp_xformsw = {
1009 	XF_ESP,		XFT_CONF|XFT_AUTH,	"IPsec ESP",
1010 	esp_init,	esp_zeroize,		esp_input,
1011 	esp_output
1012 };
1013 
1014 static void
1015 esp_attach(void)
1016 {
1017 
1018 	xform_register(&esp_xformsw);
1019 }
1020 SYSINIT(esp_xform_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE, esp_attach, NULL);
1021