xref: /freebsd/sys/netipsec/xform_esp.c (revision e8e8c939350bdf3c228a411caa9660c607c27a11)
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 	char buf[128];
272 	struct auth_hash *esph;
273 	struct enc_xform *espx;
274 	struct tdb_crypto *tc;
275 	int plen, alen, hlen;
276 	struct newesp *esp;
277 	struct cryptodesc *crde;
278 	struct cryptop *crp;
279 
280 	IPSEC_ASSERT(sav != NULL, ("null SA"));
281 	IPSEC_ASSERT(sav->tdb_encalgxform != NULL, ("null encoding xform"));
282 
283 	alen = 0;
284 	/* Valid IP Packet length ? */
285 	if ( (skip&3) || (m->m_pkthdr.len&3) ){
286 		DPRINTF(("%s: misaligned packet, skip %u pkt len %u",
287 				__func__, skip, m->m_pkthdr.len));
288 		ESPSTAT_INC(esps_badilen);
289 		m_freem(m);
290 		return EINVAL;
291 	}
292 
293 	/* XXX don't pullup, just copy header */
294 	IP6_EXTHDR_GET(esp, struct newesp *, m, skip, sizeof (struct newesp));
295 
296 	esph = sav->tdb_authalgxform;
297 	espx = sav->tdb_encalgxform;
298 
299 	/* Determine the ESP header length */
300 	if (sav->flags & SADB_X_EXT_OLD)
301 		hlen = sizeof (struct esp) + sav->ivlen;
302 	else
303 		hlen = sizeof (struct newesp) + sav->ivlen;
304 	/* Authenticator hash size */
305 	if (esph != NULL) {
306 		switch (esph->type) {
307 		case CRYPTO_SHA2_256_HMAC:
308 		case CRYPTO_SHA2_384_HMAC:
309 		case CRYPTO_SHA2_512_HMAC:
310 			alen = esph->hashsize/2;
311 			break;
312 		default:
313 			alen = AH_HMAC_HASHLEN;
314 			break;
315 		}
316 	}
317 
318 	/*
319 	 * Verify payload length is multiple of encryption algorithm
320 	 * block size.
321 	 *
322 	 * NB: This works for the null algorithm because the blocksize
323 	 *     is 4 and all packets must be 4-byte aligned regardless
324 	 *     of the algorithm.
325 	 */
326 	plen = m->m_pkthdr.len - (skip + hlen + alen);
327 	if ((plen & (espx->blocksize - 1)) || (plen <= 0)) {
328 		DPRINTF(("%s: payload of %d octets not a multiple of %d octets,"
329 		    "  SA %s/%08lx\n", __func__,
330 		    plen, espx->blocksize, ipsec_address(&sav->sah->saidx.dst,
331 			buf, sizeof(buf)), (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, buf, sizeof(buf))));	/*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 	char buf[128];
435 	u_int8_t lastthree[3], aalg[AH_HMAC_MAXHASHLEN];
436 	int hlen, skip, protoff, error, alen;
437 	struct mbuf *m;
438 	struct cryptodesc *crd;
439 	struct auth_hash *esph;
440 	struct enc_xform *espx;
441 	struct tdb_crypto *tc;
442 	struct secasvar *sav;
443 	struct secasindex *saidx;
444 	caddr_t ptr;
445 
446 	crd = crp->crp_desc;
447 	IPSEC_ASSERT(crd != NULL, ("null crypto descriptor!"));
448 
449 	tc = (struct tdb_crypto *) crp->crp_opaque;
450 	IPSEC_ASSERT(tc != NULL, ("null opaque crypto data area!"));
451 	skip = tc->tc_skip;
452 	protoff = tc->tc_protoff;
453 	m = (struct mbuf *) crp->crp_buf;
454 
455 	sav = tc->tc_sav;
456 	IPSEC_ASSERT(sav != NULL, ("null SA!"));
457 
458 	saidx = &sav->sah->saidx;
459 	IPSEC_ASSERT(saidx->dst.sa.sa_family == AF_INET ||
460 		saidx->dst.sa.sa_family == AF_INET6,
461 		("unexpected protocol family %u", saidx->dst.sa.sa_family));
462 
463 	esph = sav->tdb_authalgxform;
464 	espx = sav->tdb_encalgxform;
465 
466 	/* Check for crypto errors */
467 	if (crp->crp_etype) {
468 		/* Reset the session ID */
469 		if (sav->tdb_cryptoid != 0)
470 			sav->tdb_cryptoid = crp->crp_sid;
471 
472 		if (crp->crp_etype == EAGAIN)
473 			return (crypto_dispatch(crp));
474 
475 		ESPSTAT_INC(esps_noxform);
476 		DPRINTF(("%s: crypto error %d\n", __func__, crp->crp_etype));
477 		error = crp->crp_etype;
478 		goto bad;
479 	}
480 
481 	/* Shouldn't happen... */
482 	if (m == NULL) {
483 		ESPSTAT_INC(esps_crypto);
484 		DPRINTF(("%s: bogus returned buffer from crypto\n", __func__));
485 		error = EINVAL;
486 		goto bad;
487 	}
488 	ESPSTAT_INC(esps_hist[sav->alg_enc]);
489 
490 	/* If authentication was performed, check now. */
491 	if (esph != NULL) {
492 		switch (esph->type) {
493 		case CRYPTO_SHA2_256_HMAC:
494 		case CRYPTO_SHA2_384_HMAC:
495 		case CRYPTO_SHA2_512_HMAC:
496 			alen = esph->hashsize/2;
497 			break;
498 		default:
499 			alen = AH_HMAC_HASHLEN;
500 			break;
501 		}
502 		AHSTAT_INC(ahs_hist[sav->alg_auth]);
503 		/* Copy the authenticator from the packet */
504 		m_copydata(m, m->m_pkthdr.len - alen, alen, aalg);
505 		ptr = (caddr_t) (tc + 1);
506 
507 		/* Verify authenticator */
508 		if (bcmp(ptr, aalg, alen) != 0) {
509 			DPRINTF(("%s: authentication hash mismatch for "
510 			    "packet in SA %s/%08lx\n", __func__,
511 			    ipsec_address(&saidx->dst, buf, sizeof(buf)),
512 			    (u_long) ntohl(sav->spi)));
513 			ESPSTAT_INC(esps_badauth);
514 			error = EACCES;
515 			goto bad;
516 		}
517 
518 		/* Remove trailing authenticator */
519 		m_adj(m, -alen);
520 	}
521 
522 	/* Release the crypto descriptors */
523 	free(tc, M_XDATA), tc = NULL;
524 	crypto_freereq(crp), crp = NULL;
525 
526 	/*
527 	 * Packet is now decrypted.
528 	 */
529 	m->m_flags |= M_DECRYPTED;
530 
531 	/*
532 	 * Update replay sequence number, if appropriate.
533 	 */
534 	if (sav->replay) {
535 		u_int32_t seq;
536 
537 		m_copydata(m, skip + offsetof(struct newesp, esp_seq),
538 			   sizeof (seq), (caddr_t) &seq);
539 		if (ipsec_updatereplay(ntohl(seq), sav)) {
540 			DPRINTF(("%s: packet replay check for %s\n", __func__,
541 			    ipsec_logsastr(sav, buf, sizeof(buf))));
542 			ESPSTAT_INC(esps_replay);
543 			error = ENOBUFS;
544 			goto bad;
545 		}
546 	}
547 
548 	/* Determine the ESP header length */
549 	if (sav->flags & SADB_X_EXT_OLD)
550 		hlen = sizeof (struct esp) + sav->ivlen;
551 	else
552 		hlen = sizeof (struct newesp) + sav->ivlen;
553 
554 	/* Remove the ESP header and IV from the mbuf. */
555 	error = m_striphdr(m, skip, hlen);
556 	if (error) {
557 		ESPSTAT_INC(esps_hdrops);
558 		DPRINTF(("%s: bad mbuf chain, SA %s/%08lx\n", __func__,
559 		    ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
560 		    (u_long) ntohl(sav->spi)));
561 		goto bad;
562 	}
563 
564 	/* Save the last three bytes of decrypted data */
565 	m_copydata(m, m->m_pkthdr.len - 3, 3, lastthree);
566 
567 	/* Verify pad length */
568 	if (lastthree[1] + 2 > m->m_pkthdr.len - skip) {
569 		ESPSTAT_INC(esps_badilen);
570 		DPRINTF(("%s: invalid padding length %d for %u byte packet "
571 		    "in SA %s/%08lx\n", __func__, lastthree[1],
572 		    m->m_pkthdr.len - skip,
573 		    ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
574 		    (u_long) ntohl(sav->spi)));
575 		error = EINVAL;
576 		goto bad;
577 	}
578 
579 	/* Verify correct decryption by checking the last padding bytes */
580 	if ((sav->flags & SADB_X_EXT_PMASK) != SADB_X_EXT_PRAND) {
581 		if (lastthree[1] != lastthree[0] && lastthree[1] != 0) {
582 			ESPSTAT_INC(esps_badenc);
583 			DPRINTF(("%s: decryption failed for packet in "
584 			    "SA %s/%08lx\n", __func__, ipsec_address(
585 			    &sav->sah->saidx.dst, buf, sizeof(buf)),
586 			    (u_long) ntohl(sav->spi)));
587 			error = EINVAL;
588 			goto bad;
589 		}
590 	}
591 
592 	/* Trim the mbuf chain to remove trailing authenticator and padding */
593 	m_adj(m, -(lastthree[1] + 2));
594 
595 	/* Restore the Next Protocol field */
596 	m_copyback(m, protoff, sizeof (u_int8_t), lastthree + 2);
597 
598 	switch (saidx->dst.sa.sa_family) {
599 #ifdef INET6
600 	case AF_INET6:
601 		error = ipsec6_common_input_cb(m, sav, skip, protoff);
602 		break;
603 #endif
604 #ifdef INET
605 	case AF_INET:
606 		error = ipsec4_common_input_cb(m, sav, skip, protoff);
607 		break;
608 #endif
609 	default:
610 		panic("%s: Unexpected address family: %d saidx=%p", __func__,
611 		    saidx->dst.sa.sa_family, saidx);
612 	}
613 
614 	KEY_FREESAV(&sav);
615 	return error;
616 bad:
617 	if (sav)
618 		KEY_FREESAV(&sav);
619 	if (m != NULL)
620 		m_freem(m);
621 	if (tc != NULL)
622 		free(tc, M_XDATA);
623 	if (crp != NULL)
624 		crypto_freereq(crp);
625 	return error;
626 }
627 
628 /*
629  * ESP output routine, called by ipsec[46]_process_packet().
630  */
631 static int
632 esp_output(struct mbuf *m, struct ipsecrequest *isr, struct mbuf **mp,
633     int skip, int protoff)
634 {
635 	char buf[INET6_ADDRSTRLEN];
636 	struct enc_xform *espx;
637 	struct auth_hash *esph;
638 	int hlen, rlen, padding, blks, alen, i, roff;
639 	struct mbuf *mo = (struct mbuf *) NULL;
640 	struct tdb_crypto *tc;
641 	struct secasvar *sav;
642 	struct secasindex *saidx;
643 	unsigned char *pad;
644 	u_int8_t prot;
645 	int error, maxpacketsize;
646 
647 	struct cryptodesc *crde = NULL, *crda = NULL;
648 	struct cryptop *crp;
649 
650 	sav = isr->sav;
651 	IPSEC_ASSERT(sav != NULL, ("null SA"));
652 	esph = sav->tdb_authalgxform;
653 	espx = sav->tdb_encalgxform;
654 	IPSEC_ASSERT(espx != NULL, ("null encoding xform"));
655 
656 	if (sav->flags & SADB_X_EXT_OLD)
657 		hlen = sizeof (struct esp) + sav->ivlen;
658 	else
659 		hlen = sizeof (struct newesp) + sav->ivlen;
660 
661 	rlen = m->m_pkthdr.len - skip;	/* Raw payload length. */
662 	/*
663 	 * NB: The null encoding transform has a blocksize of 4
664 	 *     so that headers are properly aligned.
665 	 */
666 	blks = espx->blocksize;		/* IV blocksize */
667 
668 	/* XXX clamp padding length a la KAME??? */
669 	padding = ((blks - ((rlen + 2) % blks)) % blks) + 2;
670 
671 	if (esph)
672 		switch (esph->type) {
673 		case CRYPTO_SHA2_256_HMAC:
674 		case CRYPTO_SHA2_384_HMAC:
675 		case CRYPTO_SHA2_512_HMAC:
676 			alen = esph->hashsize/2;
677 			break;
678 		default:
679 		alen = AH_HMAC_HASHLEN;
680 			break;
681 		}
682 	else
683 		alen = 0;
684 
685 	ESPSTAT_INC(esps_output);
686 
687 	saidx = &sav->sah->saidx;
688 	/* Check for maximum packet size violations. */
689 	switch (saidx->dst.sa.sa_family) {
690 #ifdef INET
691 	case AF_INET:
692 		maxpacketsize = IP_MAXPACKET;
693 		break;
694 #endif /* INET */
695 #ifdef INET6
696 	case AF_INET6:
697 		maxpacketsize = IPV6_MAXPACKET;
698 		break;
699 #endif /* INET6 */
700 	default:
701 		DPRINTF(("%s: unknown/unsupported protocol "
702 		    "family %d, SA %s/%08lx\n", __func__,
703 		    saidx->dst.sa.sa_family, ipsec_address(&saidx->dst,
704 			buf, sizeof(buf)), (u_long) ntohl(sav->spi)));
705 		ESPSTAT_INC(esps_nopf);
706 		error = EPFNOSUPPORT;
707 		goto bad;
708 	}
709 	if (skip + hlen + rlen + padding + alen > maxpacketsize) {
710 		DPRINTF(("%s: packet in SA %s/%08lx got too big "
711 		    "(len %u, max len %u)\n", __func__,
712 		    ipsec_address(&saidx->dst, buf, sizeof(buf)),
713 		    (u_long) ntohl(sav->spi),
714 		    skip + hlen + rlen + padding + alen, maxpacketsize));
715 		ESPSTAT_INC(esps_toobig);
716 		error = EMSGSIZE;
717 		goto bad;
718 	}
719 
720 	/* Update the counters. */
721 	ESPSTAT_ADD(esps_obytes, m->m_pkthdr.len - skip);
722 
723 	m = m_unshare(m, M_NOWAIT);
724 	if (m == NULL) {
725 		DPRINTF(("%s: cannot clone mbuf chain, SA %s/%08lx\n", __func__,
726 		    ipsec_address(&saidx->dst, buf, sizeof(buf)),
727 		    (u_long) ntohl(sav->spi)));
728 		ESPSTAT_INC(esps_hdrops);
729 		error = ENOBUFS;
730 		goto bad;
731 	}
732 
733 	/* Inject ESP header. */
734 	mo = m_makespace(m, skip, hlen, &roff);
735 	if (mo == NULL) {
736 		DPRINTF(("%s: %u byte ESP hdr inject failed for SA %s/%08lx\n",
737 		    __func__, hlen, ipsec_address(&saidx->dst, buf,
738 		    sizeof(buf)), (u_long) ntohl(sav->spi)));
739 		ESPSTAT_INC(esps_hdrops);		/* XXX diffs from openbsd */
740 		error = ENOBUFS;
741 		goto bad;
742 	}
743 
744 	/* Initialize ESP header. */
745 	bcopy((caddr_t) &sav->spi, mtod(mo, caddr_t) + roff, sizeof(u_int32_t));
746 	if (sav->replay) {
747 		u_int32_t replay;
748 
749 #ifdef REGRESSION
750 		/* Emulate replay attack when ipsec_replay is TRUE. */
751 		if (!V_ipsec_replay)
752 #endif
753 			sav->replay->count++;
754 		replay = htonl(sav->replay->count);
755 		bcopy((caddr_t) &replay,
756 		    mtod(mo, caddr_t) + roff + sizeof(u_int32_t),
757 		    sizeof(u_int32_t));
758 	}
759 
760 	/*
761 	 * Add padding -- better to do it ourselves than use the crypto engine,
762 	 * although if/when we support compression, we'd have to do that.
763 	 */
764 	pad = (u_char *) m_pad(m, padding + alen);
765 	if (pad == NULL) {
766 		DPRINTF(("%s: m_pad failed for SA %s/%08lx\n", __func__,
767 		    ipsec_address(&saidx->dst, buf, sizeof(buf)),
768 		    (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 	char buf[INET6_ADDRSTRLEN];
880 	struct tdb_crypto *tc;
881 	struct ipsecrequest *isr;
882 	struct secasvar *sav;
883 	struct mbuf *m;
884 	int error;
885 
886 	tc = (struct tdb_crypto *) crp->crp_opaque;
887 	IPSEC_ASSERT(tc != NULL, ("null opaque data area!"));
888 	m = (struct mbuf *) crp->crp_buf;
889 
890 	isr = tc->tc_isr;
891 	IPSEC_ASSERT(isr->sp != NULL, ("NULL isr->sp"));
892 	IPSECREQUEST_LOCK(isr);
893 	sav = tc->tc_sav;
894 	/* With the isr lock released SA pointer can be updated. */
895 	if (sav != isr->sav) {
896 		ESPSTAT_INC(esps_notdb);
897 		DPRINTF(("%s: SA gone during crypto (SA %s/%08lx proto %u)\n",
898 		    __func__, ipsec_address(&tc->tc_dst, buf, sizeof(buf)),
899 		    (u_long) ntohl(tc->tc_spi), tc->tc_proto));
900 		error = ENOBUFS;		/*XXX*/
901 		goto bad;
902 	}
903 
904 	/* Check for crypto errors. */
905 	if (crp->crp_etype) {
906 		/* Reset session ID. */
907 		if (sav->tdb_cryptoid != 0)
908 			sav->tdb_cryptoid = crp->crp_sid;
909 
910 		if (crp->crp_etype == EAGAIN) {
911 			IPSECREQUEST_UNLOCK(isr);
912 			return (crypto_dispatch(crp));
913 		}
914 
915 		ESPSTAT_INC(esps_noxform);
916 		DPRINTF(("%s: crypto error %d\n", __func__, crp->crp_etype));
917 		error = crp->crp_etype;
918 		goto bad;
919 	}
920 
921 	/* Shouldn't happen... */
922 	if (m == NULL) {
923 		ESPSTAT_INC(esps_crypto);
924 		DPRINTF(("%s: bogus returned buffer from crypto\n", __func__));
925 		error = EINVAL;
926 		goto bad;
927 	}
928 	ESPSTAT_INC(esps_hist[sav->alg_enc]);
929 	if (sav->tdb_authalgxform != NULL)
930 		AHSTAT_INC(ahs_hist[sav->alg_auth]);
931 
932 	/* Release crypto descriptors. */
933 	free(tc, M_XDATA);
934 	crypto_freereq(crp);
935 
936 #ifdef REGRESSION
937 	/* Emulate man-in-the-middle attack when ipsec_integrity is TRUE. */
938 	if (V_ipsec_integrity) {
939 		static unsigned char ipseczeroes[AH_HMAC_MAXHASHLEN];
940 		struct auth_hash *esph;
941 
942 		/*
943 		 * Corrupt HMAC if we want to test integrity verification of
944 		 * the other side.
945 		 */
946 		esph = sav->tdb_authalgxform;
947 		if (esph !=  NULL) {
948 			int alen;
949 
950 			switch (esph->type) {
951 			case CRYPTO_SHA2_256_HMAC:
952 			case CRYPTO_SHA2_384_HMAC:
953 			case CRYPTO_SHA2_512_HMAC:
954 				alen = esph->hashsize/2;
955 				break;
956 			default:
957 				alen = AH_HMAC_HASHLEN;
958 				break;
959 			}
960 			m_copyback(m, m->m_pkthdr.len - alen,
961 			    alen, ipseczeroes);
962 		}
963 	}
964 #endif
965 
966 	/* NB: m is reclaimed by ipsec_process_done. */
967 	error = ipsec_process_done(m, isr);
968 	KEY_FREESAV(&sav);
969 	IPSECREQUEST_UNLOCK(isr);
970 	KEY_FREESP(&isr->sp);
971 	return (error);
972 bad:
973 	if (sav)
974 		KEY_FREESAV(&sav);
975 	IPSECREQUEST_UNLOCK(isr);
976 	KEY_FREESP(&isr->sp);
977 	if (m)
978 		m_freem(m);
979 	free(tc, M_XDATA);
980 	crypto_freereq(crp);
981 	return (error);
982 }
983 
984 static struct xformsw esp_xformsw = {
985 	XF_ESP,		XFT_CONF|XFT_AUTH,	"IPsec ESP",
986 	esp_init,	esp_zeroize,		esp_input,
987 	esp_output
988 };
989 
990 static void
991 esp_attach(void)
992 {
993 
994 	xform_register(&esp_xformsw);
995 }
996 SYSINIT(esp_xform_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE, esp_attach, NULL);
997