xref: /freebsd/sys/crypto/aesni/aesni.c (revision 99db5849f7506e765c43f4e69a7105cc888e8d5e)
1 /*-
2  * Copyright (c) 2005-2008 Pawel Jakub Dawidek <pjd@FreeBSD.org>
3  * Copyright (c) 2010 Konstantin Belousov <kib@FreeBSD.org>
4  * Copyright (c) 2014 The FreeBSD Foundation
5  * Copyright (c) 2017 Conrad Meyer <cem@FreeBSD.org>
6  * All rights reserved.
7  *
8  * Portions of this software were developed by John-Mark Gurney
9  * under sponsorship of the FreeBSD Foundation and
10  * Rubicon Communications, LLC (Netgate).
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33 
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
36 
37 #include <sys/param.h>
38 #include <sys/bus.h>
39 #include <sys/kernel.h>
40 #include <sys/kobj.h>
41 #include <sys/libkern.h>
42 #include <sys/lock.h>
43 #include <sys/malloc.h>
44 #include <sys/mbuf.h>
45 #include <sys/module.h>
46 #include <sys/mutex.h>
47 #include <sys/smp.h>
48 #include <sys/systm.h>
49 #include <sys/uio.h>
50 
51 #include <crypto/aesni/aesni.h>
52 #include <crypto/aesni/sha_sse.h>
53 #include <crypto/sha1.h>
54 #include <crypto/sha2/sha224.h>
55 #include <crypto/sha2/sha256.h>
56 
57 #include <opencrypto/cryptodev.h>
58 #include <opencrypto/gmac.h>
59 #include <cryptodev_if.h>
60 
61 #include <machine/md_var.h>
62 #include <machine/specialreg.h>
63 #if defined(__i386__)
64 #include <machine/npx.h>
65 #elif defined(__amd64__)
66 #include <machine/fpu.h>
67 #endif
68 
69 static struct mtx_padalign *ctx_mtx;
70 static struct fpu_kern_ctx **ctx_fpu;
71 
72 struct aesni_softc {
73 	int32_t cid;
74 	bool	has_aes;
75 	bool	has_sha;
76 };
77 
78 #define ACQUIRE_CTX(i, ctx)					\
79 	do {							\
80 		(i) = PCPU_GET(cpuid);				\
81 		mtx_lock(&ctx_mtx[(i)]);			\
82 		(ctx) = ctx_fpu[(i)];				\
83 	} while (0)
84 #define RELEASE_CTX(i, ctx)					\
85 	do {							\
86 		mtx_unlock(&ctx_mtx[(i)]);			\
87 		(i) = -1;					\
88 		(ctx) = NULL;					\
89 	} while (0)
90 
91 static int aesni_cipher_setup(struct aesni_session *ses,
92     const struct crypto_session_params *csp);
93 static int aesni_cipher_process(struct aesni_session *ses, struct cryptop *crp);
94 static int aesni_cipher_crypt(struct aesni_session *ses, struct cryptop *crp,
95     const struct crypto_session_params *csp);
96 static int aesni_cipher_mac(struct aesni_session *ses, struct cryptop *crp,
97     const struct crypto_session_params *csp);
98 
99 MALLOC_DEFINE(M_AESNI, "aesni_data", "AESNI Data");
100 
101 static void
102 aesni_identify(driver_t *drv, device_t parent)
103 {
104 
105 	/* NB: order 10 is so we get attached after h/w devices */
106 	if (device_find_child(parent, "aesni", -1) == NULL &&
107 	    BUS_ADD_CHILD(parent, 10, "aesni", -1) == 0)
108 		panic("aesni: could not attach");
109 }
110 
111 static void
112 detect_cpu_features(bool *has_aes, bool *has_sha)
113 {
114 
115 	*has_aes = ((cpu_feature2 & CPUID2_AESNI) != 0 &&
116 	    (cpu_feature2 & CPUID2_SSE41) != 0);
117 	*has_sha = ((cpu_stdext_feature & CPUID_STDEXT_SHA) != 0 &&
118 	    (cpu_feature2 & CPUID2_SSSE3) != 0);
119 }
120 
121 static int
122 aesni_probe(device_t dev)
123 {
124 	bool has_aes, has_sha;
125 
126 	detect_cpu_features(&has_aes, &has_sha);
127 	if (!has_aes && !has_sha) {
128 		device_printf(dev, "No AES or SHA support.\n");
129 		return (EINVAL);
130 	} else if (has_aes && has_sha)
131 		device_set_desc(dev,
132 		    "AES-CBC,AES-CCM,AES-GCM,AES-ICM,AES-XTS,SHA1,SHA256");
133 	else if (has_aes)
134 		device_set_desc(dev,
135 		    "AES-CBC,AES-CCM,AES-GCM,AES-ICM,AES-XTS");
136 	else
137 		device_set_desc(dev, "SHA1,SHA256");
138 
139 	return (0);
140 }
141 
142 static void
143 aesni_cleanctx(void)
144 {
145 	int i;
146 
147 	/* XXX - no way to return driverid */
148 	CPU_FOREACH(i) {
149 		if (ctx_fpu[i] != NULL) {
150 			mtx_destroy(&ctx_mtx[i]);
151 			fpu_kern_free_ctx(ctx_fpu[i]);
152 		}
153 		ctx_fpu[i] = NULL;
154 	}
155 	free(ctx_mtx, M_AESNI);
156 	ctx_mtx = NULL;
157 	free(ctx_fpu, M_AESNI);
158 	ctx_fpu = NULL;
159 }
160 
161 static int
162 aesni_attach(device_t dev)
163 {
164 	struct aesni_softc *sc;
165 	int i;
166 
167 	sc = device_get_softc(dev);
168 
169 	sc->cid = crypto_get_driverid(dev, sizeof(struct aesni_session),
170 	    CRYPTOCAP_F_SOFTWARE | CRYPTOCAP_F_SYNC |
171 	    CRYPTOCAP_F_ACCEL_SOFTWARE);
172 	if (sc->cid < 0) {
173 		device_printf(dev, "Could not get crypto driver id.\n");
174 		return (ENOMEM);
175 	}
176 
177 	ctx_mtx = malloc(sizeof *ctx_mtx * (mp_maxid + 1), M_AESNI,
178 	    M_WAITOK|M_ZERO);
179 	ctx_fpu = malloc(sizeof *ctx_fpu * (mp_maxid + 1), M_AESNI,
180 	    M_WAITOK|M_ZERO);
181 
182 	CPU_FOREACH(i) {
183 		ctx_fpu[i] = fpu_kern_alloc_ctx(0);
184 		mtx_init(&ctx_mtx[i], "anifpumtx", NULL, MTX_DEF|MTX_NEW);
185 	}
186 
187 	detect_cpu_features(&sc->has_aes, &sc->has_sha);
188 	return (0);
189 }
190 
191 static int
192 aesni_detach(device_t dev)
193 {
194 	struct aesni_softc *sc;
195 
196 	sc = device_get_softc(dev);
197 
198 	crypto_unregister_all(sc->cid);
199 
200 	aesni_cleanctx();
201 
202 	return (0);
203 }
204 
205 static bool
206 aesni_auth_supported(struct aesni_softc *sc,
207     const struct crypto_session_params *csp)
208 {
209 
210 	if (!sc->has_sha)
211 		return (false);
212 
213 	switch (csp->csp_auth_alg) {
214 	case CRYPTO_SHA1:
215 	case CRYPTO_SHA2_224:
216 	case CRYPTO_SHA2_256:
217 	case CRYPTO_SHA1_HMAC:
218 	case CRYPTO_SHA2_224_HMAC:
219 	case CRYPTO_SHA2_256_HMAC:
220 		break;
221 	default:
222 		return (false);
223 	}
224 
225 	return (true);
226 }
227 
228 static bool
229 aesni_cipher_supported(struct aesni_softc *sc,
230     const struct crypto_session_params *csp)
231 {
232 
233 	if (!sc->has_aes)
234 		return (false);
235 
236 	switch (csp->csp_cipher_alg) {
237 	case CRYPTO_AES_CBC:
238 	case CRYPTO_AES_ICM:
239 		if (csp->csp_ivlen != AES_BLOCK_LEN)
240 			return (false);
241 		return (sc->has_aes);
242 	case CRYPTO_AES_XTS:
243 		if (csp->csp_ivlen != AES_XTS_IV_LEN)
244 			return (false);
245 		return (sc->has_aes);
246 	default:
247 		return (false);
248 	}
249 }
250 
251 static int
252 aesni_probesession(device_t dev, const struct crypto_session_params *csp)
253 {
254 	struct aesni_softc *sc;
255 
256 	sc = device_get_softc(dev);
257 	if ((csp->csp_flags & ~(CSP_F_SEPARATE_OUTPUT | CSP_F_SEPARATE_AAD)) !=
258 	    0)
259 		return (EINVAL);
260 	switch (csp->csp_mode) {
261 	case CSP_MODE_DIGEST:
262 		if (!aesni_auth_supported(sc, csp))
263 			return (EINVAL);
264 		break;
265 	case CSP_MODE_CIPHER:
266 		if (!aesni_cipher_supported(sc, csp))
267 			return (EINVAL);
268 		break;
269 	case CSP_MODE_AEAD:
270 		switch (csp->csp_cipher_alg) {
271 		case CRYPTO_AES_NIST_GCM_16:
272 			if (csp->csp_auth_mlen != 0 &&
273 			    csp->csp_auth_mlen != GMAC_DIGEST_LEN)
274 				return (EINVAL);
275 			if (csp->csp_ivlen != AES_GCM_IV_LEN ||
276 			    !sc->has_aes)
277 				return (EINVAL);
278 			break;
279 		case CRYPTO_AES_CCM_16:
280 			if (csp->csp_auth_mlen != 0 &&
281 			    csp->csp_auth_mlen != AES_CBC_MAC_HASH_LEN)
282 				return (EINVAL);
283 			if (csp->csp_ivlen != AES_CCM_IV_LEN ||
284 			    !sc->has_aes)
285 				return (EINVAL);
286 			break;
287 		default:
288 			return (EINVAL);
289 		}
290 		break;
291 	case CSP_MODE_ETA:
292 		if (!aesni_auth_supported(sc, csp) ||
293 		    !aesni_cipher_supported(sc, csp))
294 			return (EINVAL);
295 		break;
296 	default:
297 		return (EINVAL);
298 	}
299 
300 	return (CRYPTODEV_PROBE_ACCEL_SOFTWARE);
301 }
302 
303 static int
304 aesni_newsession(device_t dev, crypto_session_t cses,
305     const struct crypto_session_params *csp)
306 {
307 	struct aesni_softc *sc;
308 	struct aesni_session *ses;
309 	int error;
310 
311 	sc = device_get_softc(dev);
312 
313 	ses = crypto_get_driver_session(cses);
314 
315 	switch (csp->csp_mode) {
316 	case CSP_MODE_DIGEST:
317 	case CSP_MODE_CIPHER:
318 	case CSP_MODE_AEAD:
319 	case CSP_MODE_ETA:
320 		break;
321 	default:
322 		return (EINVAL);
323 	}
324 	error = aesni_cipher_setup(ses, csp);
325 	if (error != 0) {
326 		CRYPTDEB("setup failed");
327 		return (error);
328 	}
329 
330 	return (0);
331 }
332 
333 static int
334 aesni_process(device_t dev, struct cryptop *crp, int hint __unused)
335 {
336 	struct aesni_session *ses;
337 	int error;
338 
339 	ses = crypto_get_driver_session(crp->crp_session);
340 
341 	error = aesni_cipher_process(ses, crp);
342 
343 	crp->crp_etype = error;
344 	crypto_done(crp);
345 	return (0);
346 }
347 
348 static uint8_t *
349 aesni_cipher_alloc(struct cryptop *crp, int start, int length, bool *allocated)
350 {
351 	uint8_t *addr;
352 
353 	addr = crypto_contiguous_subsegment(crp, start, length);
354 	if (addr != NULL) {
355 		*allocated = false;
356 		return (addr);
357 	}
358 	addr = malloc(length, M_AESNI, M_NOWAIT);
359 	if (addr != NULL) {
360 		*allocated = true;
361 		crypto_copydata(crp, start, length, addr);
362 	} else
363 		*allocated = false;
364 	return (addr);
365 }
366 
367 static device_method_t aesni_methods[] = {
368 	DEVMETHOD(device_identify, aesni_identify),
369 	DEVMETHOD(device_probe, aesni_probe),
370 	DEVMETHOD(device_attach, aesni_attach),
371 	DEVMETHOD(device_detach, aesni_detach),
372 
373 	DEVMETHOD(cryptodev_probesession, aesni_probesession),
374 	DEVMETHOD(cryptodev_newsession, aesni_newsession),
375 	DEVMETHOD(cryptodev_process, aesni_process),
376 
377 	DEVMETHOD_END
378 };
379 
380 static driver_t aesni_driver = {
381 	"aesni",
382 	aesni_methods,
383 	sizeof(struct aesni_softc),
384 };
385 static devclass_t aesni_devclass;
386 
387 DRIVER_MODULE(aesni, nexus, aesni_driver, aesni_devclass, 0, 0);
388 MODULE_VERSION(aesni, 1);
389 MODULE_DEPEND(aesni, crypto, 1, 1, 1);
390 
391 static int
392 intel_sha1_update(void *vctx, const void *vdata, u_int datalen)
393 {
394 	struct sha1_ctxt *ctx = vctx;
395 	const char *data = vdata;
396 	size_t gaplen;
397 	size_t gapstart;
398 	size_t off;
399 	size_t copysiz;
400 	u_int blocks;
401 
402 	off = 0;
403 	/* Do any aligned blocks without redundant copying. */
404 	if (datalen >= 64 && ctx->count % 64 == 0) {
405 		blocks = datalen / 64;
406 		ctx->c.b64[0] += blocks * 64 * 8;
407 		intel_sha1_step(ctx->h.b32, data + off, blocks);
408 		off += blocks * 64;
409 	}
410 
411 	while (off < datalen) {
412 		gapstart = ctx->count % 64;
413 		gaplen = 64 - gapstart;
414 
415 		copysiz = (gaplen < datalen - off) ? gaplen : datalen - off;
416 		bcopy(&data[off], &ctx->m.b8[gapstart], copysiz);
417 		ctx->count += copysiz;
418 		ctx->count %= 64;
419 		ctx->c.b64[0] += copysiz * 8;
420 		if (ctx->count % 64 == 0)
421 			intel_sha1_step(ctx->h.b32, (void *)ctx->m.b8, 1);
422 		off += copysiz;
423 	}
424 
425 	return (0);
426 }
427 
428 static void
429 SHA1_Init_fn(void *ctx)
430 {
431 	sha1_init(ctx);
432 }
433 
434 static void
435 SHA1_Finalize_fn(void *digest, void *ctx)
436 {
437 	sha1_result(ctx, digest);
438 }
439 
440 static int
441 intel_sha256_update(void *vctx, const void *vdata, u_int len)
442 {
443 	SHA256_CTX *ctx = vctx;
444 	uint64_t bitlen;
445 	uint32_t r;
446 	u_int blocks;
447 	const unsigned char *src = vdata;
448 
449 	/* Number of bytes left in the buffer from previous updates */
450 	r = (ctx->count >> 3) & 0x3f;
451 
452 	/* Convert the length into a number of bits */
453 	bitlen = len << 3;
454 
455 	/* Update number of bits */
456 	ctx->count += bitlen;
457 
458 	/* Handle the case where we don't need to perform any transforms */
459 	if (len < 64 - r) {
460 		memcpy(&ctx->buf[r], src, len);
461 		return (0);
462 	}
463 
464 	/* Finish the current block */
465 	memcpy(&ctx->buf[r], src, 64 - r);
466 	intel_sha256_step(ctx->state, ctx->buf, 1);
467 	src += 64 - r;
468 	len -= 64 - r;
469 
470 	/* Perform complete blocks */
471 	if (len >= 64) {
472 		blocks = len / 64;
473 		intel_sha256_step(ctx->state, src, blocks);
474 		src += blocks * 64;
475 		len -= blocks * 64;
476 	}
477 
478 	/* Copy left over data into buffer */
479 	memcpy(ctx->buf, src, len);
480 
481 	return (0);
482 }
483 
484 static void
485 SHA224_Init_fn(void *ctx)
486 {
487 	SHA224_Init(ctx);
488 }
489 
490 static void
491 SHA224_Finalize_fn(void *digest, void *ctx)
492 {
493 	SHA224_Final(digest, ctx);
494 }
495 
496 static void
497 SHA256_Init_fn(void *ctx)
498 {
499 	SHA256_Init(ctx);
500 }
501 
502 static void
503 SHA256_Finalize_fn(void *digest, void *ctx)
504 {
505 	SHA256_Final(digest, ctx);
506 }
507 
508 static int
509 aesni_authprepare(struct aesni_session *ses, int klen)
510 {
511 
512 	if (klen > SHA1_BLOCK_LEN)
513 		return (EINVAL);
514 	if ((ses->hmac && klen == 0) || (!ses->hmac && klen != 0))
515 		return (EINVAL);
516 	return (0);
517 }
518 
519 static int
520 aesni_cipherprepare(const struct crypto_session_params *csp)
521 {
522 
523 	switch (csp->csp_cipher_alg) {
524 	case CRYPTO_AES_ICM:
525 	case CRYPTO_AES_NIST_GCM_16:
526 	case CRYPTO_AES_CCM_16:
527 	case CRYPTO_AES_CBC:
528 		switch (csp->csp_cipher_klen * 8) {
529 		case 128:
530 		case 192:
531 		case 256:
532 			break;
533 		default:
534 			CRYPTDEB("invalid CBC/ICM/GCM key length");
535 			return (EINVAL);
536 		}
537 		break;
538 	case CRYPTO_AES_XTS:
539 		switch (csp->csp_cipher_klen * 8) {
540 		case 256:
541 		case 512:
542 			break;
543 		default:
544 			CRYPTDEB("invalid XTS key length");
545 			return (EINVAL);
546 		}
547 		break;
548 	default:
549 		return (EINVAL);
550 	}
551 	return (0);
552 }
553 
554 static int
555 aesni_cipher_setup(struct aesni_session *ses,
556     const struct crypto_session_params *csp)
557 {
558 	struct fpu_kern_ctx *ctx;
559 	int kt, ctxidx, error;
560 
561 	switch (csp->csp_auth_alg) {
562 	case CRYPTO_SHA1_HMAC:
563 		ses->hmac = true;
564 		/* FALLTHROUGH */
565 	case CRYPTO_SHA1:
566 		ses->hash_len = SHA1_HASH_LEN;
567 		ses->hash_init = SHA1_Init_fn;
568 		ses->hash_update = intel_sha1_update;
569 		ses->hash_finalize = SHA1_Finalize_fn;
570 		break;
571 	case CRYPTO_SHA2_224_HMAC:
572 		ses->hmac = true;
573 		/* FALLTHROUGH */
574 	case CRYPTO_SHA2_224:
575 		ses->hash_len = SHA2_224_HASH_LEN;
576 		ses->hash_init = SHA224_Init_fn;
577 		ses->hash_update = intel_sha256_update;
578 		ses->hash_finalize = SHA224_Finalize_fn;
579 		break;
580 	case CRYPTO_SHA2_256_HMAC:
581 		ses->hmac = true;
582 		/* FALLTHROUGH */
583 	case CRYPTO_SHA2_256:
584 		ses->hash_len = SHA2_256_HASH_LEN;
585 		ses->hash_init = SHA256_Init_fn;
586 		ses->hash_update = intel_sha256_update;
587 		ses->hash_finalize = SHA256_Finalize_fn;
588 		break;
589 	}
590 
591 	if (ses->hash_len != 0) {
592 		if (csp->csp_auth_mlen == 0)
593 			ses->mlen = ses->hash_len;
594 		else
595 			ses->mlen = csp->csp_auth_mlen;
596 
597 		error = aesni_authprepare(ses, csp->csp_auth_klen);
598 		if (error != 0)
599 			return (error);
600 	}
601 
602 	error = aesni_cipherprepare(csp);
603 	if (error != 0)
604 		return (error);
605 
606 	kt = is_fpu_kern_thread(0) || (csp->csp_cipher_alg == 0);
607 	if (!kt) {
608 		ACQUIRE_CTX(ctxidx, ctx);
609 		fpu_kern_enter(curthread, ctx,
610 		    FPU_KERN_NORMAL | FPU_KERN_KTHR);
611 	}
612 
613 	error = 0;
614 	if (csp->csp_cipher_key != NULL)
615 		aesni_cipher_setup_common(ses, csp, csp->csp_cipher_key,
616 		    csp->csp_cipher_klen);
617 
618 	if (!kt) {
619 		fpu_kern_leave(curthread, ctx);
620 		RELEASE_CTX(ctxidx, ctx);
621 	}
622 	return (error);
623 }
624 
625 static int
626 aesni_cipher_process(struct aesni_session *ses, struct cryptop *crp)
627 {
628 	const struct crypto_session_params *csp;
629 	struct fpu_kern_ctx *ctx;
630 	int error, ctxidx;
631 	bool kt;
632 
633 	csp = crypto_get_params(crp->crp_session);
634 	switch (csp->csp_cipher_alg) {
635 	case CRYPTO_AES_ICM:
636 	case CRYPTO_AES_NIST_GCM_16:
637 	case CRYPTO_AES_CCM_16:
638 		if ((crp->crp_flags & CRYPTO_F_IV_SEPARATE) == 0)
639 			return (EINVAL);
640 		break;
641 	case CRYPTO_AES_CBC:
642 	case CRYPTO_AES_XTS:
643 		/* CBC & XTS can only handle full blocks for now */
644 		if ((crp->crp_payload_length % AES_BLOCK_LEN) != 0)
645 			return (EINVAL);
646 		break;
647 	}
648 
649 	ctx = NULL;
650 	ctxidx = 0;
651 	error = 0;
652 	kt = is_fpu_kern_thread(0);
653 	if (!kt) {
654 		ACQUIRE_CTX(ctxidx, ctx);
655 		fpu_kern_enter(curthread, ctx,
656 		    FPU_KERN_NORMAL | FPU_KERN_KTHR);
657 	}
658 
659 	/* Do work */
660 	if (csp->csp_mode == CSP_MODE_ETA) {
661 		if (CRYPTO_OP_IS_ENCRYPT(crp->crp_op)) {
662 			error = aesni_cipher_crypt(ses, crp, csp);
663 			if (error == 0)
664 				error = aesni_cipher_mac(ses, crp, csp);
665 		} else {
666 			error = aesni_cipher_mac(ses, crp, csp);
667 			if (error == 0)
668 				error = aesni_cipher_crypt(ses, crp, csp);
669 		}
670 	} else if (csp->csp_mode == CSP_MODE_DIGEST)
671 		error = aesni_cipher_mac(ses, crp, csp);
672 	else
673 		error = aesni_cipher_crypt(ses, crp, csp);
674 
675 	if (!kt) {
676 		fpu_kern_leave(curthread, ctx);
677 		RELEASE_CTX(ctxidx, ctx);
678 	}
679 	return (error);
680 }
681 
682 static int
683 aesni_cipher_crypt(struct aesni_session *ses, struct cryptop *crp,
684     const struct crypto_session_params *csp)
685 {
686 	uint8_t iv[AES_BLOCK_LEN], tag[GMAC_DIGEST_LEN];
687 	uint8_t *authbuf, *buf, *outbuf;
688 	int error;
689 	bool encflag, allocated, authallocated, outallocated, outcopy;
690 
691 	buf = aesni_cipher_alloc(crp, crp->crp_payload_start,
692 	    crp->crp_payload_length, &allocated);
693 	if (buf == NULL)
694 		return (ENOMEM);
695 
696 	outallocated = false;
697 	authallocated = false;
698 	authbuf = NULL;
699 	if (csp->csp_cipher_alg == CRYPTO_AES_NIST_GCM_16 ||
700 	    csp->csp_cipher_alg == CRYPTO_AES_CCM_16) {
701 		if (crp->crp_aad != NULL)
702 			authbuf = crp->crp_aad;
703 		else
704 			authbuf = aesni_cipher_alloc(crp, crp->crp_aad_start,
705 			    crp->crp_aad_length, &authallocated);
706 		if (authbuf == NULL) {
707 			error = ENOMEM;
708 			goto out;
709 		}
710 	}
711 
712 	if (CRYPTO_HAS_OUTPUT_BUFFER(crp)) {
713 		outbuf = crypto_buffer_contiguous_subsegment(&crp->crp_obuf,
714 		    crp->crp_payload_output_start, crp->crp_payload_length);
715 		if (outbuf == NULL) {
716 			outcopy = true;
717 			if (allocated)
718 				outbuf = buf;
719 			else {
720 				outbuf = malloc(crp->crp_payload_length,
721 				    M_AESNI, M_NOWAIT);
722 				if (outbuf == NULL) {
723 					error = ENOMEM;
724 					goto out;
725 				}
726 				outallocated = true;
727 			}
728 		} else
729 			outcopy = false;
730 	} else {
731 		outbuf = buf;
732 		outcopy = allocated;
733 	}
734 
735 	error = 0;
736 	encflag = CRYPTO_OP_IS_ENCRYPT(crp->crp_op);
737 	if (crp->crp_cipher_key != NULL)
738 		aesni_cipher_setup_common(ses, csp, crp->crp_cipher_key,
739 		    csp->csp_cipher_klen);
740 
741 	crypto_read_iv(crp, iv);
742 
743 	switch (csp->csp_cipher_alg) {
744 	case CRYPTO_AES_CBC:
745 		if (encflag)
746 			aesni_encrypt_cbc(ses->rounds, ses->enc_schedule,
747 			    crp->crp_payload_length, buf, outbuf, iv);
748 		else {
749 			if (buf != outbuf)
750 				memcpy(outbuf, buf, crp->crp_payload_length);
751 			aesni_decrypt_cbc(ses->rounds, ses->dec_schedule,
752 			    crp->crp_payload_length, outbuf, iv);
753 		}
754 		break;
755 	case CRYPTO_AES_ICM:
756 		/* encryption & decryption are the same */
757 		aesni_encrypt_icm(ses->rounds, ses->enc_schedule,
758 		    crp->crp_payload_length, buf, outbuf, iv);
759 		break;
760 	case CRYPTO_AES_XTS:
761 		if (encflag)
762 			aesni_encrypt_xts(ses->rounds, ses->enc_schedule,
763 			    ses->xts_schedule, crp->crp_payload_length, buf,
764 			    outbuf, iv);
765 		else
766 			aesni_decrypt_xts(ses->rounds, ses->dec_schedule,
767 			    ses->xts_schedule, crp->crp_payload_length, buf,
768 			    outbuf, iv);
769 		break;
770 	case CRYPTO_AES_NIST_GCM_16:
771 		if (encflag) {
772 			memset(tag, 0, sizeof(tag));
773 			AES_GCM_encrypt(buf, outbuf, authbuf, iv, tag,
774 			    crp->crp_payload_length, crp->crp_aad_length,
775 			    csp->csp_ivlen, ses->enc_schedule, ses->rounds);
776 			crypto_copyback(crp, crp->crp_digest_start, sizeof(tag),
777 			    tag);
778 		} else {
779 			crypto_copydata(crp, crp->crp_digest_start, sizeof(tag),
780 			    tag);
781 			if (!AES_GCM_decrypt(buf, outbuf, authbuf, iv, tag,
782 			    crp->crp_payload_length, crp->crp_aad_length,
783 			    csp->csp_ivlen, ses->enc_schedule, ses->rounds))
784 				error = EBADMSG;
785 		}
786 		break;
787 	case CRYPTO_AES_CCM_16:
788 		if (encflag) {
789 			memset(tag, 0, sizeof(tag));
790 			AES_CCM_encrypt(buf, outbuf, authbuf, iv, tag,
791 			    crp->crp_payload_length, crp->crp_aad_length,
792 			    csp->csp_ivlen, ses->enc_schedule, ses->rounds);
793 			crypto_copyback(crp, crp->crp_digest_start, sizeof(tag),
794 			    tag);
795 		} else {
796 			crypto_copydata(crp, crp->crp_digest_start, sizeof(tag),
797 			    tag);
798 			if (!AES_CCM_decrypt(buf, outbuf, authbuf, iv, tag,
799 			    crp->crp_payload_length, crp->crp_aad_length,
800 			    csp->csp_ivlen, ses->enc_schedule, ses->rounds))
801 				error = EBADMSG;
802 		}
803 		break;
804 	}
805 	if (outcopy && error == 0)
806 		crypto_copyback(crp, CRYPTO_HAS_OUTPUT_BUFFER(crp) ?
807 		    crp->crp_payload_output_start : crp->crp_payload_start,
808 		    crp->crp_payload_length, outbuf);
809 
810 out:
811 	if (allocated) {
812 		explicit_bzero(buf, crp->crp_payload_length);
813 		free(buf, M_AESNI);
814 	}
815 	if (authallocated) {
816 		explicit_bzero(authbuf, crp->crp_aad_length);
817 		free(authbuf, M_AESNI);
818 	}
819 	if (outallocated) {
820 		explicit_bzero(outbuf, crp->crp_payload_length);
821 		free(outbuf, M_AESNI);
822 	}
823 	explicit_bzero(iv, sizeof(iv));
824 	explicit_bzero(tag, sizeof(tag));
825 	return (error);
826 }
827 
828 static int
829 aesni_cipher_mac(struct aesni_session *ses, struct cryptop *crp,
830     const struct crypto_session_params *csp)
831 {
832 	union {
833 		struct SHA256Context sha2 __aligned(16);
834 		struct sha1_ctxt sha1 __aligned(16);
835 	} sctx;
836 	uint32_t res[SHA2_256_HASH_LEN / sizeof(uint32_t)];
837 	const uint8_t *key;
838 	int i, keylen;
839 
840 	if (crp->crp_auth_key != NULL)
841 		key = crp->crp_auth_key;
842 	else
843 		key = csp->csp_auth_key;
844 	keylen = csp->csp_auth_klen;
845 
846 	if (ses->hmac) {
847 		uint8_t hmac_key[SHA1_BLOCK_LEN] __aligned(16);
848 
849 		/* Inner hash: (K ^ IPAD) || data */
850 		ses->hash_init(&sctx);
851 		for (i = 0; i < keylen; i++)
852 			hmac_key[i] = key[i] ^ HMAC_IPAD_VAL;
853 		for (i = keylen; i < sizeof(hmac_key); i++)
854 			hmac_key[i] = 0 ^ HMAC_IPAD_VAL;
855 		ses->hash_update(&sctx, hmac_key, sizeof(hmac_key));
856 
857 		if (crp->crp_aad != NULL)
858 			ses->hash_update(&sctx, crp->crp_aad,
859 			    crp->crp_aad_length);
860 		else
861 			crypto_apply(crp, crp->crp_aad_start,
862 			    crp->crp_aad_length, ses->hash_update, &sctx);
863 		if (CRYPTO_HAS_OUTPUT_BUFFER(crp) &&
864 		    CRYPTO_OP_IS_ENCRYPT(crp->crp_op))
865 			crypto_apply_buf(&crp->crp_obuf,
866 			    crp->crp_payload_output_start,
867 			    crp->crp_payload_length,
868 			    ses->hash_update, &sctx);
869 		else
870 			crypto_apply(crp, crp->crp_payload_start,
871 			    crp->crp_payload_length, ses->hash_update, &sctx);
872 		ses->hash_finalize(res, &sctx);
873 
874 		/* Outer hash: (K ^ OPAD) || inner hash */
875 		ses->hash_init(&sctx);
876 		for (i = 0; i < keylen; i++)
877 			hmac_key[i] = key[i] ^ HMAC_OPAD_VAL;
878 		for (i = keylen; i < sizeof(hmac_key); i++)
879 			hmac_key[i] = 0 ^ HMAC_OPAD_VAL;
880 		ses->hash_update(&sctx, hmac_key, sizeof(hmac_key));
881 		ses->hash_update(&sctx, res, ses->hash_len);
882 		ses->hash_finalize(res, &sctx);
883 		explicit_bzero(hmac_key, sizeof(hmac_key));
884 	} else {
885 		ses->hash_init(&sctx);
886 
887 		if (crp->crp_aad != NULL)
888 			ses->hash_update(&sctx, crp->crp_aad,
889 			    crp->crp_aad_length);
890 		else
891 			crypto_apply(crp, crp->crp_aad_start,
892 			    crp->crp_aad_length, ses->hash_update, &sctx);
893 		if (CRYPTO_HAS_OUTPUT_BUFFER(crp) &&
894 		    CRYPTO_OP_IS_ENCRYPT(crp->crp_op))
895 			crypto_apply_buf(&crp->crp_obuf,
896 			    crp->crp_payload_output_start,
897 			    crp->crp_payload_length,
898 			    ses->hash_update, &sctx);
899 		else
900 			crypto_apply(crp, crp->crp_payload_start,
901 			    crp->crp_payload_length,
902 			    ses->hash_update, &sctx);
903 
904 		ses->hash_finalize(res, &sctx);
905 	}
906 
907 	if (crp->crp_op & CRYPTO_OP_VERIFY_DIGEST) {
908 		uint32_t res2[SHA2_256_HASH_LEN / sizeof(uint32_t)];
909 
910 		crypto_copydata(crp, crp->crp_digest_start, ses->mlen, res2);
911 		if (timingsafe_bcmp(res, res2, ses->mlen) != 0)
912 			return (EBADMSG);
913 		explicit_bzero(res2, sizeof(res2));
914 	} else
915 		crypto_copyback(crp, crp->crp_digest_start, ses->mlen, res);
916 	explicit_bzero(res, sizeof(res));
917 	return (0);
918 }
919