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