xref: /freebsd/sys/netipsec/xform_esp.c (revision 652a9748855320619e075c4e83aef2f5294412d2)
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/mutex.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 struct timeval deswarn, blfwarn, castwarn, camelliawarn;
98 
99 static int esp_input_cb(struct cryptop *op);
100 static int esp_output_cb(struct cryptop *crp);
101 
102 size_t
103 esp_hdrsiz(struct secasvar *sav)
104 {
105 	size_t size;
106 
107 	if (sav != NULL) {
108 		/*XXX not right for null algorithm--does it matter??*/
109 		IPSEC_ASSERT(sav->tdb_encalgxform != NULL,
110 			("SA with null xform"));
111 		if (sav->flags & SADB_X_EXT_OLD)
112 			size = sizeof (struct esp);
113 		else
114 			size = sizeof (struct newesp);
115 		size += sav->tdb_encalgxform->blocksize + 9;
116 		/*XXX need alg check???*/
117 		if (sav->tdb_authalgxform != NULL && sav->replay)
118 			size += ah_hdrsiz(sav);
119 	} else {
120 		/*
121 		 *   base header size
122 		 * + max iv length for CBC mode
123 		 * + max pad length
124 		 * + sizeof (pad length field)
125 		 * + sizeof (next header field)
126 		 * + max icv supported.
127 		 */
128 		size = sizeof (struct newesp) + EALG_MAX_BLOCK_LEN + 9 + 16;
129 	}
130 	return size;
131 }
132 
133 /*
134  * esp_init() is called when an SPI is being set up.
135  */
136 static int
137 esp_init(struct secasvar *sav, struct xformsw *xsp)
138 {
139 	const struct enc_xform *txform;
140 	struct crypto_session_params csp;
141 	int keylen;
142 	int error;
143 
144 	txform = enc_algorithm_lookup(sav->alg_enc);
145 	if (txform == NULL) {
146 		DPRINTF(("%s: unsupported encryption algorithm %d\n",
147 			__func__, sav->alg_enc));
148 		return EINVAL;
149 	}
150 	if (sav->key_enc == NULL) {
151 		DPRINTF(("%s: no encoding key for %s algorithm\n",
152 			 __func__, txform->name));
153 		return EINVAL;
154 	}
155 	if ((sav->flags & (SADB_X_EXT_OLD | SADB_X_EXT_IV4B)) ==
156 	    SADB_X_EXT_IV4B) {
157 		DPRINTF(("%s: 4-byte IV not supported with protocol\n",
158 			__func__));
159 		return EINVAL;
160 	}
161 
162 	switch (sav->alg_enc) {
163 	case SADB_EALG_DESCBC:
164 		if (ratecheck(&deswarn, &ipsec_warn_interval))
165 			gone_in(13, "DES cipher for IPsec");
166 		break;
167 	case SADB_X_EALG_BLOWFISHCBC:
168 		if (ratecheck(&blfwarn, &ipsec_warn_interval))
169 			gone_in(13, "Blowfish cipher for IPsec");
170 		break;
171 	case SADB_X_EALG_CAST128CBC:
172 		if (ratecheck(&castwarn, &ipsec_warn_interval))
173 			gone_in(13, "CAST cipher for IPsec");
174 		break;
175 	case SADB_X_EALG_CAMELLIACBC:
176 		if (ratecheck(&camelliawarn, &ipsec_warn_interval))
177 			gone_in(13, "Camellia cipher for IPsec");
178 		break;
179 	}
180 
181 	/* subtract off the salt, RFC4106, 8.1 and RFC3686, 5.1 */
182 	keylen = _KEYLEN(sav->key_enc) - SAV_ISCTRORGCM(sav) * 4;
183 	if (txform->minkey > keylen || keylen > txform->maxkey) {
184 		DPRINTF(("%s: invalid key length %u, must be in the range "
185 			"[%u..%u] for algorithm %s\n", __func__,
186 			keylen, txform->minkey, txform->maxkey,
187 			txform->name));
188 		return EINVAL;
189 	}
190 
191 	if (SAV_ISCTRORGCM(sav))
192 		sav->ivlen = 8;	/* RFC4106 3.1 and RFC3686 3.1 */
193 	else
194 		sav->ivlen = txform->ivsize;
195 
196 	memset(&csp, 0, sizeof(csp));
197 
198 	/*
199 	 * Setup AH-related state.
200 	 */
201 	if (sav->alg_auth != 0) {
202 		error = ah_init0(sav, xsp, &csp);
203 		if (error)
204 			return error;
205 	}
206 
207 	/* NB: override anything set in ah_init0 */
208 	sav->tdb_xform = xsp;
209 	sav->tdb_encalgxform = txform;
210 
211 	/*
212 	 * Whenever AES-GCM is used for encryption, one
213 	 * of the AES authentication algorithms is chosen
214 	 * as well, based on the key size.
215 	 */
216 	if (sav->alg_enc == SADB_X_EALG_AESGCM16) {
217 		switch (keylen) {
218 		case AES_128_GMAC_KEY_LEN:
219 			sav->alg_auth = SADB_X_AALG_AES128GMAC;
220 			sav->tdb_authalgxform = &auth_hash_nist_gmac_aes_128;
221 			break;
222 		case AES_192_GMAC_KEY_LEN:
223 			sav->alg_auth = SADB_X_AALG_AES192GMAC;
224 			sav->tdb_authalgxform = &auth_hash_nist_gmac_aes_192;
225 			break;
226 		case AES_256_GMAC_KEY_LEN:
227 			sav->alg_auth = SADB_X_AALG_AES256GMAC;
228 			sav->tdb_authalgxform = &auth_hash_nist_gmac_aes_256;
229 			break;
230 		default:
231 			DPRINTF(("%s: invalid key length %u"
232 				 "for algorithm %s\n", __func__,
233 				 keylen, txform->name));
234 			return EINVAL;
235 		}
236 		csp.csp_mode = CSP_MODE_AEAD;
237 	} else if (sav->alg_auth != 0)
238 		csp.csp_mode = CSP_MODE_ETA;
239 	else
240 		csp.csp_mode = CSP_MODE_CIPHER;
241 
242 	/* Initialize crypto session. */
243 	csp.csp_cipher_alg = sav->tdb_encalgxform->type;
244 	csp.csp_cipher_key = sav->key_enc->key_data;
245 	csp.csp_cipher_klen = _KEYBITS(sav->key_enc) / 8 -
246 	    SAV_ISCTRORGCM(sav) * 4;
247 	csp.csp_ivlen = txform->ivsize;
248 
249 	error = crypto_newsession(&sav->tdb_cryptoid, &csp, V_crypto_support);
250 	return error;
251 }
252 
253 /*
254  * Paranoia.
255  */
256 static int
257 esp_zeroize(struct secasvar *sav)
258 {
259 	/* NB: ah_zerorize free's the crypto session state */
260 	int error = ah_zeroize(sav);
261 
262 	if (sav->key_enc)
263 		bzero(sav->key_enc->key_data, _KEYLEN(sav->key_enc));
264 	sav->tdb_encalgxform = NULL;
265 	sav->tdb_xform = NULL;
266 	return error;
267 }
268 
269 /*
270  * ESP input processing, called (eventually) through the protocol switch.
271  */
272 static int
273 esp_input(struct mbuf *m, struct secasvar *sav, int skip, int protoff)
274 {
275 	IPSEC_DEBUG_DECLARE(char buf[128]);
276 	const struct auth_hash *esph;
277 	const struct enc_xform *espx;
278 	struct xform_data *xd;
279 	struct cryptop *crp;
280 	struct newesp *esp;
281 	uint8_t *ivp;
282 	crypto_session_t cryptoid;
283 	int alen, error, hlen, plen;
284 
285 	IPSEC_ASSERT(sav != NULL, ("null SA"));
286 	IPSEC_ASSERT(sav->tdb_encalgxform != NULL, ("null encoding xform"));
287 
288 	error = EINVAL;
289 	/* Valid IP Packet length ? */
290 	if ( (skip&3) || (m->m_pkthdr.len&3) ){
291 		DPRINTF(("%s: misaligned packet, skip %u pkt len %u",
292 				__func__, skip, m->m_pkthdr.len));
293 		ESPSTAT_INC(esps_badilen);
294 		goto bad;
295 	}
296 
297 	if (m->m_len < skip + sizeof(*esp)) {
298 		m = m_pullup(m, skip + sizeof(*esp));
299 		if (m == NULL) {
300 			DPRINTF(("%s: cannot pullup header\n", __func__));
301 			ESPSTAT_INC(esps_hdrops);	/*XXX*/
302 			error = ENOBUFS;
303 			goto bad;
304 		}
305 	}
306 	esp = (struct newesp *)(mtod(m, caddr_t) + skip);
307 
308 	esph = sav->tdb_authalgxform;
309 	espx = sav->tdb_encalgxform;
310 
311 	/* Determine the ESP header and auth length */
312 	if (sav->flags & SADB_X_EXT_OLD)
313 		hlen = sizeof (struct esp) + sav->ivlen;
314 	else
315 		hlen = sizeof (struct newesp) + sav->ivlen;
316 
317 	alen = xform_ah_authsize(esph);
318 
319 	/*
320 	 * Verify payload length is multiple of encryption algorithm
321 	 * block size.
322 	 *
323 	 * NB: This works for the null algorithm because the blocksize
324 	 *     is 4 and all packets must be 4-byte aligned regardless
325 	 *     of the algorithm.
326 	 */
327 	plen = m->m_pkthdr.len - (skip + hlen + alen);
328 	if ((plen & (espx->blocksize - 1)) || (plen <= 0)) {
329 		DPRINTF(("%s: payload of %d octets not a multiple of %d octets,"
330 		    "  SA %s/%08lx\n", __func__, plen, espx->blocksize,
331 		    ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
332 		    (u_long)ntohl(sav->spi)));
333 		ESPSTAT_INC(esps_badilen);
334 		goto bad;
335 	}
336 
337 	/*
338 	 * Check sequence number.
339 	 */
340 	SECASVAR_LOCK(sav);
341 	if (esph != NULL && sav->replay != NULL && sav->replay->wsize != 0) {
342 		if (ipsec_chkreplay(ntohl(esp->esp_seq), sav) == 0) {
343 			SECASVAR_UNLOCK(sav);
344 			DPRINTF(("%s: packet replay check for %s\n", __func__,
345 			    ipsec_sa2str(sav, buf, sizeof(buf))));
346 			ESPSTAT_INC(esps_replay);
347 			error = EACCES;
348 			goto bad;
349 		}
350 	}
351 	cryptoid = sav->tdb_cryptoid;
352 	SECASVAR_UNLOCK(sav);
353 
354 	/* Update the counters */
355 	ESPSTAT_ADD(esps_ibytes, m->m_pkthdr.len - (skip + hlen + alen));
356 
357 	/* Get crypto descriptors */
358 	crp = crypto_getreq(cryptoid, M_NOWAIT);
359 	if (crp == NULL) {
360 		DPRINTF(("%s: failed to acquire crypto descriptors\n",
361 			__func__));
362 		ESPSTAT_INC(esps_crypto);
363 		error = ENOBUFS;
364 		goto bad;
365 	}
366 
367 	/* Get IPsec-specific opaque pointer */
368 	xd = malloc(sizeof(*xd), M_XDATA, M_NOWAIT | M_ZERO);
369 	if (xd == NULL) {
370 		DPRINTF(("%s: failed to allocate xform_data\n", __func__));
371 		ESPSTAT_INC(esps_crypto);
372 		crypto_freereq(crp);
373 		error = ENOBUFS;
374 		goto bad;
375 	}
376 
377 	if (esph != NULL) {
378 		crp->crp_op = CRYPTO_OP_VERIFY_DIGEST;
379 		crp->crp_aad_start = skip;
380 		if (SAV_ISGCM(sav))
381 			crp->crp_aad_length = 8; /* RFC4106 5, SPI + SN */
382 		else
383 			crp->crp_aad_length = hlen;
384 		crp->crp_digest_start = m->m_pkthdr.len - alen;
385 	}
386 
387 	/* Crypto operation descriptor */
388 	crp->crp_ilen = m->m_pkthdr.len; /* Total input length */
389 	crp->crp_flags = CRYPTO_F_CBIFSYNC;
390 	if (V_async_crypto)
391 		crp->crp_flags |= CRYPTO_F_ASYNC | CRYPTO_F_ASYNC_KEEPORDER;
392 	crp->crp_mbuf = m;
393 	crp->crp_buf_type = CRYPTO_BUF_MBUF;
394 	crp->crp_callback = esp_input_cb;
395 	crp->crp_opaque = xd;
396 
397 	/* These are passed as-is to the callback */
398 	xd->sav = sav;
399 	xd->protoff = protoff;
400 	xd->skip = skip;
401 	xd->cryptoid = cryptoid;
402 	xd->vnet = curvnet;
403 
404 	/* Decryption descriptor */
405 	crp->crp_op |= CRYPTO_OP_DECRYPT;
406 	crp->crp_payload_start = skip + hlen;
407 	crp->crp_payload_length = m->m_pkthdr.len - (skip + hlen + alen);
408 
409 	if (SAV_ISCTRORGCM(sav)) {
410 		ivp = &crp->crp_iv[0];
411 
412 		/* GCM IV Format: RFC4106 4 */
413 		/* CTR IV Format: RFC3686 4 */
414 		/* Salt is last four bytes of key, RFC4106 8.1 */
415 		/* Nonce is last four bytes of key, RFC3686 5.1 */
416 		memcpy(ivp, sav->key_enc->key_data +
417 		    _KEYLEN(sav->key_enc) - 4, 4);
418 
419 		if (SAV_ISCTR(sav)) {
420 			/* Initial block counter is 1, RFC3686 4 */
421 			be32enc(&ivp[sav->ivlen + 4], 1);
422 		}
423 
424 		m_copydata(m, skip + hlen - sav->ivlen, sav->ivlen, &ivp[4]);
425 		crp->crp_flags |= CRYPTO_F_IV_SEPARATE;
426 	} else if (sav->ivlen != 0)
427 		crp->crp_iv_start = skip + hlen - sav->ivlen;
428 
429 	return (crypto_dispatch(crp));
430 bad:
431 	m_freem(m);
432 	key_freesav(&sav);
433 	return (error);
434 }
435 
436 /*
437  * ESP input callback from the crypto driver.
438  */
439 static int
440 esp_input_cb(struct cryptop *crp)
441 {
442 	IPSEC_DEBUG_DECLARE(char buf[128]);
443 	uint8_t lastthree[3];
444 	const struct auth_hash *esph;
445 	struct mbuf *m;
446 	struct xform_data *xd;
447 	struct secasvar *sav;
448 	struct secasindex *saidx;
449 	crypto_session_t cryptoid;
450 	int hlen, skip, protoff, error, alen;
451 
452 	m = crp->crp_mbuf;
453 	xd = crp->crp_opaque;
454 	CURVNET_SET(xd->vnet);
455 	sav = xd->sav;
456 	skip = xd->skip;
457 	protoff = xd->protoff;
458 	cryptoid = xd->cryptoid;
459 	saidx = &sav->sah->saidx;
460 	esph = sav->tdb_authalgxform;
461 
462 	/* Check for crypto errors */
463 	if (crp->crp_etype) {
464 		if (crp->crp_etype == EAGAIN) {
465 			/* Reset the session ID */
466 			if (ipsec_updateid(sav, &crp->crp_session, &cryptoid) != 0)
467 				crypto_freesession(cryptoid);
468 			xd->cryptoid = crp->crp_session;
469 			CURVNET_RESTORE();
470 			return (crypto_dispatch(crp));
471 		}
472 
473 		/* EBADMSG indicates authentication failure. */
474 		if (!(crp->crp_etype == EBADMSG && esph != NULL)) {
475 			ESPSTAT_INC(esps_noxform);
476 			DPRINTF(("%s: crypto error %d\n", __func__,
477 				crp->crp_etype));
478 			error = crp->crp_etype;
479 			goto bad;
480 		}
481 	}
482 
483 	/* Shouldn't happen... */
484 	if (m == NULL) {
485 		ESPSTAT_INC(esps_crypto);
486 		DPRINTF(("%s: bogus returned buffer from crypto\n", __func__));
487 		error = EINVAL;
488 		goto bad;
489 	}
490 	ESPSTAT_INC(esps_hist[sav->alg_enc]);
491 
492 	/* If authentication was performed, check now. */
493 	if (esph != NULL) {
494 		alen = xform_ah_authsize(esph);
495 		AHSTAT_INC(ahs_hist[sav->alg_auth]);
496 		if (crp->crp_etype == EBADMSG) {
497 			DPRINTF(("%s: authentication hash mismatch for "
498 			    "packet in SA %s/%08lx\n", __func__,
499 			    ipsec_address(&saidx->dst, buf, sizeof(buf)),
500 			    (u_long) ntohl(sav->spi)));
501 			ESPSTAT_INC(esps_badauth);
502 			error = EACCES;
503 			goto bad;
504 		}
505 		m->m_flags |= M_AUTHIPDGM;
506 		/* Remove trailing authenticator */
507 		m_adj(m, -alen);
508 	}
509 
510 	/* Release the crypto descriptors */
511 	free(xd, M_XDATA), xd = NULL;
512 	crypto_freereq(crp), crp = NULL;
513 
514 	/*
515 	 * Packet is now decrypted.
516 	 */
517 	m->m_flags |= M_DECRYPTED;
518 
519 	/*
520 	 * Update replay sequence number, if appropriate.
521 	 */
522 	if (sav->replay) {
523 		u_int32_t seq;
524 
525 		m_copydata(m, skip + offsetof(struct newesp, esp_seq),
526 			   sizeof (seq), (caddr_t) &seq);
527 		SECASVAR_LOCK(sav);
528 		if (ipsec_updatereplay(ntohl(seq), sav)) {
529 			SECASVAR_UNLOCK(sav);
530 			DPRINTF(("%s: packet replay check for %s\n", __func__,
531 			    ipsec_sa2str(sav, buf, sizeof(buf))));
532 			ESPSTAT_INC(esps_replay);
533 			error = EACCES;
534 			goto bad;
535 		}
536 		SECASVAR_UNLOCK(sav);
537 	}
538 
539 	/* Determine the ESP header length */
540 	if (sav->flags & SADB_X_EXT_OLD)
541 		hlen = sizeof (struct esp) + sav->ivlen;
542 	else
543 		hlen = sizeof (struct newesp) + sav->ivlen;
544 
545 	/* Remove the ESP header and IV from the mbuf. */
546 	error = m_striphdr(m, skip, hlen);
547 	if (error) {
548 		ESPSTAT_INC(esps_hdrops);
549 		DPRINTF(("%s: bad mbuf chain, SA %s/%08lx\n", __func__,
550 		    ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
551 		    (u_long) ntohl(sav->spi)));
552 		goto bad;
553 	}
554 
555 	/* Save the last three bytes of decrypted data */
556 	m_copydata(m, m->m_pkthdr.len - 3, 3, lastthree);
557 
558 	/* Verify pad length */
559 	if (lastthree[1] + 2 > m->m_pkthdr.len - skip) {
560 		ESPSTAT_INC(esps_badilen);
561 		DPRINTF(("%s: invalid padding length %d for %u byte packet "
562 		    "in SA %s/%08lx\n", __func__, lastthree[1],
563 		    m->m_pkthdr.len - skip,
564 		    ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
565 		    (u_long) ntohl(sav->spi)));
566 		error = EINVAL;
567 		goto bad;
568 	}
569 
570 	/* Verify correct decryption by checking the last padding bytes */
571 	if ((sav->flags & SADB_X_EXT_PMASK) != SADB_X_EXT_PRAND) {
572 		if (lastthree[1] != lastthree[0] && lastthree[1] != 0) {
573 			ESPSTAT_INC(esps_badenc);
574 			DPRINTF(("%s: decryption failed for packet in "
575 			    "SA %s/%08lx\n", __func__, ipsec_address(
576 			    &sav->sah->saidx.dst, buf, sizeof(buf)),
577 			    (u_long) ntohl(sav->spi)));
578 			error = EINVAL;
579 			goto bad;
580 		}
581 	}
582 
583 	/*
584 	 * RFC4303 2.6:
585 	 * Silently drop packet if next header field is IPPROTO_NONE.
586 	 */
587 	if (lastthree[2] == IPPROTO_NONE)
588 		goto bad;
589 
590 	/* Trim the mbuf chain to remove trailing authenticator and padding */
591 	m_adj(m, -(lastthree[1] + 2));
592 
593 	/* Restore the Next Protocol field */
594 	m_copyback(m, protoff, sizeof (u_int8_t), lastthree + 2);
595 
596 	switch (saidx->dst.sa.sa_family) {
597 #ifdef INET6
598 	case AF_INET6:
599 		error = ipsec6_common_input_cb(m, sav, skip, protoff);
600 		break;
601 #endif
602 #ifdef INET
603 	case AF_INET:
604 		error = ipsec4_common_input_cb(m, sav, skip, protoff);
605 		break;
606 #endif
607 	default:
608 		panic("%s: Unexpected address family: %d saidx=%p", __func__,
609 		    saidx->dst.sa.sa_family, saidx);
610 	}
611 	CURVNET_RESTORE();
612 	return error;
613 bad:
614 	CURVNET_RESTORE();
615 	if (sav != NULL)
616 		key_freesav(&sav);
617 	if (m != NULL)
618 		m_freem(m);
619 	if (xd != NULL)
620 		free(xd, M_XDATA);
621 	if (crp != NULL)
622 		crypto_freereq(crp);
623 	return error;
624 }
625 /*
626  * ESP output routine, called by ipsec[46]_perform_request().
627  */
628 static int
629 esp_output(struct mbuf *m, struct secpolicy *sp, struct secasvar *sav,
630     u_int idx, int skip, int protoff)
631 {
632 	IPSEC_DEBUG_DECLARE(char buf[IPSEC_ADDRSTRLEN]);
633 	struct cryptop *crp;
634 	const struct auth_hash *esph;
635 	const struct enc_xform *espx;
636 	struct mbuf *mo = NULL;
637 	struct xform_data *xd;
638 	struct secasindex *saidx;
639 	unsigned char *pad;
640 	uint8_t *ivp;
641 	uint64_t cntr;
642 	crypto_session_t cryptoid;
643 	int hlen, rlen, padding, blks, alen, i, roff;
644 	int error, maxpacketsize;
645 	uint8_t prot;
646 
647 	IPSEC_ASSERT(sav != NULL, ("null SA"));
648 	esph = sav->tdb_authalgxform;
649 	espx = sav->tdb_encalgxform;
650 	IPSEC_ASSERT(espx != NULL, ("null encoding xform"));
651 
652 	if (sav->flags & SADB_X_EXT_OLD)
653 		hlen = sizeof (struct esp) + sav->ivlen;
654 	else
655 		hlen = sizeof (struct newesp) + sav->ivlen;
656 
657 	rlen = m->m_pkthdr.len - skip;	/* Raw payload length. */
658 	/*
659 	 * RFC4303 2.4 Requires 4 byte alignment.
660 	 */
661 	blks = MAX(4, espx->blocksize);		/* Cipher blocksize */
662 
663 	/* XXX clamp padding length a la KAME??? */
664 	padding = ((blks - ((rlen + 2) % blks)) % blks) + 2;
665 
666 	alen = xform_ah_authsize(esph);
667 
668 	ESPSTAT_INC(esps_output);
669 
670 	saidx = &sav->sah->saidx;
671 	/* Check for maximum packet size violations. */
672 	switch (saidx->dst.sa.sa_family) {
673 #ifdef INET
674 	case AF_INET:
675 		maxpacketsize = IP_MAXPACKET;
676 		break;
677 #endif /* INET */
678 #ifdef INET6
679 	case AF_INET6:
680 		maxpacketsize = IPV6_MAXPACKET;
681 		break;
682 #endif /* INET6 */
683 	default:
684 		DPRINTF(("%s: unknown/unsupported protocol "
685 		    "family %d, SA %s/%08lx\n", __func__,
686 		    saidx->dst.sa.sa_family, ipsec_address(&saidx->dst,
687 			buf, sizeof(buf)), (u_long) ntohl(sav->spi)));
688 		ESPSTAT_INC(esps_nopf);
689 		error = EPFNOSUPPORT;
690 		goto bad;
691 	}
692 	/*
693 	DPRINTF(("%s: skip %d hlen %d rlen %d padding %d alen %d blksd %d\n",
694 		__func__, skip, hlen, rlen, padding, alen, blks)); */
695 	if (skip + hlen + rlen + padding + alen > maxpacketsize) {
696 		DPRINTF(("%s: packet in SA %s/%08lx got too big "
697 		    "(len %u, max len %u)\n", __func__,
698 		    ipsec_address(&saidx->dst, buf, sizeof(buf)),
699 		    (u_long) ntohl(sav->spi),
700 		    skip + hlen + rlen + padding + alen, maxpacketsize));
701 		ESPSTAT_INC(esps_toobig);
702 		error = EMSGSIZE;
703 		goto bad;
704 	}
705 
706 	/* Update the counters. */
707 	ESPSTAT_ADD(esps_obytes, m->m_pkthdr.len - skip);
708 
709 	m = m_unshare(m, M_NOWAIT);
710 	if (m == NULL) {
711 		DPRINTF(("%s: cannot clone mbuf chain, SA %s/%08lx\n", __func__,
712 		    ipsec_address(&saidx->dst, buf, sizeof(buf)),
713 		    (u_long) ntohl(sav->spi)));
714 		ESPSTAT_INC(esps_hdrops);
715 		error = ENOBUFS;
716 		goto bad;
717 	}
718 
719 	/* Inject ESP header. */
720 	mo = m_makespace(m, skip, hlen, &roff);
721 	if (mo == NULL) {
722 		DPRINTF(("%s: %u byte ESP hdr inject failed for SA %s/%08lx\n",
723 		    __func__, hlen, ipsec_address(&saidx->dst, buf,
724 		    sizeof(buf)), (u_long) ntohl(sav->spi)));
725 		ESPSTAT_INC(esps_hdrops);	/* XXX diffs from openbsd */
726 		error = ENOBUFS;
727 		goto bad;
728 	}
729 
730 	/* Initialize ESP header. */
731 	bcopy((caddr_t) &sav->spi, mtod(mo, caddr_t) + roff,
732 	    sizeof(uint32_t));
733 	SECASVAR_LOCK(sav);
734 	if (sav->replay) {
735 		uint32_t replay;
736 
737 #ifdef REGRESSION
738 		/* Emulate replay attack when ipsec_replay is TRUE. */
739 		if (!V_ipsec_replay)
740 #endif
741 			sav->replay->count++;
742 		replay = htonl(sav->replay->count);
743 
744 		bcopy((caddr_t) &replay, mtod(mo, caddr_t) + roff +
745 		    sizeof(uint32_t), sizeof(uint32_t));
746 	}
747 	cryptoid = sav->tdb_cryptoid;
748 	if (SAV_ISCTRORGCM(sav))
749 		cntr = sav->cntr++;
750 	SECASVAR_UNLOCK(sav);
751 
752 	/*
753 	 * Add padding -- better to do it ourselves than use the crypto engine,
754 	 * although if/when we support compression, we'd have to do that.
755 	 */
756 	pad = (u_char *) m_pad(m, padding + alen);
757 	if (pad == NULL) {
758 		DPRINTF(("%s: m_pad failed for SA %s/%08lx\n", __func__,
759 		    ipsec_address(&saidx->dst, buf, sizeof(buf)),
760 		    (u_long) ntohl(sav->spi)));
761 		m = NULL;		/* NB: free'd by m_pad */
762 		error = ENOBUFS;
763 		goto bad;
764 	}
765 
766 	/*
767 	 * Add padding: random, zero, or self-describing.
768 	 * XXX catch unexpected setting
769 	 */
770 	switch (sav->flags & SADB_X_EXT_PMASK) {
771 	case SADB_X_EXT_PRAND:
772 		arc4random_buf(pad, padding - 2);
773 		break;
774 	case SADB_X_EXT_PZERO:
775 		bzero(pad, padding - 2);
776 		break;
777 	case SADB_X_EXT_PSEQ:
778 		for (i = 0; i < padding - 2; i++)
779 			pad[i] = i+1;
780 		break;
781 	}
782 
783 	/* Fix padding length and Next Protocol in padding itself. */
784 	pad[padding - 2] = padding - 2;
785 	m_copydata(m, protoff, sizeof(u_int8_t), pad + padding - 1);
786 
787 	/* Fix Next Protocol in IPv4/IPv6 header. */
788 	prot = IPPROTO_ESP;
789 	m_copyback(m, protoff, sizeof(u_int8_t), (u_char *) &prot);
790 
791 	/* Get crypto descriptor. */
792 	crp = crypto_getreq(cryptoid, M_NOWAIT);
793 	if (crp == NULL) {
794 		DPRINTF(("%s: failed to acquire crypto descriptor\n",
795 			__func__));
796 		ESPSTAT_INC(esps_crypto);
797 		error = ENOBUFS;
798 		goto bad;
799 	}
800 
801 	/* IPsec-specific opaque crypto info. */
802 	xd =  malloc(sizeof(struct xform_data), M_XDATA, M_NOWAIT | M_ZERO);
803 	if (xd == NULL) {
804 		crypto_freereq(crp);
805 		DPRINTF(("%s: failed to allocate xform_data\n", __func__));
806 		ESPSTAT_INC(esps_crypto);
807 		error = ENOBUFS;
808 		goto bad;
809 	}
810 
811 	/* Encryption descriptor. */
812 	crp->crp_payload_start = skip + hlen;
813 	crp->crp_payload_length = m->m_pkthdr.len - (skip + hlen + alen);
814 	crp->crp_op = CRYPTO_OP_ENCRYPT;
815 
816 	/* Encryption operation. */
817 	if (SAV_ISCTRORGCM(sav)) {
818 		ivp = &crp->crp_iv[0];
819 
820 		/* GCM IV Format: RFC4106 4 */
821 		/* CTR IV Format: RFC3686 4 */
822 		/* Salt is last four bytes of key, RFC4106 8.1 */
823 		/* Nonce is last four bytes of key, RFC3686 5.1 */
824 		memcpy(ivp, sav->key_enc->key_data +
825 		    _KEYLEN(sav->key_enc) - 4, 4);
826 		be64enc(&ivp[4], cntr);
827 		if (SAV_ISCTR(sav)) {
828 			/* Initial block counter is 1, RFC3686 4 */
829 			/* XXXAE: should we use this only for first packet? */
830 			be32enc(&ivp[sav->ivlen + 4], 1);
831 		}
832 
833 		m_copyback(m, skip + hlen - sav->ivlen, sav->ivlen, &ivp[4]);
834 		crp->crp_flags |= CRYPTO_F_IV_SEPARATE;
835 	} else if (sav->ivlen != 0) {
836 		crp->crp_iv_start = skip + hlen - sav->ivlen;
837 		crp->crp_flags |= CRYPTO_F_IV_GENERATE;
838 	}
839 
840 	/* Callback parameters */
841 	xd->sp = sp;
842 	xd->sav = sav;
843 	xd->idx = idx;
844 	xd->cryptoid = cryptoid;
845 	xd->vnet = curvnet;
846 
847 	/* Crypto operation descriptor. */
848 	crp->crp_ilen = m->m_pkthdr.len; /* Total input length. */
849 	crp->crp_flags |= CRYPTO_F_CBIFSYNC;
850 	if (V_async_crypto)
851 		crp->crp_flags |= CRYPTO_F_ASYNC | CRYPTO_F_ASYNC_KEEPORDER;
852 	crp->crp_mbuf = m;
853 	crp->crp_buf_type = CRYPTO_BUF_MBUF;
854 	crp->crp_callback = esp_output_cb;
855 	crp->crp_opaque = xd;
856 
857 	if (esph) {
858 		/* Authentication descriptor. */
859 		crp->crp_op |= CRYPTO_OP_COMPUTE_DIGEST;
860 		crp->crp_aad_start = skip;
861 		if (SAV_ISGCM(sav))
862 			crp->crp_aad_length = 8; /* RFC4106 5, SPI + SN */
863 		else
864 			crp->crp_aad_length = hlen;
865 		crp->crp_digest_start = m->m_pkthdr.len - alen;
866 	}
867 
868 	return crypto_dispatch(crp);
869 bad:
870 	if (m)
871 		m_freem(m);
872 	key_freesav(&sav);
873 	key_freesp(&sp);
874 	return (error);
875 }
876 /*
877  * ESP output callback from the crypto driver.
878  */
879 static int
880 esp_output_cb(struct cryptop *crp)
881 {
882 	struct xform_data *xd;
883 	struct secpolicy *sp;
884 	struct secasvar *sav;
885 	struct mbuf *m;
886 	crypto_session_t cryptoid;
887 	u_int idx;
888 	int error;
889 
890 	xd = (struct xform_data *) crp->crp_opaque;
891 	CURVNET_SET(xd->vnet);
892 	m = (struct mbuf *) crp->crp_buf;
893 	sp = xd->sp;
894 	sav = xd->sav;
895 	idx = xd->idx;
896 	cryptoid = xd->cryptoid;
897 
898 	/* Check for crypto errors. */
899 	if (crp->crp_etype) {
900 		if (crp->crp_etype == EAGAIN) {
901 			/* Reset the session ID */
902 			if (ipsec_updateid(sav, &crp->crp_session, &cryptoid) != 0)
903 				crypto_freesession(cryptoid);
904 			xd->cryptoid = crp->crp_session;
905 			CURVNET_RESTORE();
906 			return (crypto_dispatch(crp));
907 		}
908 		ESPSTAT_INC(esps_noxform);
909 		DPRINTF(("%s: crypto error %d\n", __func__, crp->crp_etype));
910 		error = crp->crp_etype;
911 		m_freem(m);
912 		goto bad;
913 	}
914 
915 	/* Shouldn't happen... */
916 	if (m == NULL) {
917 		ESPSTAT_INC(esps_crypto);
918 		DPRINTF(("%s: bogus returned buffer from crypto\n", __func__));
919 		error = EINVAL;
920 		goto bad;
921 	}
922 	free(xd, M_XDATA);
923 	crypto_freereq(crp);
924 	ESPSTAT_INC(esps_hist[sav->alg_enc]);
925 	if (sav->tdb_authalgxform != NULL)
926 		AHSTAT_INC(ahs_hist[sav->alg_auth]);
927 
928 #ifdef REGRESSION
929 	/* Emulate man-in-the-middle attack when ipsec_integrity is TRUE. */
930 	if (V_ipsec_integrity) {
931 		static unsigned char ipseczeroes[AH_HMAC_MAXHASHLEN];
932 		const struct auth_hash *esph;
933 
934 		/*
935 		 * Corrupt HMAC if we want to test integrity verification of
936 		 * the other side.
937 		 */
938 		esph = sav->tdb_authalgxform;
939 		if (esph !=  NULL) {
940 			int alen;
941 
942 			alen = xform_ah_authsize(esph);
943 			m_copyback(m, m->m_pkthdr.len - alen,
944 			    alen, ipseczeroes);
945 		}
946 	}
947 #endif
948 
949 	/* NB: m is reclaimed by ipsec_process_done. */
950 	error = ipsec_process_done(m, sp, sav, idx);
951 	CURVNET_RESTORE();
952 	return (error);
953 bad:
954 	CURVNET_RESTORE();
955 	free(xd, M_XDATA);
956 	crypto_freereq(crp);
957 	key_freesav(&sav);
958 	key_freesp(&sp);
959 	return (error);
960 }
961 
962 static struct xformsw esp_xformsw = {
963 	.xf_type =	XF_ESP,
964 	.xf_name =	"IPsec ESP",
965 	.xf_init =	esp_init,
966 	.xf_zeroize =	esp_zeroize,
967 	.xf_input =	esp_input,
968 	.xf_output =	esp_output,
969 };
970 
971 SYSINIT(esp_xform_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE,
972     xform_attach, &esp_xformsw);
973 SYSUNINIT(esp_xform_uninit, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE,
974     xform_detach, &esp_xformsw);
975