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