1 /*-
2  * Copyright (c) 2018 Conrad Meyer <cem@FreeBSD.org>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  */
26 
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29 
30 #include <sys/param.h>
31 #include <sys/bus.h>
32 #include <sys/kernel.h>
33 #include <sys/kobj.h>
34 #include <sys/lock.h>
35 #include <sys/malloc.h>
36 #include <sys/module.h>
37 #include <sys/mutex.h>
38 #include <sys/rwlock.h>
39 #include <sys/smp.h>
40 
41 #include <blake2.h>
42 
43 #include <opencrypto/cryptodev.h>
44 #include <cryptodev_if.h>
45 
46 #if defined(__amd64__)
47 #include <machine/fpu.h>
48 #elif defined(__i386__)
49 #include <machine/npx.h>
50 #endif
51 
52 struct blake2_session {
53 	size_t mlen;
54 };
55 CTASSERT((size_t)BLAKE2B_KEYBYTES > (size_t)BLAKE2S_KEYBYTES);
56 
57 struct blake2_softc {
58 	bool	dying;
59 	int32_t cid;
60 	struct rwlock lock;
61 };
62 
63 static struct mtx_padalign *ctx_mtx;
64 static struct fpu_kern_ctx **ctx_fpu;
65 
66 #define ACQUIRE_CTX(i, ctx)					\
67 	do {							\
68 		(i) = PCPU_GET(cpuid);				\
69 		mtx_lock(&ctx_mtx[(i)]);			\
70 		(ctx) = ctx_fpu[(i)];				\
71 	} while (0)
72 #define RELEASE_CTX(i, ctx)					\
73 	do {							\
74 		mtx_unlock(&ctx_mtx[(i)]);			\
75 		(i) = -1;					\
76 		(ctx) = NULL;					\
77 	} while (0)
78 
79 static int blake2_cipher_setup(struct blake2_session *ses,
80     const struct crypto_session_params *csp);
81 static int blake2_cipher_process(struct blake2_session *ses,
82     struct cryptop *crp);
83 
84 MALLOC_DEFINE(M_BLAKE2, "blake2_data", "Blake2 Data");
85 
86 static void
87 blake2_identify(driver_t *drv, device_t parent)
88 {
89 
90 	/* NB: order 10 is so we get attached after h/w devices */
91 	if (device_find_child(parent, "blaketwo", -1) == NULL &&
92 	    BUS_ADD_CHILD(parent, 10, "blaketwo", -1) == 0)
93 		panic("blaketwo: could not attach");
94 }
95 
96 static int
97 blake2_probe(device_t dev)
98 {
99 	device_set_desc(dev, "Blake2");
100 	return (0);
101 }
102 
103 static void
104 blake2_cleanctx(void)
105 {
106 	int i;
107 
108 	/* XXX - no way to return driverid */
109 	CPU_FOREACH(i) {
110 		if (ctx_fpu[i] != NULL) {
111 			mtx_destroy(&ctx_mtx[i]);
112 			fpu_kern_free_ctx(ctx_fpu[i]);
113 		}
114 		ctx_fpu[i] = NULL;
115 	}
116 	free(ctx_mtx, M_BLAKE2);
117 	ctx_mtx = NULL;
118 	free(ctx_fpu, M_BLAKE2);
119 	ctx_fpu = NULL;
120 }
121 
122 static int
123 blake2_attach(device_t dev)
124 {
125 	struct blake2_softc *sc;
126 	int i;
127 
128 	sc = device_get_softc(dev);
129 	sc->dying = false;
130 
131 	sc->cid = crypto_get_driverid(dev, sizeof(struct blake2_session),
132 	    CRYPTOCAP_F_SOFTWARE | CRYPTOCAP_F_SYNC |
133 	    CRYPTOCAP_F_ACCEL_SOFTWARE);
134 	if (sc->cid < 0) {
135 		device_printf(dev, "Could not get crypto driver id.\n");
136 		return (ENOMEM);
137 	}
138 
139 	ctx_mtx = malloc(sizeof(*ctx_mtx) * (mp_maxid + 1), M_BLAKE2,
140 	    M_WAITOK | M_ZERO);
141 	ctx_fpu = malloc(sizeof(*ctx_fpu) * (mp_maxid + 1), M_BLAKE2,
142 	    M_WAITOK | M_ZERO);
143 
144 	CPU_FOREACH(i) {
145 #ifdef __amd64__
146 		ctx_fpu[i] = fpu_kern_alloc_ctx_domain(
147 		    pcpu_find(i)->pc_domain, FPU_KERN_NORMAL);
148 #else
149 		ctx_fpu[i] = fpu_kern_alloc_ctx(FPU_KERN_NORMAL);
150 #endif
151 		mtx_init(&ctx_mtx[i], "bl2fpumtx", NULL, MTX_DEF | MTX_NEW);
152 	}
153 
154 	rw_init(&sc->lock, "blake2_lock");
155 
156 	return (0);
157 }
158 
159 static int
160 blake2_detach(device_t dev)
161 {
162 	struct blake2_softc *sc;
163 
164 	sc = device_get_softc(dev);
165 
166 	rw_wlock(&sc->lock);
167 	sc->dying = true;
168 	rw_wunlock(&sc->lock);
169 	crypto_unregister_all(sc->cid);
170 
171 	rw_destroy(&sc->lock);
172 
173 	blake2_cleanctx();
174 
175 	return (0);
176 }
177 
178 static int
179 blake2_probesession(device_t dev, const struct crypto_session_params *csp)
180 {
181 
182 	if (csp->csp_flags != 0)
183 		return (EINVAL);
184 	switch (csp->csp_mode) {
185 	case CSP_MODE_DIGEST:
186 		switch (csp->csp_auth_alg) {
187 		case CRYPTO_BLAKE2B:
188 		case CRYPTO_BLAKE2S:
189 			break;
190 		default:
191 			return (EINVAL);
192 		}
193 		break;
194 	default:
195 		return (EINVAL);
196 	}
197 	return (CRYPTODEV_PROBE_ACCEL_SOFTWARE);
198 }
199 
200 static int
201 blake2_newsession(device_t dev, crypto_session_t cses,
202     const struct crypto_session_params *csp)
203 {
204 	struct blake2_softc *sc;
205 	struct blake2_session *ses;
206 	int error;
207 
208 	sc = device_get_softc(dev);
209 
210 	ses = crypto_get_driver_session(cses);
211 
212 	rw_rlock(&sc->lock);
213 	if (sc->dying) {
214 		rw_runlock(&sc->lock);
215 		return (EINVAL);
216 	}
217 	rw_runlock(&sc->lock);
218 
219 	error = blake2_cipher_setup(ses, csp);
220 	if (error != 0) {
221 		CRYPTDEB("setup failed");
222 		return (error);
223 	}
224 
225 	return (0);
226 }
227 
228 static int
229 blake2_process(device_t dev, struct cryptop *crp, int hint __unused)
230 {
231 	struct blake2_session *ses;
232 	int error;
233 
234 	ses = crypto_get_driver_session(crp->crp_session);
235 	error = blake2_cipher_process(ses, crp);
236 
237 	crp->crp_etype = error;
238 	crypto_done(crp);
239 	return (0);
240 }
241 
242 static device_method_t blake2_methods[] = {
243 	DEVMETHOD(device_identify, blake2_identify),
244 	DEVMETHOD(device_probe, blake2_probe),
245 	DEVMETHOD(device_attach, blake2_attach),
246 	DEVMETHOD(device_detach, blake2_detach),
247 
248 	DEVMETHOD(cryptodev_probesession, blake2_probesession),
249 	DEVMETHOD(cryptodev_newsession, blake2_newsession),
250 	DEVMETHOD(cryptodev_process, blake2_process),
251 
252 	DEVMETHOD_END
253 };
254 
255 static driver_t blake2_driver = {
256 	"blaketwo",
257 	blake2_methods,
258 	sizeof(struct blake2_softc),
259 };
260 static devclass_t blake2_devclass;
261 
262 DRIVER_MODULE(blake2, nexus, blake2_driver, blake2_devclass, 0, 0);
263 MODULE_VERSION(blake2, 1);
264 MODULE_DEPEND(blake2, crypto, 1, 1, 1);
265 
266 static bool
267 blake2_check_klen(const struct crypto_session_params *csp, unsigned klen)
268 {
269 
270 	if (csp->csp_auth_alg == CRYPTO_BLAKE2S)
271 		return (klen <= BLAKE2S_KEYBYTES);
272 	else
273 		return (klen <= BLAKE2B_KEYBYTES);
274 }
275 
276 static int
277 blake2_cipher_setup(struct blake2_session *ses,
278     const struct crypto_session_params *csp)
279 {
280 	int hashlen;
281 
282 	CTASSERT((size_t)BLAKE2S_OUTBYTES <= (size_t)BLAKE2B_OUTBYTES);
283 
284 	if (!blake2_check_klen(csp, csp->csp_auth_klen))
285 		return (EINVAL);
286 
287 	if (csp->csp_auth_mlen < 0)
288 		return (EINVAL);
289 
290 	switch (csp->csp_auth_alg) {
291 	case CRYPTO_BLAKE2S:
292 		hashlen = BLAKE2S_OUTBYTES;
293 		break;
294 	case CRYPTO_BLAKE2B:
295 		hashlen = BLAKE2B_OUTBYTES;
296 		break;
297 	default:
298 		return (EINVAL);
299 	}
300 
301 	if (csp->csp_auth_mlen > hashlen)
302 		return (EINVAL);
303 
304 	if (csp->csp_auth_mlen == 0)
305 		ses->mlen = hashlen;
306 	else
307 		ses->mlen = csp->csp_auth_mlen;
308 	return (0);
309 }
310 
311 static int
312 blake2b_applicator(void *state, const void *buf, u_int len)
313 {
314 	int rc;
315 
316 	rc = blake2b_update(state, buf, len);
317 	if (rc != 0)
318 		return (EINVAL);
319 	return (0);
320 }
321 
322 static int
323 blake2s_applicator(void *state, const void *buf, u_int len)
324 {
325 	int rc;
326 
327 	rc = blake2s_update(state, buf, len);
328 	if (rc != 0)
329 		return (EINVAL);
330 	return (0);
331 }
332 
333 static int
334 blake2_cipher_process(struct blake2_session *ses, struct cryptop *crp)
335 {
336 	union {
337 		blake2b_state sb;
338 		blake2s_state ss;
339 	} bctx;
340 	char res[BLAKE2B_OUTBYTES], res2[BLAKE2B_OUTBYTES];
341 	const struct crypto_session_params *csp;
342 	struct fpu_kern_ctx *ctx;
343 	const void *key;
344 	int ctxidx;
345 	bool kt;
346 	int error, rc;
347 	unsigned klen;
348 
349 	ctx = NULL;
350 	ctxidx = 0;
351 	error = EINVAL;
352 
353 	kt = is_fpu_kern_thread(0);
354 	if (!kt) {
355 		ACQUIRE_CTX(ctxidx, ctx);
356 		fpu_kern_enter(curthread, ctx,
357 		    FPU_KERN_NORMAL | FPU_KERN_KTHR);
358 	}
359 
360 	csp = crypto_get_params(crp->crp_session);
361 	if (crp->crp_auth_key != NULL)
362 		key = crp->crp_auth_key;
363 	else
364 		key = csp->csp_auth_key;
365 	klen = csp->csp_auth_klen;
366 	switch (csp->csp_auth_alg) {
367 	case CRYPTO_BLAKE2B:
368 		if (klen > 0)
369 			rc = blake2b_init_key(&bctx.sb, ses->mlen, key, klen);
370 		else
371 			rc = blake2b_init(&bctx.sb, ses->mlen);
372 		if (rc != 0)
373 			goto out;
374 		error = crypto_apply(crp, crp->crp_payload_start,
375 		    crp->crp_payload_length, blake2b_applicator, &bctx.sb);
376 		if (error != 0)
377 			goto out;
378 		rc = blake2b_final(&bctx.sb, res, ses->mlen);
379 		if (rc != 0) {
380 			error = EINVAL;
381 			goto out;
382 		}
383 		break;
384 	case CRYPTO_BLAKE2S:
385 		if (klen > 0)
386 			rc = blake2s_init_key(&bctx.ss, ses->mlen, key, klen);
387 		else
388 			rc = blake2s_init(&bctx.ss, ses->mlen);
389 		if (rc != 0)
390 			goto out;
391 		error = crypto_apply(crp, crp->crp_payload_start,
392 		    crp->crp_payload_length, blake2s_applicator, &bctx.ss);
393 		if (error != 0)
394 			goto out;
395 		rc = blake2s_final(&bctx.ss, res, ses->mlen);
396 		if (rc != 0) {
397 			error = EINVAL;
398 			goto out;
399 		}
400 		break;
401 	default:
402 		panic("unreachable");
403 	}
404 
405 	if (crp->crp_op & CRYPTO_OP_VERIFY_DIGEST) {
406 		crypto_copydata(crp, crp->crp_digest_start, ses->mlen, res2);
407 		if (timingsafe_bcmp(res, res2, ses->mlen) != 0)
408 			return (EBADMSG);
409 	} else
410 		crypto_copyback(crp, crp->crp_digest_start, ses->mlen, res);
411 
412 out:
413 	if (!kt) {
414 		fpu_kern_leave(curthread, ctx);
415 		RELEASE_CTX(ctxidx, ctx);
416 	}
417 	return (error);
418 }
419