xref: /freebsd/sys/netipsec/xform_esp.c (revision f527d7de582277fbebe8897b082a726786cb11e9)
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 	/* Generate or read cipher IV. */
410 	if (SAV_ISCTRORGCM(sav)) {
411 		ivp = &crp->crp_iv[0];
412 
413 		/*
414 		 * AES-GCM and AES-CTR use similar cipher IV formats
415 		 * defined in RFC 4106 section 4 and RFC 3686 section
416 		 * 4, respectively.
417 		 *
418 		 * The first 4 bytes of the cipher IV contain an
419 		 * implicit salt, or nonce, obtained from the last 4
420 		 * bytes of the encryption key.  The next 8 bytes hold
421 		 * an explicit IV unique to each packet.  This
422 		 * explicit IV is used as the ESP IV for the packet.
423 		 * The last 4 bytes hold a big-endian block counter
424 		 * incremented for each block.  For AES-GCM, the block
425 		 * counter's initial value is defined as part of the
426 		 * algorithm.  For AES-CTR, the block counter's
427 		 * initial value for each packet is defined as 1 by
428 		 * RFC 3686.
429 		 *
430 		 * ------------------------------------------
431 		 * | Salt | Explicit ESP IV | Block Counter |
432 		 * ------------------------------------------
433 		 *  4 bytes     8 bytes          4 bytes
434 		 */
435 		memcpy(ivp, sav->key_enc->key_data +
436 		    _KEYLEN(sav->key_enc) - 4, 4);
437 		m_copydata(m, skip + hlen - sav->ivlen, sav->ivlen, &ivp[4]);
438 		if (SAV_ISCTR(sav)) {
439 			be32enc(&ivp[sav->ivlen + 4], 1);
440 		}
441 		crp->crp_flags |= CRYPTO_F_IV_SEPARATE;
442 	} else if (sav->ivlen != 0)
443 		crp->crp_iv_start = skip + hlen - sav->ivlen;
444 
445 	return (crypto_dispatch(crp));
446 bad:
447 	m_freem(m);
448 	key_freesav(&sav);
449 	return (error);
450 }
451 
452 /*
453  * ESP input callback from the crypto driver.
454  */
455 static int
456 esp_input_cb(struct cryptop *crp)
457 {
458 	IPSEC_DEBUG_DECLARE(char buf[128]);
459 	uint8_t lastthree[3];
460 	const struct auth_hash *esph;
461 	struct mbuf *m;
462 	struct xform_data *xd;
463 	struct secasvar *sav;
464 	struct secasindex *saidx;
465 	crypto_session_t cryptoid;
466 	int hlen, skip, protoff, error, alen;
467 
468 	m = crp->crp_mbuf;
469 	xd = crp->crp_opaque;
470 	CURVNET_SET(xd->vnet);
471 	sav = xd->sav;
472 	skip = xd->skip;
473 	protoff = xd->protoff;
474 	cryptoid = xd->cryptoid;
475 	saidx = &sav->sah->saidx;
476 	esph = sav->tdb_authalgxform;
477 
478 	/* Check for crypto errors */
479 	if (crp->crp_etype) {
480 		if (crp->crp_etype == EAGAIN) {
481 			/* Reset the session ID */
482 			if (ipsec_updateid(sav, &crp->crp_session, &cryptoid) != 0)
483 				crypto_freesession(cryptoid);
484 			xd->cryptoid = crp->crp_session;
485 			CURVNET_RESTORE();
486 			return (crypto_dispatch(crp));
487 		}
488 
489 		/* EBADMSG indicates authentication failure. */
490 		if (!(crp->crp_etype == EBADMSG && esph != NULL)) {
491 			ESPSTAT_INC(esps_noxform);
492 			DPRINTF(("%s: crypto error %d\n", __func__,
493 				crp->crp_etype));
494 			error = crp->crp_etype;
495 			goto bad;
496 		}
497 	}
498 
499 	/* Shouldn't happen... */
500 	if (m == NULL) {
501 		ESPSTAT_INC(esps_crypto);
502 		DPRINTF(("%s: bogus returned buffer from crypto\n", __func__));
503 		error = EINVAL;
504 		goto bad;
505 	}
506 	ESPSTAT_INC(esps_hist[sav->alg_enc]);
507 
508 	/* If authentication was performed, check now. */
509 	if (esph != NULL) {
510 		alen = xform_ah_authsize(esph);
511 		AHSTAT_INC(ahs_hist[sav->alg_auth]);
512 		if (crp->crp_etype == EBADMSG) {
513 			DPRINTF(("%s: authentication hash mismatch for "
514 			    "packet in SA %s/%08lx\n", __func__,
515 			    ipsec_address(&saidx->dst, buf, sizeof(buf)),
516 			    (u_long) ntohl(sav->spi)));
517 			ESPSTAT_INC(esps_badauth);
518 			error = EACCES;
519 			goto bad;
520 		}
521 		m->m_flags |= M_AUTHIPDGM;
522 		/* Remove trailing authenticator */
523 		m_adj(m, -alen);
524 	}
525 
526 	/* Release the crypto descriptors */
527 	free(xd, M_XDATA), xd = NULL;
528 	crypto_freereq(crp), crp = NULL;
529 
530 	/*
531 	 * Packet is now decrypted.
532 	 */
533 	m->m_flags |= M_DECRYPTED;
534 
535 	/*
536 	 * Update replay sequence number, if appropriate.
537 	 */
538 	if (sav->replay) {
539 		u_int32_t seq;
540 
541 		m_copydata(m, skip + offsetof(struct newesp, esp_seq),
542 			   sizeof (seq), (caddr_t) &seq);
543 		SECASVAR_LOCK(sav);
544 		if (ipsec_updatereplay(ntohl(seq), sav)) {
545 			SECASVAR_UNLOCK(sav);
546 			DPRINTF(("%s: packet replay check for %s\n", __func__,
547 			    ipsec_sa2str(sav, buf, sizeof(buf))));
548 			ESPSTAT_INC(esps_replay);
549 			error = EACCES;
550 			goto bad;
551 		}
552 		SECASVAR_UNLOCK(sav);
553 	}
554 
555 	/* Determine the ESP header length */
556 	if (sav->flags & SADB_X_EXT_OLD)
557 		hlen = sizeof (struct esp) + sav->ivlen;
558 	else
559 		hlen = sizeof (struct newesp) + sav->ivlen;
560 
561 	/* Remove the ESP header and IV from the mbuf. */
562 	error = m_striphdr(m, skip, hlen);
563 	if (error) {
564 		ESPSTAT_INC(esps_hdrops);
565 		DPRINTF(("%s: bad mbuf chain, SA %s/%08lx\n", __func__,
566 		    ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
567 		    (u_long) ntohl(sav->spi)));
568 		goto bad;
569 	}
570 
571 	/* Save the last three bytes of decrypted data */
572 	m_copydata(m, m->m_pkthdr.len - 3, 3, lastthree);
573 
574 	/* Verify pad length */
575 	if (lastthree[1] + 2 > m->m_pkthdr.len - skip) {
576 		ESPSTAT_INC(esps_badilen);
577 		DPRINTF(("%s: invalid padding length %d for %u byte packet "
578 		    "in SA %s/%08lx\n", __func__, lastthree[1],
579 		    m->m_pkthdr.len - skip,
580 		    ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
581 		    (u_long) ntohl(sav->spi)));
582 		error = EINVAL;
583 		goto bad;
584 	}
585 
586 	/* Verify correct decryption by checking the last padding bytes */
587 	if ((sav->flags & SADB_X_EXT_PMASK) != SADB_X_EXT_PRAND) {
588 		if (lastthree[1] != lastthree[0] && lastthree[1] != 0) {
589 			ESPSTAT_INC(esps_badenc);
590 			DPRINTF(("%s: decryption failed for packet in "
591 			    "SA %s/%08lx\n", __func__, ipsec_address(
592 			    &sav->sah->saidx.dst, buf, sizeof(buf)),
593 			    (u_long) ntohl(sav->spi)));
594 			error = EINVAL;
595 			goto bad;
596 		}
597 	}
598 
599 	/*
600 	 * RFC4303 2.6:
601 	 * Silently drop packet if next header field is IPPROTO_NONE.
602 	 */
603 	if (lastthree[2] == IPPROTO_NONE)
604 		goto bad;
605 
606 	/* Trim the mbuf chain to remove trailing authenticator and padding */
607 	m_adj(m, -(lastthree[1] + 2));
608 
609 	/* Restore the Next Protocol field */
610 	m_copyback(m, protoff, sizeof (u_int8_t), lastthree + 2);
611 
612 	switch (saidx->dst.sa.sa_family) {
613 #ifdef INET6
614 	case AF_INET6:
615 		error = ipsec6_common_input_cb(m, sav, skip, protoff);
616 		break;
617 #endif
618 #ifdef INET
619 	case AF_INET:
620 		error = ipsec4_common_input_cb(m, sav, skip, protoff);
621 		break;
622 #endif
623 	default:
624 		panic("%s: Unexpected address family: %d saidx=%p", __func__,
625 		    saidx->dst.sa.sa_family, saidx);
626 	}
627 	CURVNET_RESTORE();
628 	return error;
629 bad:
630 	CURVNET_RESTORE();
631 	if (sav != NULL)
632 		key_freesav(&sav);
633 	if (m != NULL)
634 		m_freem(m);
635 	if (xd != NULL)
636 		free(xd, M_XDATA);
637 	if (crp != NULL)
638 		crypto_freereq(crp);
639 	return error;
640 }
641 /*
642  * ESP output routine, called by ipsec[46]_perform_request().
643  */
644 static int
645 esp_output(struct mbuf *m, struct secpolicy *sp, struct secasvar *sav,
646     u_int idx, int skip, int protoff)
647 {
648 	IPSEC_DEBUG_DECLARE(char buf[IPSEC_ADDRSTRLEN]);
649 	struct cryptop *crp;
650 	const struct auth_hash *esph;
651 	const struct enc_xform *espx;
652 	struct mbuf *mo = NULL;
653 	struct xform_data *xd;
654 	struct secasindex *saidx;
655 	unsigned char *pad;
656 	uint8_t *ivp;
657 	uint64_t cntr;
658 	crypto_session_t cryptoid;
659 	int hlen, rlen, padding, blks, alen, i, roff;
660 	int error, maxpacketsize;
661 	uint8_t prot;
662 
663 	IPSEC_ASSERT(sav != NULL, ("null SA"));
664 	esph = sav->tdb_authalgxform;
665 	espx = sav->tdb_encalgxform;
666 	IPSEC_ASSERT(espx != NULL, ("null encoding xform"));
667 
668 	if (sav->flags & SADB_X_EXT_OLD)
669 		hlen = sizeof (struct esp) + sav->ivlen;
670 	else
671 		hlen = sizeof (struct newesp) + sav->ivlen;
672 
673 	rlen = m->m_pkthdr.len - skip;	/* Raw payload length. */
674 	/*
675 	 * RFC4303 2.4 Requires 4 byte alignment.
676 	 */
677 	blks = MAX(4, espx->blocksize);		/* Cipher blocksize */
678 
679 	/* XXX clamp padding length a la KAME??? */
680 	padding = ((blks - ((rlen + 2) % blks)) % blks) + 2;
681 
682 	alen = xform_ah_authsize(esph);
683 
684 	ESPSTAT_INC(esps_output);
685 
686 	saidx = &sav->sah->saidx;
687 	/* Check for maximum packet size violations. */
688 	switch (saidx->dst.sa.sa_family) {
689 #ifdef INET
690 	case AF_INET:
691 		maxpacketsize = IP_MAXPACKET;
692 		break;
693 #endif /* INET */
694 #ifdef INET6
695 	case AF_INET6:
696 		maxpacketsize = IPV6_MAXPACKET;
697 		break;
698 #endif /* INET6 */
699 	default:
700 		DPRINTF(("%s: unknown/unsupported protocol "
701 		    "family %d, SA %s/%08lx\n", __func__,
702 		    saidx->dst.sa.sa_family, ipsec_address(&saidx->dst,
703 			buf, sizeof(buf)), (u_long) ntohl(sav->spi)));
704 		ESPSTAT_INC(esps_nopf);
705 		error = EPFNOSUPPORT;
706 		goto bad;
707 	}
708 	/*
709 	DPRINTF(("%s: skip %d hlen %d rlen %d padding %d alen %d blksd %d\n",
710 		__func__, skip, hlen, rlen, padding, alen, blks)); */
711 	if (skip + hlen + rlen + padding + alen > maxpacketsize) {
712 		DPRINTF(("%s: packet in SA %s/%08lx got too big "
713 		    "(len %u, max len %u)\n", __func__,
714 		    ipsec_address(&saidx->dst, buf, sizeof(buf)),
715 		    (u_long) ntohl(sav->spi),
716 		    skip + hlen + rlen + padding + alen, maxpacketsize));
717 		ESPSTAT_INC(esps_toobig);
718 		error = EMSGSIZE;
719 		goto bad;
720 	}
721 
722 	/* Update the counters. */
723 	ESPSTAT_ADD(esps_obytes, m->m_pkthdr.len - skip);
724 
725 	m = m_unshare(m, M_NOWAIT);
726 	if (m == NULL) {
727 		DPRINTF(("%s: cannot clone mbuf chain, SA %s/%08lx\n", __func__,
728 		    ipsec_address(&saidx->dst, buf, sizeof(buf)),
729 		    (u_long) ntohl(sav->spi)));
730 		ESPSTAT_INC(esps_hdrops);
731 		error = ENOBUFS;
732 		goto bad;
733 	}
734 
735 	/* Inject ESP header. */
736 	mo = m_makespace(m, skip, hlen, &roff);
737 	if (mo == NULL) {
738 		DPRINTF(("%s: %u byte ESP hdr inject failed for SA %s/%08lx\n",
739 		    __func__, hlen, ipsec_address(&saidx->dst, buf,
740 		    sizeof(buf)), (u_long) ntohl(sav->spi)));
741 		ESPSTAT_INC(esps_hdrops);	/* XXX diffs from openbsd */
742 		error = ENOBUFS;
743 		goto bad;
744 	}
745 
746 	/* Initialize ESP header. */
747 	bcopy((caddr_t) &sav->spi, mtod(mo, caddr_t) + roff,
748 	    sizeof(uint32_t));
749 	SECASVAR_LOCK(sav);
750 	if (sav->replay) {
751 		uint32_t replay;
752 
753 #ifdef REGRESSION
754 		/* Emulate replay attack when ipsec_replay is TRUE. */
755 		if (!V_ipsec_replay)
756 #endif
757 			sav->replay->count++;
758 		replay = htonl(sav->replay->count);
759 
760 		bcopy((caddr_t) &replay, mtod(mo, caddr_t) + roff +
761 		    sizeof(uint32_t), sizeof(uint32_t));
762 	}
763 	cryptoid = sav->tdb_cryptoid;
764 	if (SAV_ISCTRORGCM(sav))
765 		cntr = sav->cntr++;
766 	SECASVAR_UNLOCK(sav);
767 
768 	/*
769 	 * Add padding -- better to do it ourselves than use the crypto engine,
770 	 * although if/when we support compression, we'd have to do that.
771 	 */
772 	pad = (u_char *) m_pad(m, padding + alen);
773 	if (pad == NULL) {
774 		DPRINTF(("%s: m_pad failed for SA %s/%08lx\n", __func__,
775 		    ipsec_address(&saidx->dst, buf, sizeof(buf)),
776 		    (u_long) ntohl(sav->spi)));
777 		m = NULL;		/* NB: free'd by m_pad */
778 		error = ENOBUFS;
779 		goto bad;
780 	}
781 
782 	/*
783 	 * Add padding: random, zero, or self-describing.
784 	 * XXX catch unexpected setting
785 	 */
786 	switch (sav->flags & SADB_X_EXT_PMASK) {
787 	case SADB_X_EXT_PRAND:
788 		arc4random_buf(pad, padding - 2);
789 		break;
790 	case SADB_X_EXT_PZERO:
791 		bzero(pad, padding - 2);
792 		break;
793 	case SADB_X_EXT_PSEQ:
794 		for (i = 0; i < padding - 2; i++)
795 			pad[i] = i+1;
796 		break;
797 	}
798 
799 	/* Fix padding length and Next Protocol in padding itself. */
800 	pad[padding - 2] = padding - 2;
801 	m_copydata(m, protoff, sizeof(u_int8_t), pad + padding - 1);
802 
803 	/* Fix Next Protocol in IPv4/IPv6 header. */
804 	prot = IPPROTO_ESP;
805 	m_copyback(m, protoff, sizeof(u_int8_t), (u_char *) &prot);
806 
807 	/* Get crypto descriptor. */
808 	crp = crypto_getreq(cryptoid, M_NOWAIT);
809 	if (crp == NULL) {
810 		DPRINTF(("%s: failed to acquire crypto descriptor\n",
811 			__func__));
812 		ESPSTAT_INC(esps_crypto);
813 		error = ENOBUFS;
814 		goto bad;
815 	}
816 
817 	/* IPsec-specific opaque crypto info. */
818 	xd =  malloc(sizeof(struct xform_data), M_XDATA, M_NOWAIT | M_ZERO);
819 	if (xd == NULL) {
820 		crypto_freereq(crp);
821 		DPRINTF(("%s: failed to allocate xform_data\n", __func__));
822 		ESPSTAT_INC(esps_crypto);
823 		error = ENOBUFS;
824 		goto bad;
825 	}
826 
827 	/* Encryption descriptor. */
828 	crp->crp_payload_start = skip + hlen;
829 	crp->crp_payload_length = m->m_pkthdr.len - (skip + hlen + alen);
830 	crp->crp_op = CRYPTO_OP_ENCRYPT;
831 
832 	/* Generate cipher and ESP IVs. */
833 	ivp = &crp->crp_iv[0];
834 	if (SAV_ISCTRORGCM(sav)) {
835 		/*
836 		 * See comment in esp_input() for details on the
837 		 * cipher IV.  A simple per-SA counter stored in
838 		 * 'cntr' is used as the explicit ESP IV.
839 		 */
840 		memcpy(ivp, sav->key_enc->key_data +
841 		    _KEYLEN(sav->key_enc) - 4, 4);
842 		be64enc(&ivp[4], cntr);
843 		if (SAV_ISCTR(sav)) {
844 			be32enc(&ivp[sav->ivlen + 4], 1);
845 		}
846 		m_copyback(m, skip + hlen - sav->ivlen, sav->ivlen, &ivp[4]);
847 		crp->crp_flags |= CRYPTO_F_IV_SEPARATE;
848 	} else if (sav->ivlen != 0) {
849 		arc4rand(ivp, sav->ivlen, 0);
850 		crp->crp_iv_start = skip + hlen - sav->ivlen;
851 		m_copyback(m, crp->crp_iv_start, sav->ivlen, ivp);
852 	}
853 
854 	/* Callback parameters */
855 	xd->sp = sp;
856 	xd->sav = sav;
857 	xd->idx = idx;
858 	xd->cryptoid = cryptoid;
859 	xd->vnet = curvnet;
860 
861 	/* Crypto operation descriptor. */
862 	crp->crp_ilen = m->m_pkthdr.len; /* Total input length. */
863 	crp->crp_flags |= CRYPTO_F_CBIFSYNC;
864 	if (V_async_crypto)
865 		crp->crp_flags |= CRYPTO_F_ASYNC | CRYPTO_F_ASYNC_KEEPORDER;
866 	crp->crp_mbuf = m;
867 	crp->crp_buf_type = CRYPTO_BUF_MBUF;
868 	crp->crp_callback = esp_output_cb;
869 	crp->crp_opaque = xd;
870 
871 	if (esph) {
872 		/* Authentication descriptor. */
873 		crp->crp_op |= CRYPTO_OP_COMPUTE_DIGEST;
874 		crp->crp_aad_start = skip;
875 		if (SAV_ISGCM(sav))
876 			crp->crp_aad_length = 8; /* RFC4106 5, SPI + SN */
877 		else
878 			crp->crp_aad_length = hlen;
879 		crp->crp_digest_start = m->m_pkthdr.len - alen;
880 	}
881 
882 	return crypto_dispatch(crp);
883 bad:
884 	if (m)
885 		m_freem(m);
886 	key_freesav(&sav);
887 	key_freesp(&sp);
888 	return (error);
889 }
890 /*
891  * ESP output callback from the crypto driver.
892  */
893 static int
894 esp_output_cb(struct cryptop *crp)
895 {
896 	struct xform_data *xd;
897 	struct secpolicy *sp;
898 	struct secasvar *sav;
899 	struct mbuf *m;
900 	crypto_session_t cryptoid;
901 	u_int idx;
902 	int error;
903 
904 	xd = (struct xform_data *) crp->crp_opaque;
905 	CURVNET_SET(xd->vnet);
906 	m = (struct mbuf *) crp->crp_buf;
907 	sp = xd->sp;
908 	sav = xd->sav;
909 	idx = xd->idx;
910 	cryptoid = xd->cryptoid;
911 
912 	/* Check for crypto errors. */
913 	if (crp->crp_etype) {
914 		if (crp->crp_etype == EAGAIN) {
915 			/* Reset the session ID */
916 			if (ipsec_updateid(sav, &crp->crp_session, &cryptoid) != 0)
917 				crypto_freesession(cryptoid);
918 			xd->cryptoid = crp->crp_session;
919 			CURVNET_RESTORE();
920 			return (crypto_dispatch(crp));
921 		}
922 		ESPSTAT_INC(esps_noxform);
923 		DPRINTF(("%s: crypto error %d\n", __func__, crp->crp_etype));
924 		error = crp->crp_etype;
925 		m_freem(m);
926 		goto bad;
927 	}
928 
929 	/* Shouldn't happen... */
930 	if (m == NULL) {
931 		ESPSTAT_INC(esps_crypto);
932 		DPRINTF(("%s: bogus returned buffer from crypto\n", __func__));
933 		error = EINVAL;
934 		goto bad;
935 	}
936 	free(xd, M_XDATA);
937 	crypto_freereq(crp);
938 	ESPSTAT_INC(esps_hist[sav->alg_enc]);
939 	if (sav->tdb_authalgxform != NULL)
940 		AHSTAT_INC(ahs_hist[sav->alg_auth]);
941 
942 #ifdef REGRESSION
943 	/* Emulate man-in-the-middle attack when ipsec_integrity is TRUE. */
944 	if (V_ipsec_integrity) {
945 		static unsigned char ipseczeroes[AH_HMAC_MAXHASHLEN];
946 		const struct auth_hash *esph;
947 
948 		/*
949 		 * Corrupt HMAC if we want to test integrity verification of
950 		 * the other side.
951 		 */
952 		esph = sav->tdb_authalgxform;
953 		if (esph !=  NULL) {
954 			int alen;
955 
956 			alen = xform_ah_authsize(esph);
957 			m_copyback(m, m->m_pkthdr.len - alen,
958 			    alen, ipseczeroes);
959 		}
960 	}
961 #endif
962 
963 	/* NB: m is reclaimed by ipsec_process_done. */
964 	error = ipsec_process_done(m, sp, sav, idx);
965 	CURVNET_RESTORE();
966 	return (error);
967 bad:
968 	CURVNET_RESTORE();
969 	free(xd, M_XDATA);
970 	crypto_freereq(crp);
971 	key_freesav(&sav);
972 	key_freesp(&sp);
973 	return (error);
974 }
975 
976 static struct xformsw esp_xformsw = {
977 	.xf_type =	XF_ESP,
978 	.xf_name =	"IPsec ESP",
979 	.xf_init =	esp_init,
980 	.xf_zeroize =	esp_zeroize,
981 	.xf_input =	esp_input,
982 	.xf_output =	esp_output,
983 };
984 
985 SYSINIT(esp_xform_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE,
986     xform_attach, &esp_xformsw);
987 SYSUNINIT(esp_xform_uninit, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE,
988     xform_detach, &esp_xformsw);
989