xref: /freebsd/sys/geom/eli/g_eli.c (revision 2b743a9e9ddc6736208dc8ca1ce06ce64ad20a19)
1 /*-
2  * Copyright (c) 2005-2006 Pawel Jakub Dawidek <pjd@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/systm.h>
32 #include <sys/kernel.h>
33 #include <sys/linker.h>
34 #include <sys/module.h>
35 #include <sys/lock.h>
36 #include <sys/mutex.h>
37 #include <sys/bio.h>
38 #include <sys/sysctl.h>
39 #include <sys/malloc.h>
40 #include <sys/kthread.h>
41 #include <sys/proc.h>
42 #include <sys/sched.h>
43 #include <sys/smp.h>
44 #include <sys/uio.h>
45 #include <sys/vnode.h>
46 
47 #include <vm/uma.h>
48 
49 #include <geom/geom.h>
50 #include <geom/eli/g_eli.h>
51 #include <geom/eli/pkcs5v2.h>
52 
53 
54 MALLOC_DEFINE(M_ELI, "eli data", "GEOM_ELI Data");
55 
56 SYSCTL_DECL(_kern_geom);
57 SYSCTL_NODE(_kern_geom, OID_AUTO, eli, CTLFLAG_RW, 0, "GEOM_ELI stuff");
58 u_int g_eli_debug = 0;
59 TUNABLE_INT("kern.geom.eli.debug", &g_eli_debug);
60 SYSCTL_UINT(_kern_geom_eli, OID_AUTO, debug, CTLFLAG_RW, &g_eli_debug, 0,
61     "Debug level");
62 static u_int g_eli_tries = 3;
63 TUNABLE_INT("kern.geom.eli.tries", &g_eli_tries);
64 SYSCTL_UINT(_kern_geom_eli, OID_AUTO, tries, CTLFLAG_RW, &g_eli_tries, 0,
65     "Number of tries for entering the passphrase");
66 static u_int g_eli_visible_passphrase = 0;
67 TUNABLE_INT("kern.geom.eli.visible_passphrase", &g_eli_visible_passphrase);
68 SYSCTL_UINT(_kern_geom_eli, OID_AUTO, visible_passphrase, CTLFLAG_RW,
69     &g_eli_visible_passphrase, 0,
70     "Turn on echo when entering the passphrase (for debug purposes only!!)");
71 u_int g_eli_overwrites = 5;
72 TUNABLE_INT("kern.geom.eli.overwrites", &g_eli_overwrites);
73 SYSCTL_UINT(_kern_geom_eli, OID_AUTO, overwrites, CTLFLAG_RW, &g_eli_overwrites,
74     0, "Number of times on-disk keys should be overwritten when destroying them");
75 static u_int g_eli_threads = 0;
76 TUNABLE_INT("kern.geom.eli.threads", &g_eli_threads);
77 SYSCTL_UINT(_kern_geom_eli, OID_AUTO, threads, CTLFLAG_RW, &g_eli_threads, 0,
78     "Number of threads doing crypto work");
79 u_int g_eli_batch = 0;
80 TUNABLE_INT("kern.geom.eli.batch", &g_eli_batch);
81 SYSCTL_UINT(_kern_geom_eli, OID_AUTO, batch, CTLFLAG_RW, &g_eli_batch, 0,
82     "Use crypto operations batching");
83 
84 static int g_eli_destroy_geom(struct gctl_req *req, struct g_class *mp,
85     struct g_geom *gp);
86 
87 static g_taste_t g_eli_taste;
88 static g_dumpconf_t g_eli_dumpconf;
89 
90 struct g_class g_eli_class = {
91 	.name = G_ELI_CLASS_NAME,
92 	.version = G_VERSION,
93 	.ctlreq = g_eli_config,
94 	.taste = g_eli_taste,
95 	.destroy_geom = g_eli_destroy_geom
96 };
97 
98 
99 /*
100  * Code paths:
101  * BIO_READ:
102  *	g_eli_start -> g_io_request -> g_eli_read_done -> g_eli_crypto_run -> g_eli_crypto_read_done -> g_io_deliver
103  * BIO_WRITE:
104  *	g_eli_start -> g_eli_crypto_run -> g_eli_crypto_write_done -> g_io_request -> g_eli_write_done -> g_io_deliver
105  */
106 
107 
108 /*
109  * EAGAIN from crypto(9) means, that we were probably balanced to another crypto
110  * accelerator or something like this.
111  * The function updates the SID and rerun the operation.
112  */
113 int
114 g_eli_crypto_rerun(struct cryptop *crp)
115 {
116 	struct g_eli_softc *sc;
117 	struct g_eli_worker *wr;
118 	struct bio *bp;
119 	int error;
120 
121 	bp = (struct bio *)crp->crp_opaque;
122 	sc = bp->bio_to->geom->softc;
123 	LIST_FOREACH(wr, &sc->sc_workers, w_next) {
124 		if (wr->w_number == bp->bio_pflags)
125 			break;
126 	}
127 	KASSERT(wr != NULL, ("Invalid worker (%u).", bp->bio_pflags));
128 	G_ELI_DEBUG(1, "Rerunning crypto %s request (sid: %ju -> %ju).",
129 	    bp->bio_cmd == BIO_READ ? "READ" : "WRITE", (uintmax_t)wr->w_sid,
130 	    (uintmax_t)crp->crp_sid);
131 	wr->w_sid = crp->crp_sid;
132 	crp->crp_etype = 0;
133 	error = crypto_dispatch(crp);
134 	if (error == 0)
135 		return (0);
136 	G_ELI_DEBUG(1, "%s: crypto_dispatch() returned %d.", __func__, error);
137 	crp->crp_etype = error;
138 	return (error);
139 }
140 
141 /*
142  * The function is called afer reading encrypted data from the provider.
143  *
144  * g_eli_start -> g_io_request -> G_ELI_READ_DONE -> g_eli_crypto_run -> g_eli_crypto_read_done -> g_io_deliver
145  */
146 void
147 g_eli_read_done(struct bio *bp)
148 {
149 	struct g_eli_softc *sc;
150 	struct bio *pbp;
151 
152 	G_ELI_LOGREQ(2, bp, "Request done.");
153 	pbp = bp->bio_parent;
154 	if (pbp->bio_error == 0)
155 		pbp->bio_error = bp->bio_error;
156 	/*
157 	 * Do we have all sectors already?
158 	 */
159 	pbp->bio_inbed++;
160 	if (pbp->bio_inbed < pbp->bio_children)
161 		return;
162 	g_destroy_bio(bp);
163 	if (pbp->bio_error != 0) {
164 		G_ELI_LOGREQ(0, pbp, "%s() failed", __func__);
165 		pbp->bio_completed = 0;
166 		if (pbp->bio_driver2 != NULL) {
167 			free(pbp->bio_driver2, M_ELI);
168 			pbp->bio_driver2 = NULL;
169 		}
170 		g_io_deliver(pbp, pbp->bio_error);
171 		return;
172 	}
173 	sc = pbp->bio_to->geom->softc;
174 	mtx_lock(&sc->sc_queue_mtx);
175 	bioq_insert_tail(&sc->sc_queue, pbp);
176 	mtx_unlock(&sc->sc_queue_mtx);
177 	wakeup(sc);
178 }
179 
180 /*
181  * The function is called after we encrypt and write data.
182  *
183  * g_eli_start -> g_eli_crypto_run -> g_eli_crypto_write_done -> g_io_request -> G_ELI_WRITE_DONE -> g_io_deliver
184  */
185 void
186 g_eli_write_done(struct bio *bp)
187 {
188 	struct bio *pbp;
189 
190 	G_ELI_LOGREQ(2, bp, "Request done.");
191 	pbp = bp->bio_parent;
192 	if (pbp->bio_error == 0) {
193 		if (bp->bio_error != 0)
194 			pbp->bio_error = bp->bio_error;
195 	}
196 	/*
197 	 * Do we have all sectors already?
198 	 */
199 	pbp->bio_inbed++;
200 	if (pbp->bio_inbed < pbp->bio_children)
201 		return;
202 	free(pbp->bio_driver2, M_ELI);
203 	pbp->bio_driver2 = NULL;
204 	if (pbp->bio_error != 0) {
205 		G_ELI_LOGREQ(0, pbp, "Crypto WRITE request failed (error=%d).",
206 		    pbp->bio_error);
207 		pbp->bio_completed = 0;
208 	}
209 	g_destroy_bio(bp);
210 	/*
211 	 * Write is finished, send it up.
212 	 */
213 	pbp->bio_completed = pbp->bio_length;
214 	g_io_deliver(pbp, pbp->bio_error);
215 }
216 
217 /*
218  * This function should never be called, but GEOM made as it set ->orphan()
219  * method for every geom.
220  */
221 static void
222 g_eli_orphan_spoil_assert(struct g_consumer *cp)
223 {
224 
225 	panic("Function %s() called for %s.", __func__, cp->geom->name);
226 }
227 
228 static void
229 g_eli_orphan(struct g_consumer *cp)
230 {
231 	struct g_eli_softc *sc;
232 
233 	g_topology_assert();
234 	sc = cp->geom->softc;
235 	if (sc == NULL)
236 		return;
237 	g_eli_destroy(sc, 1);
238 }
239 
240 /*
241  * BIO_READ : G_ELI_START -> g_io_request -> g_eli_read_done -> g_eli_crypto_run -> g_eli_crypto_read_done -> g_io_deliver
242  * BIO_WRITE: G_ELI_START -> g_eli_crypto_run -> g_eli_crypto_write_done -> g_io_request -> g_eli_write_done -> g_io_deliver
243  */
244 static void
245 g_eli_start(struct bio *bp)
246 {
247 	struct g_eli_softc *sc;
248 	struct g_consumer *cp;
249 	struct bio *cbp;
250 
251 	sc = bp->bio_to->geom->softc;
252 	KASSERT(sc != NULL,
253 	    ("Provider's error should be set (error=%d)(device=%s).",
254 	    bp->bio_to->error, bp->bio_to->name));
255 	G_ELI_LOGREQ(2, bp, "Request received.");
256 
257 	switch (bp->bio_cmd) {
258 	case BIO_READ:
259 	case BIO_WRITE:
260 	case BIO_GETATTR:
261 	case BIO_FLUSH:
262 		break;
263 	case BIO_DELETE:
264 		/*
265 		 * We could eventually support BIO_DELETE request.
266 		 * It could be done by overwritting requested sector with
267 		 * random data g_eli_overwrites number of times.
268 		 */
269 	default:
270 		g_io_deliver(bp, EOPNOTSUPP);
271 		return;
272 	}
273 	cbp = g_clone_bio(bp);
274 	if (cbp == NULL) {
275 		g_io_deliver(bp, ENOMEM);
276 		return;
277 	}
278 	switch (bp->bio_cmd) {
279 	case BIO_READ:
280 		if (!(sc->sc_flags & G_ELI_FLAG_AUTH)) {
281 			bp->bio_driver2 = NULL;
282 			cbp->bio_done = g_eli_read_done;
283 			cp = LIST_FIRST(&sc->sc_geom->consumer);
284 			cbp->bio_to = cp->provider;
285 			G_ELI_LOGREQ(2, cbp, "Sending request.");
286 			/*
287 			 * Read encrypted data from provider.
288 			 */
289 			g_io_request(cbp, cp);
290 			break;
291 		}
292 		bp->bio_pflags = 255;
293 		/* FALLTHROUGH */
294 	case BIO_WRITE:
295 		bp->bio_driver1 = cbp;
296 		mtx_lock(&sc->sc_queue_mtx);
297 		bioq_insert_tail(&sc->sc_queue, bp);
298 		mtx_unlock(&sc->sc_queue_mtx);
299 		wakeup(sc);
300 		break;
301 	case BIO_GETATTR:
302 	case BIO_FLUSH:
303 		cbp->bio_done = g_std_done;
304 		cp = LIST_FIRST(&sc->sc_geom->consumer);
305 		cbp->bio_to = cp->provider;
306 		G_ELI_LOGREQ(2, cbp, "Sending request.");
307 		g_io_request(cbp, cp);
308 		break;
309 	}
310 }
311 
312 /*
313  * This is the main function for kernel worker thread when we don't have
314  * hardware acceleration and we have to do cryptography in software.
315  * Dedicated thread is needed, so we don't slow down g_up/g_down GEOM
316  * threads with crypto work.
317  */
318 static void
319 g_eli_worker(void *arg)
320 {
321 	struct g_eli_softc *sc;
322 	struct g_eli_worker *wr;
323 	struct bio *bp;
324 
325 	wr = arg;
326 	sc = wr->w_softc;
327 #ifdef SMP
328 	/* Before sched_bind() to a CPU, wait for all CPUs to go on-line. */
329 	if (sc->sc_crypto == G_ELI_CRYPTO_SW && g_eli_threads == 0) {
330 		while (!smp_started)
331 			tsleep(wr, 0, "geli:smp", hz / 4);
332 	}
333 #endif
334 	mtx_lock_spin(&sched_lock);
335 	sched_prio(curthread, PRIBIO);
336 	if (sc->sc_crypto == G_ELI_CRYPTO_SW && g_eli_threads == 0)
337 		sched_bind(curthread, wr->w_number);
338 	mtx_unlock_spin(&sched_lock);
339 
340 	G_ELI_DEBUG(1, "Thread %s started.", curthread->td_proc->p_comm);
341 
342 	for (;;) {
343 		mtx_lock(&sc->sc_queue_mtx);
344 		bp = bioq_takefirst(&sc->sc_queue);
345 		if (bp == NULL) {
346 			if (sc->sc_flags & G_ELI_FLAG_DESTROY) {
347 				LIST_REMOVE(wr, w_next);
348 				crypto_freesession(wr->w_sid);
349 				free(wr, M_ELI);
350 				G_ELI_DEBUG(1, "Thread %s exiting.",
351 				    curthread->td_proc->p_comm);
352 				wakeup(&sc->sc_workers);
353 				mtx_unlock(&sc->sc_queue_mtx);
354 				kthread_exit(0);
355 			}
356 			msleep(sc, &sc->sc_queue_mtx, PRIBIO | PDROP,
357 			    "geli:w", 0);
358 			continue;
359 		}
360 		mtx_unlock(&sc->sc_queue_mtx);
361 		if (bp->bio_cmd == BIO_READ && bp->bio_pflags == 255)
362 			g_eli_auth_read(sc, bp);
363 		else if (sc->sc_flags & G_ELI_FLAG_AUTH)
364 			g_eli_auth_run(wr, bp);
365 		else
366 			g_eli_crypto_run(wr, bp);
367 	}
368 }
369 
370 /*
371  * Here we generate IV. It is unique for every sector.
372  */
373 void
374 g_eli_crypto_ivgen(struct g_eli_softc *sc, off_t offset, u_char *iv,
375     size_t size)
376 {
377 	u_char off[8], hash[SHA256_DIGEST_LENGTH];
378 	SHA256_CTX ctx;
379 
380 	if (!(sc->sc_flags & G_ELI_FLAG_NATIVE_BYTE_ORDER))
381 		le64enc(off, (uint64_t)offset);
382 	/* Copy precalculated SHA256 context for IV-Key. */
383 	bcopy(&sc->sc_ivctx, &ctx, sizeof(ctx));
384 	SHA256_Update(&ctx, (uint8_t *)&offset, sizeof(offset));
385 	SHA256_Final(hash, &ctx);
386 	bcopy(hash, iv, size);
387 }
388 
389 int
390 g_eli_read_metadata(struct g_class *mp, struct g_provider *pp,
391     struct g_eli_metadata *md)
392 {
393 	struct g_geom *gp;
394 	struct g_consumer *cp;
395 	u_char *buf = NULL;
396 	int error;
397 
398 	g_topology_assert();
399 
400 	gp = g_new_geomf(mp, "eli:taste");
401 	gp->start = g_eli_start;
402 	gp->access = g_std_access;
403 	/*
404 	 * g_eli_read_metadata() is always called from the event thread.
405 	 * Our geom is created and destroyed in the same event, so there
406 	 * could be no orphan nor spoil event in the meantime.
407 	 */
408 	gp->orphan = g_eli_orphan_spoil_assert;
409 	gp->spoiled = g_eli_orphan_spoil_assert;
410 	cp = g_new_consumer(gp);
411 	error = g_attach(cp, pp);
412 	if (error != 0)
413 		goto end;
414 	error = g_access(cp, 1, 0, 0);
415 	if (error != 0)
416 		goto end;
417 	g_topology_unlock();
418 	buf = g_read_data(cp, pp->mediasize - pp->sectorsize, pp->sectorsize,
419 	    &error);
420 	g_topology_lock();
421 	if (buf == NULL)
422 		goto end;
423 	eli_metadata_decode(buf, md);
424 end:
425 	if (buf != NULL)
426 		g_free(buf);
427 	if (cp->provider != NULL) {
428 		if (cp->acr == 1)
429 			g_access(cp, -1, 0, 0);
430 		g_detach(cp);
431 	}
432 	g_destroy_consumer(cp);
433 	g_destroy_geom(gp);
434 	return (error);
435 }
436 
437 /*
438  * The function is called when we had last close on provider and user requested
439  * to close it when this situation occur.
440  */
441 static void
442 g_eli_last_close(struct g_eli_softc *sc)
443 {
444 	struct g_geom *gp;
445 	struct g_provider *pp;
446 	char ppname[64];
447 	int error;
448 
449 	g_topology_assert();
450 	gp = sc->sc_geom;
451 	pp = LIST_FIRST(&gp->provider);
452 	strlcpy(ppname, pp->name, sizeof(ppname));
453 	error = g_eli_destroy(sc, 1);
454 	KASSERT(error == 0, ("Cannot detach %s on last close (error=%d).",
455 	    ppname, error));
456 	G_ELI_DEBUG(0, "Detached %s on last close.", ppname);
457 }
458 
459 int
460 g_eli_access(struct g_provider *pp, int dr, int dw, int de)
461 {
462 	struct g_eli_softc *sc;
463 	struct g_geom *gp;
464 
465 	gp = pp->geom;
466 	sc = gp->softc;
467 
468 	if (dw > 0) {
469 		if (sc->sc_flags & G_ELI_FLAG_RO) {
470 			/* Deny write attempts. */
471 			return (EROFS);
472 		}
473 		/* Someone is opening us for write, we need to remember that. */
474 		sc->sc_flags |= G_ELI_FLAG_WOPEN;
475 		return (0);
476 	}
477 	/* Is this the last close? */
478 	if (pp->acr + dr > 0 || pp->acw + dw > 0 || pp->ace + de > 0)
479 		return (0);
480 
481 	/*
482 	 * Automatically detach on last close if requested.
483 	 */
484 	if ((sc->sc_flags & G_ELI_FLAG_RW_DETACH) ||
485 	    (sc->sc_flags & G_ELI_FLAG_WOPEN)) {
486 		g_eli_last_close(sc);
487 	}
488 	return (0);
489 }
490 
491 static int
492 g_eli_cpu_is_disabled(int cpu)
493 {
494 #ifdef SMP
495 	return ((hlt_cpus_mask & (1 << cpu)) != 0);
496 #else
497 	return (0);
498 #endif
499 }
500 
501 struct g_geom *
502 g_eli_create(struct gctl_req *req, struct g_class *mp, struct g_provider *bpp,
503     const struct g_eli_metadata *md, const u_char *mkey, int nkey)
504 {
505 	struct g_eli_softc *sc;
506 	struct g_eli_worker *wr;
507 	struct g_geom *gp;
508 	struct g_provider *pp;
509 	struct g_consumer *cp;
510 	struct cryptoini crie, cria;
511 	u_int i, threads;
512 	int error;
513 
514 	G_ELI_DEBUG(1, "Creating device %s%s.", bpp->name, G_ELI_SUFFIX);
515 
516 	gp = g_new_geomf(mp, "%s%s", bpp->name, G_ELI_SUFFIX);
517 	gp->softc = NULL;	/* for a moment */
518 
519 	sc = malloc(sizeof(*sc), M_ELI, M_WAITOK | M_ZERO);
520 	gp->start = g_eli_start;
521 	/*
522 	 * Spoiling cannot happen actually, because we keep provider open for
523 	 * writing all the time or provider is read-only.
524 	 */
525 	gp->spoiled = g_eli_orphan_spoil_assert;
526 	gp->orphan = g_eli_orphan;
527 	gp->dumpconf = g_eli_dumpconf;
528 	/*
529 	 * If detach-on-last-close feature is not enabled and we don't operate
530 	 * on read-only provider, we can simply use g_std_access().
531 	 */
532 	if (md->md_flags & (G_ELI_FLAG_WO_DETACH | G_ELI_FLAG_RO))
533 		gp->access = g_eli_access;
534 	else
535 		gp->access = g_std_access;
536 
537 	sc->sc_crypto = G_ELI_CRYPTO_SW;
538 	sc->sc_flags = md->md_flags;
539 	/* Backward compatibility. */
540 	if (md->md_version < 2)
541 		sc->sc_flags |= G_ELI_FLAG_NATIVE_BYTE_ORDER;
542 	sc->sc_ealgo = md->md_ealgo;
543 	sc->sc_nkey = nkey;
544 	/*
545 	 * Remember the keys in our softc structure.
546 	 */
547 	g_eli_mkey_propagate(sc, mkey);
548 	sc->sc_ekeylen = md->md_keylen;
549 
550 	if (sc->sc_flags & G_ELI_FLAG_AUTH) {
551 		sc->sc_akeylen = sizeof(sc->sc_akey) * 8;
552 		sc->sc_aalgo = md->md_aalgo;
553 		sc->sc_alen = g_eli_hashlen(sc->sc_aalgo);
554 
555 		sc->sc_data_per_sector = bpp->sectorsize - sc->sc_alen;
556 		/*
557 		 * Some hash functions (like SHA1 and RIPEMD160) generates hash
558 		 * which length is not multiple of 128 bits, but we want data
559 		 * length to be multiple of 128, so we can encrypt without
560 		 * padding. The line below rounds down data length to multiple
561 		 * of 128 bits.
562 		 */
563 		sc->sc_data_per_sector -= sc->sc_data_per_sector % 16;
564 
565 		sc->sc_bytes_per_sector =
566 		    (md->md_sectorsize - 1) / sc->sc_data_per_sector + 1;
567 		sc->sc_bytes_per_sector *= bpp->sectorsize;
568 		/*
569 		 * Precalculate SHA256 for HMAC key generation.
570 		 * This is expensive operation and we can do it only once now or
571 		 * for every access to sector, so now will be much better.
572 		 */
573 		SHA256_Init(&sc->sc_akeyctx);
574 		SHA256_Update(&sc->sc_akeyctx, sc->sc_akey,
575 		    sizeof(sc->sc_akey));
576 	}
577 
578 	/*
579 	 * Precalculate SHA256 for IV generation.
580 	 * This is expensive operation and we can do it only once now or for
581 	 * every access to sector, so now will be much better.
582 	 */
583 	SHA256_Init(&sc->sc_ivctx);
584 	SHA256_Update(&sc->sc_ivctx, sc->sc_ivkey, sizeof(sc->sc_ivkey));
585 
586 	gp->softc = sc;
587 	sc->sc_geom = gp;
588 
589 	bioq_init(&sc->sc_queue);
590 	mtx_init(&sc->sc_queue_mtx, "geli:queue", NULL, MTX_DEF);
591 
592 	pp = NULL;
593 	cp = g_new_consumer(gp);
594 	error = g_attach(cp, bpp);
595 	if (error != 0) {
596 		if (req != NULL) {
597 			gctl_error(req, "Cannot attach to %s (error=%d).",
598 			    bpp->name, error);
599 		} else {
600 			G_ELI_DEBUG(1, "Cannot attach to %s (error=%d).",
601 			    bpp->name, error);
602 		}
603 		goto failed;
604 	}
605 	/*
606 	 * Keep provider open all the time, so we can run critical tasks,
607 	 * like Master Keys deletion, without wondering if we can open
608 	 * provider or not.
609 	 * We don't open provider for writing only when user requested read-only
610 	 * access.
611 	 */
612 	if (sc->sc_flags & G_ELI_FLAG_RO)
613 		error = g_access(cp, 1, 0, 1);
614 	else
615 		error = g_access(cp, 1, 1, 1);
616 	if (error != 0) {
617 		if (req != NULL) {
618 			gctl_error(req, "Cannot access %s (error=%d).",
619 			    bpp->name, error);
620 		} else {
621 			G_ELI_DEBUG(1, "Cannot access %s (error=%d).",
622 			    bpp->name, error);
623 		}
624 		goto failed;
625 	}
626 
627 	LIST_INIT(&sc->sc_workers);
628 
629 	bzero(&crie, sizeof(crie));
630 	crie.cri_alg = sc->sc_ealgo;
631 	crie.cri_klen = sc->sc_ekeylen;
632 	crie.cri_key = sc->sc_ekey;
633 	if (sc->sc_flags & G_ELI_FLAG_AUTH) {
634 		bzero(&cria, sizeof(cria));
635 		cria.cri_alg = sc->sc_aalgo;
636 		cria.cri_klen = sc->sc_akeylen;
637 		cria.cri_key = sc->sc_akey;
638 		crie.cri_next = &cria;
639 	}
640 
641 	threads = g_eli_threads;
642 	if (threads == 0)
643 		threads = mp_ncpus;
644 	else if (threads > mp_ncpus) {
645 		/* There is really no need for too many worker threads. */
646 		threads = mp_ncpus;
647 		G_ELI_DEBUG(0, "Reducing number of threads to %u.", threads);
648 	}
649 	for (i = 0; i < threads; i++) {
650 		if (g_eli_cpu_is_disabled(i)) {
651 			G_ELI_DEBUG(1, "%s: CPU %u disabled, skipping.",
652 			    bpp->name, i);
653 			continue;
654 		}
655 		wr = malloc(sizeof(*wr), M_ELI, M_WAITOK | M_ZERO);
656 		wr->w_softc = sc;
657 		wr->w_number = i;
658 
659 		/*
660 		 * If this is the first pass, try to get hardware support.
661 		 * Use software cryptography, if we cannot get it.
662 		 */
663 		if (LIST_EMPTY(&sc->sc_workers)) {
664 			error = crypto_newsession(&wr->w_sid, &crie, 1);
665 			if (error == 0)
666 				sc->sc_crypto = G_ELI_CRYPTO_HW;
667 		}
668 		if (sc->sc_crypto == G_ELI_CRYPTO_SW)
669 			error = crypto_newsession(&wr->w_sid, &crie, 0);
670 		if (error != 0) {
671 			free(wr, M_ELI);
672 			if (req != NULL) {
673 				gctl_error(req, "Cannot set up crypto session "
674 				    "for %s (error=%d).", bpp->name, error);
675 			} else {
676 				G_ELI_DEBUG(1, "Cannot set up crypto session "
677 				    "for %s (error=%d).", bpp->name, error);
678 			}
679 			goto failed;
680 		}
681 
682 		error = kthread_create(g_eli_worker, wr, &wr->w_proc, 0, 0,
683 		    "g_eli[%u] %s", i, bpp->name);
684 		if (error != 0) {
685 			crypto_freesession(wr->w_sid);
686 			free(wr, M_ELI);
687 			if (req != NULL) {
688 				gctl_error(req, "Cannot create kernel thread "
689 				    "for %s (error=%d).", bpp->name, error);
690 			} else {
691 				G_ELI_DEBUG(1, "Cannot create kernel thread "
692 				    "for %s (error=%d).", bpp->name, error);
693 			}
694 			goto failed;
695 		}
696 		LIST_INSERT_HEAD(&sc->sc_workers, wr, w_next);
697 		/* If we have hardware support, one thread is enough. */
698 		if (sc->sc_crypto == G_ELI_CRYPTO_HW)
699 			break;
700 	}
701 
702 	/*
703 	 * Create decrypted provider.
704 	 */
705 	pp = g_new_providerf(gp, "%s%s", bpp->name, G_ELI_SUFFIX);
706 	pp->sectorsize = md->md_sectorsize;
707 	pp->mediasize = bpp->mediasize;
708 	if (!(sc->sc_flags & G_ELI_FLAG_ONETIME))
709 		pp->mediasize -= bpp->sectorsize;
710 	if (!(sc->sc_flags & G_ELI_FLAG_AUTH))
711 		pp->mediasize -= (pp->mediasize % pp->sectorsize);
712 	else {
713 		pp->mediasize /= sc->sc_bytes_per_sector;
714 		pp->mediasize *= pp->sectorsize;
715 	}
716 
717 	g_error_provider(pp, 0);
718 
719 	G_ELI_DEBUG(0, "Device %s created.", pp->name);
720 	G_ELI_DEBUG(0, "Encryption: %s %u", g_eli_algo2str(sc->sc_ealgo),
721 	    sc->sc_ekeylen);
722 	if (sc->sc_flags & G_ELI_FLAG_AUTH)
723 		G_ELI_DEBUG(0, " Integrity: %s", g_eli_algo2str(sc->sc_aalgo));
724 	G_ELI_DEBUG(0, "    Crypto: %s",
725 	    sc->sc_crypto == G_ELI_CRYPTO_SW ? "software" : "hardware");
726 	return (gp);
727 failed:
728 	mtx_lock(&sc->sc_queue_mtx);
729 	sc->sc_flags |= G_ELI_FLAG_DESTROY;
730 	wakeup(sc);
731 	/*
732 	 * Wait for kernel threads self destruction.
733 	 */
734 	while (!LIST_EMPTY(&sc->sc_workers)) {
735 		msleep(&sc->sc_workers, &sc->sc_queue_mtx, PRIBIO,
736 		    "geli:destroy", 0);
737 	}
738 	mtx_destroy(&sc->sc_queue_mtx);
739 	if (cp->provider != NULL) {
740 		if (cp->acr == 1)
741 			g_access(cp, -1, -1, -1);
742 		g_detach(cp);
743 	}
744 	g_destroy_consumer(cp);
745 	g_destroy_geom(gp);
746 	bzero(sc, sizeof(*sc));
747 	free(sc, M_ELI);
748 	return (NULL);
749 }
750 
751 int
752 g_eli_destroy(struct g_eli_softc *sc, boolean_t force)
753 {
754 	struct g_geom *gp;
755 	struct g_provider *pp;
756 
757 	g_topology_assert();
758 
759 	if (sc == NULL)
760 		return (ENXIO);
761 
762 	gp = sc->sc_geom;
763 	pp = LIST_FIRST(&gp->provider);
764 	if (pp != NULL && (pp->acr != 0 || pp->acw != 0 || pp->ace != 0)) {
765 		if (force) {
766 			G_ELI_DEBUG(1, "Device %s is still open, so it "
767 			    "cannot be definitely removed.", pp->name);
768 		} else {
769 			G_ELI_DEBUG(1,
770 			    "Device %s is still open (r%dw%de%d).", pp->name,
771 			    pp->acr, pp->acw, pp->ace);
772 			return (EBUSY);
773 		}
774 	}
775 
776 	mtx_lock(&sc->sc_queue_mtx);
777 	sc->sc_flags |= G_ELI_FLAG_DESTROY;
778 	wakeup(sc);
779 	while (!LIST_EMPTY(&sc->sc_workers)) {
780 		msleep(&sc->sc_workers, &sc->sc_queue_mtx, PRIBIO,
781 		    "geli:destroy", 0);
782 	}
783 	mtx_destroy(&sc->sc_queue_mtx);
784 	gp->softc = NULL;
785 	bzero(sc, sizeof(*sc));
786 	free(sc, M_ELI);
787 
788 	if (pp == NULL || (pp->acr == 0 && pp->acw == 0 && pp->ace == 0))
789 		G_ELI_DEBUG(0, "Device %s destroyed.", gp->name);
790 	g_wither_geom_close(gp, ENXIO);
791 
792 	return (0);
793 }
794 
795 static int
796 g_eli_destroy_geom(struct gctl_req *req __unused,
797     struct g_class *mp __unused, struct g_geom *gp)
798 {
799 	struct g_eli_softc *sc;
800 
801 	sc = gp->softc;
802 	return (g_eli_destroy(sc, 0));
803 }
804 
805 static int
806 g_eli_keyfiles_load(struct hmac_ctx *ctx, const char *provider)
807 {
808 	u_char *keyfile, *data, *size;
809 	char *file, name[64];
810 	int i;
811 
812 	for (i = 0; ; i++) {
813 		snprintf(name, sizeof(name), "%s:geli_keyfile%d", provider, i);
814 		keyfile = preload_search_by_type(name);
815 		if (keyfile == NULL)
816 			return (i);	/* Return number of loaded keyfiles. */
817 		data = preload_search_info(keyfile, MODINFO_ADDR);
818 		if (data == NULL) {
819 			G_ELI_DEBUG(0, "Cannot find key file data for %s.",
820 			    name);
821 			return (0);
822 		}
823 		data = *(void **)data;
824 		size = preload_search_info(keyfile, MODINFO_SIZE);
825 		if (size == NULL) {
826 			G_ELI_DEBUG(0, "Cannot find key file size for %s.",
827 			    name);
828 			return (0);
829 		}
830 		file = preload_search_info(keyfile, MODINFO_NAME);
831 		if (file == NULL) {
832 			G_ELI_DEBUG(0, "Cannot find key file name for %s.",
833 			    name);
834 			return (0);
835 		}
836 		G_ELI_DEBUG(1, "Loaded keyfile %s for %s (type: %s).", file,
837 		    provider, name);
838 		g_eli_crypto_hmac_update(ctx, data, *(size_t *)size);
839 	}
840 }
841 
842 static void
843 g_eli_keyfiles_clear(const char *provider)
844 {
845 	u_char *keyfile, *data, *size;
846 	char name[64];
847 	int i;
848 
849 	for (i = 0; ; i++) {
850 		snprintf(name, sizeof(name), "%s:geli_keyfile%d", provider, i);
851 		keyfile = preload_search_by_type(name);
852 		if (keyfile == NULL)
853 			return;
854 		data = preload_search_info(keyfile, MODINFO_ADDR);
855 		size = preload_search_info(keyfile, MODINFO_SIZE);
856 		if (data == NULL || size == NULL)
857 			continue;
858 		data = *(void **)data;
859 		bzero(data, *(size_t *)size);
860 	}
861 }
862 
863 /*
864  * Tasting is only made on boot.
865  * We detect providers which should be attached before root is mounted.
866  */
867 static struct g_geom *
868 g_eli_taste(struct g_class *mp, struct g_provider *pp, int flags __unused)
869 {
870 	struct g_eli_metadata md;
871 	struct g_geom *gp;
872 	struct hmac_ctx ctx;
873 	char passphrase[256];
874 	u_char key[G_ELI_USERKEYLEN], mkey[G_ELI_DATAIVKEYLEN];
875 	u_int i, nkey, nkeyfiles, tries;
876 	int error;
877 
878 	g_trace(G_T_TOPOLOGY, "%s(%s, %s)", __func__, mp->name, pp->name);
879 	g_topology_assert();
880 
881 	if (rootvnode != NULL || g_eli_tries == 0)
882 		return (NULL);
883 
884 	G_ELI_DEBUG(3, "Tasting %s.", pp->name);
885 
886 	error = g_eli_read_metadata(mp, pp, &md);
887 	if (error != 0)
888 		return (NULL);
889 	gp = NULL;
890 
891 	if (strcmp(md.md_magic, G_ELI_MAGIC) != 0)
892 		return (NULL);
893 	if (md.md_version > G_ELI_VERSION) {
894 		printf("geom_eli.ko module is too old to handle %s.\n",
895 		    pp->name);
896 		return (NULL);
897 	}
898 	if (md.md_provsize != pp->mediasize)
899 		return (NULL);
900 	/* Should we attach it on boot? */
901 	if (!(md.md_flags & G_ELI_FLAG_BOOT))
902 		return (NULL);
903 	if (md.md_keys == 0x00) {
904 		G_ELI_DEBUG(0, "No valid keys on %s.", pp->name);
905 		return (NULL);
906 	}
907 	if (md.md_iterations == -1) {
908 		/* If there is no passphrase, we try only once. */
909 		tries = 1;
910 	} else {
911 		/* Ask for the passphrase no more than g_eli_tries times. */
912 		tries = g_eli_tries;
913 	}
914 
915 	for (i = 0; i < tries; i++) {
916 		g_eli_crypto_hmac_init(&ctx, NULL, 0);
917 
918 		/*
919 		 * Load all key files.
920 		 */
921 		nkeyfiles = g_eli_keyfiles_load(&ctx, pp->name);
922 
923 		if (nkeyfiles == 0 && md.md_iterations == -1) {
924 			/*
925 			 * No key files and no passphrase, something is
926 			 * definitely wrong here.
927 			 * geli(8) doesn't allow for such situation, so assume
928 			 * that there was really no passphrase and in that case
929 			 * key files are no properly defined in loader.conf.
930 			 */
931 			G_ELI_DEBUG(0,
932 			    "Found no key files in loader.conf for %s.",
933 			    pp->name);
934 			return (NULL);
935 		}
936 
937 		/* Ask for the passphrase if defined. */
938 		if (md.md_iterations >= 0) {
939 			printf("Enter passphrase for %s: ", pp->name);
940 			gets(passphrase, sizeof(passphrase),
941 			    g_eli_visible_passphrase);
942 		}
943 
944 		/*
945 		 * Prepare Derived-Key from the user passphrase.
946 		 */
947 		if (md.md_iterations == 0) {
948 			g_eli_crypto_hmac_update(&ctx, md.md_salt,
949 			    sizeof(md.md_salt));
950 			g_eli_crypto_hmac_update(&ctx, passphrase,
951 			    strlen(passphrase));
952 		} else if (md.md_iterations > 0) {
953 			u_char dkey[G_ELI_USERKEYLEN];
954 
955 			pkcs5v2_genkey(dkey, sizeof(dkey), md.md_salt,
956 			    sizeof(md.md_salt), passphrase, md.md_iterations);
957 			g_eli_crypto_hmac_update(&ctx, dkey, sizeof(dkey));
958 			bzero(dkey, sizeof(dkey));
959 		}
960 
961 		g_eli_crypto_hmac_final(&ctx, key, 0);
962 
963 		/*
964 		 * Decrypt Master-Key.
965 		 */
966 		error = g_eli_mkey_decrypt(&md, key, mkey, &nkey);
967 		bzero(key, sizeof(key));
968 		if (error == -1) {
969 			if (i == tries - 1) {
970 				G_ELI_DEBUG(0,
971 				    "Wrong key for %s. No tries left.",
972 				    pp->name);
973 				g_eli_keyfiles_clear(pp->name);
974 				return (NULL);
975 			}
976 			G_ELI_DEBUG(0, "Wrong key for %s. Tries left: %u.",
977 			    pp->name, tries - i - 1);
978 			/* Try again. */
979 			continue;
980 		} else if (error > 0) {
981 			G_ELI_DEBUG(0, "Cannot decrypt Master Key for %s (error=%d).",
982 			    pp->name, error);
983 			g_eli_keyfiles_clear(pp->name);
984 			return (NULL);
985 		}
986 		G_ELI_DEBUG(1, "Using Master Key %u for %s.", nkey, pp->name);
987 		break;
988 	}
989 
990 	/*
991 	 * We have correct key, let's attach provider.
992 	 */
993 	gp = g_eli_create(NULL, mp, pp, &md, mkey, nkey);
994 	bzero(mkey, sizeof(mkey));
995 	bzero(&md, sizeof(md));
996 	if (gp == NULL) {
997 		G_ELI_DEBUG(0, "Cannot create device %s%s.", pp->name,
998 		    G_ELI_SUFFIX);
999 		return (NULL);
1000 	}
1001 	return (gp);
1002 }
1003 
1004 static void
1005 g_eli_dumpconf(struct sbuf *sb, const char *indent, struct g_geom *gp,
1006     struct g_consumer *cp, struct g_provider *pp)
1007 {
1008 	struct g_eli_softc *sc;
1009 
1010 	g_topology_assert();
1011 	sc = gp->softc;
1012 	if (sc == NULL)
1013 		return;
1014 	if (pp != NULL || cp != NULL)
1015 		return;	/* Nothing here. */
1016 	sbuf_printf(sb, "%s<Flags>", indent);
1017 	if (sc->sc_flags == 0)
1018 		sbuf_printf(sb, "NONE");
1019 	else {
1020 		int first = 1;
1021 
1022 #define ADD_FLAG(flag, name)	do {					\
1023 	if (sc->sc_flags & (flag)) {					\
1024 		if (!first)						\
1025 			sbuf_printf(sb, ", ");				\
1026 		else							\
1027 			first = 0;					\
1028 		sbuf_printf(sb, name);					\
1029 	}								\
1030 } while (0)
1031 		ADD_FLAG(G_ELI_FLAG_NATIVE_BYTE_ORDER, "NATIVE-BYTE-ORDER");
1032 		ADD_FLAG(G_ELI_FLAG_ONETIME, "ONETIME");
1033 		ADD_FLAG(G_ELI_FLAG_BOOT, "BOOT");
1034 		ADD_FLAG(G_ELI_FLAG_WO_DETACH, "W-DETACH");
1035 		ADD_FLAG(G_ELI_FLAG_RW_DETACH, "RW-DETACH");
1036 		ADD_FLAG(G_ELI_FLAG_AUTH, "AUTH");
1037 		ADD_FLAG(G_ELI_FLAG_WOPEN, "W-OPEN");
1038 		ADD_FLAG(G_ELI_FLAG_DESTROY, "DESTROY");
1039 		ADD_FLAG(G_ELI_FLAG_RO, "READ-ONLY");
1040 #undef  ADD_FLAG
1041 	}
1042 	sbuf_printf(sb, "</Flags>\n");
1043 
1044 	if (!(sc->sc_flags & G_ELI_FLAG_ONETIME)) {
1045 		sbuf_printf(sb, "%s<UsedKey>%u</UsedKey>\n", indent,
1046 		    sc->sc_nkey);
1047 	}
1048 	sbuf_printf(sb, "%s<Crypto>", indent);
1049 	switch (sc->sc_crypto) {
1050 	case G_ELI_CRYPTO_HW:
1051 		sbuf_printf(sb, "hardware");
1052 		break;
1053 	case G_ELI_CRYPTO_SW:
1054 		sbuf_printf(sb, "software");
1055 		break;
1056 	default:
1057 		sbuf_printf(sb, "UNKNOWN");
1058 		break;
1059 	}
1060 	sbuf_printf(sb, "</Crypto>\n");
1061 	if (sc->sc_flags & G_ELI_FLAG_AUTH) {
1062 		sbuf_printf(sb,
1063 		    "%s<AuthenticationAlgorithm>%s</AuthenticationAlgorithm>\n",
1064 		    indent, g_eli_algo2str(sc->sc_aalgo));
1065 	}
1066 	sbuf_printf(sb, "%s<KeyLength>%u</KeyLength>\n", indent,
1067 	    sc->sc_ekeylen);
1068 	sbuf_printf(sb, "%s<EncryptionAlgorithm>%s</EncryptionAlgorithm>\n", indent,
1069 	    g_eli_algo2str(sc->sc_ealgo));
1070 }
1071 
1072 DECLARE_GEOM_CLASS(g_eli_class, g_eli);
1073 MODULE_DEPEND(g_eli, crypto, 1, 1, 1);
1074