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