1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2005-2011 Pawel Jakub Dawidek <pawel@dawidek.net>
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD: stable/12/sys/geom/eli/g_eli.c 363486 2020-07-24 18:19:25Z asomers $");
31 
32 #include <sys/param.h>
33 #include <sys/systm.h>
34 #include <sys/cons.h>
35 #include <sys/kernel.h>
36 #include <sys/linker.h>
37 #include <sys/module.h>
38 #include <sys/lock.h>
39 #include <sys/mutex.h>
40 #include <sys/bio.h>
41 #include <sys/sbuf.h>
42 #include <sys/sysctl.h>
43 #include <sys/malloc.h>
44 #include <sys/eventhandler.h>
45 #include <sys/kthread.h>
46 #include <sys/proc.h>
47 #include <sys/sched.h>
48 #include <sys/smp.h>
49 #include <sys/uio.h>
50 #include <sys/vnode.h>
51 
52 #include <vm/uma.h>
53 
54 #include <geom/geom.h>
55 #include <geom/eli/g_eli.h>
56 #include <geom/eli/pkcs5v2.h>
57 
58 #include <crypto/intake.h>
59 
60 FEATURE(geom_eli, "GEOM crypto module");
61 
62 MALLOC_DEFINE(M_ELI, "eli data", "GEOM_ELI Data");
63 
64 SYSCTL_DECL(_kern_geom);
65 SYSCTL_NODE(_kern_geom, OID_AUTO, eli, CTLFLAG_RW, 0, "GEOM_ELI stuff");
66 static int g_eli_version = G_ELI_VERSION;
67 SYSCTL_INT(_kern_geom_eli, OID_AUTO, version, CTLFLAG_RD, &g_eli_version, 0,
68     "GELI version");
69 int g_eli_debug = 0;
70 SYSCTL_INT(_kern_geom_eli, OID_AUTO, debug, CTLFLAG_RWTUN, &g_eli_debug, 0,
71     "Debug level");
72 static u_int g_eli_tries = 3;
73 SYSCTL_UINT(_kern_geom_eli, OID_AUTO, tries, CTLFLAG_RWTUN, &g_eli_tries, 0,
74     "Number of tries for entering the passphrase");
75 static u_int g_eli_visible_passphrase = GETS_NOECHO;
76 SYSCTL_UINT(_kern_geom_eli, OID_AUTO, visible_passphrase, CTLFLAG_RWTUN,
77     &g_eli_visible_passphrase, 0,
78     "Visibility of passphrase prompt (0 = invisible, 1 = visible, 2 = asterisk)");
79 u_int g_eli_overwrites = G_ELI_OVERWRITES;
80 SYSCTL_UINT(_kern_geom_eli, OID_AUTO, overwrites, CTLFLAG_RWTUN, &g_eli_overwrites,
81     0, "Number of times on-disk keys should be overwritten when destroying them");
82 static u_int g_eli_threads = 0;
83 SYSCTL_UINT(_kern_geom_eli, OID_AUTO, threads, CTLFLAG_RWTUN, &g_eli_threads, 0,
84     "Number of threads doing crypto work");
85 u_int g_eli_batch = 0;
86 SYSCTL_UINT(_kern_geom_eli, OID_AUTO, batch, CTLFLAG_RWTUN, &g_eli_batch, 0,
87     "Use crypto operations batching");
88 
89 /*
90  * Passphrase cached during boot, in order to be more user-friendly if
91  * there are multiple providers using the same passphrase.
92  */
93 static char cached_passphrase[256];
94 static u_int g_eli_boot_passcache = 1;
95 TUNABLE_INT("kern.geom.eli.boot_passcache", &g_eli_boot_passcache);
96 SYSCTL_UINT(_kern_geom_eli, OID_AUTO, boot_passcache, CTLFLAG_RD,
97     &g_eli_boot_passcache, 0,
98     "Passphrases are cached during boot process for possible reuse");
99 static void
fetch_loader_passphrase(void * dummy)100 fetch_loader_passphrase(void * dummy)
101 {
102 	char * env_passphrase;
103 
104 	KASSERT(dynamic_kenv, ("need dynamic kenv"));
105 
106 	if ((env_passphrase = kern_getenv("kern.geom.eli.passphrase")) != NULL) {
107 		/* Extract passphrase from the environment. */
108 		strlcpy(cached_passphrase, env_passphrase,
109 		    sizeof(cached_passphrase));
110 		freeenv(env_passphrase);
111 
112 		/* Wipe the passphrase from the environment. */
113 		kern_unsetenv("kern.geom.eli.passphrase");
114 	}
115 }
116 SYSINIT(geli_fetch_loader_passphrase, SI_SUB_KMEM + 1, SI_ORDER_ANY,
117     fetch_loader_passphrase, NULL);
118 
119 static void
zero_boot_passcache(void)120 zero_boot_passcache(void)
121 {
122 
123         explicit_bzero(cached_passphrase, sizeof(cached_passphrase));
124 }
125 
126 static void
zero_geli_intake_keys(void)127 zero_geli_intake_keys(void)
128 {
129         struct keybuf *keybuf;
130         int i;
131 
132         if ((keybuf = get_keybuf()) != NULL) {
133                 /* Scan the key buffer, clear all GELI keys. */
134                 for (i = 0; i < keybuf->kb_nents; i++) {
135                          if (keybuf->kb_ents[i].ke_type == KEYBUF_TYPE_GELI) {
136                                  explicit_bzero(keybuf->kb_ents[i].ke_data,
137                                      sizeof(keybuf->kb_ents[i].ke_data));
138                                  keybuf->kb_ents[i].ke_type = KEYBUF_TYPE_NONE;
139                          }
140                 }
141         }
142 }
143 
144 static void
zero_intake_passcache(void * dummy)145 zero_intake_passcache(void *dummy)
146 {
147         zero_boot_passcache();
148         zero_geli_intake_keys();
149 }
150 EVENTHANDLER_DEFINE(mountroot, zero_intake_passcache, NULL, 0);
151 
152 static eventhandler_tag g_eli_pre_sync = NULL;
153 
154 static int g_eli_destroy_geom(struct gctl_req *req, struct g_class *mp,
155     struct g_geom *gp);
156 static void g_eli_init(struct g_class *mp);
157 static void g_eli_fini(struct g_class *mp);
158 
159 static g_taste_t g_eli_taste;
160 static g_dumpconf_t g_eli_dumpconf;
161 
162 struct g_class g_eli_class = {
163 	.name = G_ELI_CLASS_NAME,
164 	.version = G_VERSION,
165 	.ctlreq = g_eli_config,
166 	.taste = g_eli_taste,
167 	.destroy_geom = g_eli_destroy_geom,
168 	.init = g_eli_init,
169 	.fini = g_eli_fini
170 };
171 
172 
173 /*
174  * Code paths:
175  * BIO_READ:
176  *	g_eli_start -> g_eli_crypto_read -> g_io_request -> g_eli_read_done -> g_eli_crypto_run -> g_eli_crypto_read_done -> g_io_deliver
177  * BIO_WRITE:
178  *	g_eli_start -> g_eli_crypto_run -> g_eli_crypto_write_done -> g_io_request -> g_eli_write_done -> g_io_deliver
179  */
180 
181 
182 /*
183  * EAGAIN from crypto(9) means, that we were probably balanced to another crypto
184  * accelerator or something like this.
185  * The function updates the SID and rerun the operation.
186  */
187 int
g_eli_crypto_rerun(struct cryptop * crp)188 g_eli_crypto_rerun(struct cryptop *crp)
189 {
190 	struct g_eli_softc *sc;
191 	struct g_eli_worker *wr;
192 	struct bio *bp;
193 	int error;
194 
195 	bp = (struct bio *)crp->crp_opaque;
196 	sc = bp->bio_to->geom->softc;
197 	LIST_FOREACH(wr, &sc->sc_workers, w_next) {
198 		if (wr->w_number == bp->bio_pflags)
199 			break;
200 	}
201 	KASSERT(wr != NULL, ("Invalid worker (%u).", bp->bio_pflags));
202 	G_ELI_DEBUG(1, "Rerunning crypto %s request (sid: %p -> %p).",
203 	    bp->bio_cmd == BIO_READ ? "READ" : "WRITE", wr->w_sid,
204 	    crp->crp_session);
205 	wr->w_sid = crp->crp_session;
206 	crp->crp_etype = 0;
207 	error = crypto_dispatch(crp);
208 	if (error == 0)
209 		return (0);
210 	G_ELI_DEBUG(1, "%s: crypto_dispatch() returned %d.", __func__, error);
211 	crp->crp_etype = error;
212 	return (error);
213 }
214 
215 static void
g_eli_getattr_done(struct bio * bp)216 g_eli_getattr_done(struct bio *bp)
217 {
218 	if (bp->bio_error == 0 &&
219 	    !strcmp(bp->bio_attribute, "GEOM::physpath")) {
220 		strlcat(bp->bio_data, "/eli", bp->bio_length);
221 	}
222 	g_std_done(bp);
223 }
224 
225 /*
226  * The function is called afer reading encrypted data from the provider.
227  *
228  * g_eli_start -> g_eli_crypto_read -> g_io_request -> G_ELI_READ_DONE -> g_eli_crypto_run -> g_eli_crypto_read_done -> g_io_deliver
229  */
230 void
g_eli_read_done(struct bio * bp)231 g_eli_read_done(struct bio *bp)
232 {
233 	struct g_eli_softc *sc;
234 	struct bio *pbp;
235 
236 	G_ELI_LOGREQ(2, bp, "Request done.");
237 	pbp = bp->bio_parent;
238 	if (pbp->bio_error == 0 && bp->bio_error != 0)
239 		pbp->bio_error = bp->bio_error;
240 	g_destroy_bio(bp);
241 	/*
242 	 * Do we have all sectors already?
243 	 */
244 	pbp->bio_inbed++;
245 	if (pbp->bio_inbed < pbp->bio_children)
246 		return;
247 	sc = pbp->bio_to->geom->softc;
248 	if (pbp->bio_error != 0) {
249 		G_ELI_LOGREQ(0, pbp, "%s() failed (error=%d)", __func__,
250 		    pbp->bio_error);
251 		pbp->bio_completed = 0;
252 		if (pbp->bio_driver2 != NULL) {
253 			free(pbp->bio_driver2, M_ELI);
254 			pbp->bio_driver2 = NULL;
255 		}
256 		g_io_deliver(pbp, pbp->bio_error);
257 		if (sc != NULL)
258 			atomic_subtract_int(&sc->sc_inflight, 1);
259 		return;
260 	}
261 	mtx_lock(&sc->sc_queue_mtx);
262 	bioq_insert_tail(&sc->sc_queue, pbp);
263 	mtx_unlock(&sc->sc_queue_mtx);
264 	wakeup(sc);
265 }
266 
267 /*
268  * The function is called after we encrypt and write data.
269  *
270  * g_eli_start -> g_eli_crypto_run -> g_eli_crypto_write_done -> g_io_request -> G_ELI_WRITE_DONE -> g_io_deliver
271  */
272 void
g_eli_write_done(struct bio * bp)273 g_eli_write_done(struct bio *bp)
274 {
275 	struct g_eli_softc *sc;
276 	struct bio *pbp;
277 
278 	G_ELI_LOGREQ(2, bp, "Request done.");
279 	pbp = bp->bio_parent;
280 	if (pbp->bio_error == 0 && bp->bio_error != 0)
281 		pbp->bio_error = bp->bio_error;
282 	g_destroy_bio(bp);
283 	/*
284 	 * Do we have all sectors already?
285 	 */
286 	pbp->bio_inbed++;
287 	if (pbp->bio_inbed < pbp->bio_children)
288 		return;
289 	free(pbp->bio_driver2, M_ELI);
290 	pbp->bio_driver2 = NULL;
291 	if (pbp->bio_error != 0) {
292 		G_ELI_LOGREQ(0, pbp, "%s() failed (error=%d)", __func__,
293 		    pbp->bio_error);
294 		pbp->bio_completed = 0;
295 	} else
296 		pbp->bio_completed = pbp->bio_length;
297 
298 	/*
299 	 * Write is finished, send it up.
300 	 */
301 	sc = pbp->bio_to->geom->softc;
302 	g_io_deliver(pbp, pbp->bio_error);
303 	if (sc != NULL)
304 		atomic_subtract_int(&sc->sc_inflight, 1);
305 }
306 
307 /*
308  * This function should never be called, but GEOM made as it set ->orphan()
309  * method for every geom.
310  */
311 static void
g_eli_orphan_spoil_assert(struct g_consumer * cp)312 g_eli_orphan_spoil_assert(struct g_consumer *cp)
313 {
314 
315 	panic("Function %s() called for %s.", __func__, cp->geom->name);
316 }
317 
318 static void
g_eli_orphan(struct g_consumer * cp)319 g_eli_orphan(struct g_consumer *cp)
320 {
321 	struct g_eli_softc *sc;
322 
323 	g_topology_assert();
324 	sc = cp->geom->softc;
325 	if (sc == NULL)
326 		return;
327 	g_eli_destroy(sc, TRUE);
328 }
329 
330 /*
331  * BIO_READ:
332  *	G_ELI_START -> g_eli_crypto_read -> g_io_request -> g_eli_read_done -> g_eli_crypto_run -> g_eli_crypto_read_done -> g_io_deliver
333  * BIO_WRITE:
334  *	G_ELI_START -> g_eli_crypto_run -> g_eli_crypto_write_done -> g_io_request -> g_eli_write_done -> g_io_deliver
335  */
336 static void
g_eli_start(struct bio * bp)337 g_eli_start(struct bio *bp)
338 {
339 	struct g_eli_softc *sc;
340 	struct g_consumer *cp;
341 	struct bio *cbp;
342 
343 	sc = bp->bio_to->geom->softc;
344 	KASSERT(sc != NULL,
345 	    ("Provider's error should be set (error=%d)(device=%s).",
346 	    bp->bio_to->error, bp->bio_to->name));
347 	G_ELI_LOGREQ(2, bp, "Request received.");
348 
349 	switch (bp->bio_cmd) {
350 	case BIO_READ:
351 	case BIO_WRITE:
352 	case BIO_GETATTR:
353 	case BIO_FLUSH:
354 	case BIO_ZONE:
355 		break;
356 	case BIO_DELETE:
357 		/*
358 		 * If the user hasn't set the NODELETE flag, we just pass
359 		 * it down the stack and let the layers beneath us do (or
360 		 * not) whatever they do with it.  If they have, we
361 		 * reject it.  A possible extension would be an
362 		 * additional flag to take it as a hint to shred the data
363 		 * with [multiple?] overwrites.
364 		 */
365 		if (!(sc->sc_flags & G_ELI_FLAG_NODELETE))
366 			break;
367 	default:
368 		g_io_deliver(bp, EOPNOTSUPP);
369 		return;
370 	}
371 	cbp = g_clone_bio(bp);
372 	if (cbp == NULL) {
373 		g_io_deliver(bp, ENOMEM);
374 		return;
375 	}
376 	bp->bio_driver1 = cbp;
377 	bp->bio_pflags = G_ELI_NEW_BIO;
378 	switch (bp->bio_cmd) {
379 	case BIO_READ:
380 		if (!(sc->sc_flags & G_ELI_FLAG_AUTH)) {
381 			g_eli_crypto_read(sc, bp, 0);
382 			break;
383 		}
384 		/* FALLTHROUGH */
385 	case BIO_WRITE:
386 		mtx_lock(&sc->sc_queue_mtx);
387 		bioq_insert_tail(&sc->sc_queue, bp);
388 		mtx_unlock(&sc->sc_queue_mtx);
389 		wakeup(sc);
390 		break;
391 	case BIO_GETATTR:
392 	case BIO_FLUSH:
393 	case BIO_DELETE:
394 	case BIO_ZONE:
395 		if (bp->bio_cmd == BIO_GETATTR)
396 			cbp->bio_done = g_eli_getattr_done;
397 		else
398 			cbp->bio_done = g_std_done;
399 		cp = LIST_FIRST(&sc->sc_geom->consumer);
400 		cbp->bio_to = cp->provider;
401 		G_ELI_LOGREQ(2, cbp, "Sending request.");
402 		g_io_request(cbp, cp);
403 		break;
404 	}
405 }
406 
407 static int
g_eli_newsession(struct g_eli_worker * wr)408 g_eli_newsession(struct g_eli_worker *wr)
409 {
410 	struct g_eli_softc *sc;
411 	struct cryptoini crie, cria;
412 	int error;
413 
414 	sc = wr->w_softc;
415 
416 	bzero(&crie, sizeof(crie));
417 	crie.cri_alg = sc->sc_ealgo;
418 	crie.cri_klen = sc->sc_ekeylen;
419 	if (sc->sc_ealgo == CRYPTO_AES_XTS)
420 		crie.cri_klen <<= 1;
421 	if ((sc->sc_flags & G_ELI_FLAG_FIRST_KEY) != 0) {
422 		crie.cri_key = g_eli_key_hold(sc, 0,
423 		    LIST_FIRST(&sc->sc_geom->consumer)->provider->sectorsize);
424 	} else {
425 		crie.cri_key = sc->sc_ekey;
426 	}
427 	if (sc->sc_flags & G_ELI_FLAG_AUTH) {
428 		bzero(&cria, sizeof(cria));
429 		cria.cri_alg = sc->sc_aalgo;
430 		cria.cri_klen = sc->sc_akeylen;
431 		cria.cri_key = sc->sc_akey;
432 		crie.cri_next = &cria;
433 	}
434 
435 	switch (sc->sc_crypto) {
436 	case G_ELI_CRYPTO_SW:
437 		error = crypto_newsession(&wr->w_sid, &crie,
438 		    CRYPTOCAP_F_SOFTWARE);
439 		break;
440 	case G_ELI_CRYPTO_HW:
441 		error = crypto_newsession(&wr->w_sid, &crie,
442 		    CRYPTOCAP_F_HARDWARE);
443 		break;
444 	case G_ELI_CRYPTO_UNKNOWN:
445 		error = crypto_newsession(&wr->w_sid, &crie,
446 		    CRYPTOCAP_F_HARDWARE);
447 		if (error == 0) {
448 			mtx_lock(&sc->sc_queue_mtx);
449 			if (sc->sc_crypto == G_ELI_CRYPTO_UNKNOWN)
450 				sc->sc_crypto = G_ELI_CRYPTO_HW;
451 			mtx_unlock(&sc->sc_queue_mtx);
452 		} else {
453 			error = crypto_newsession(&wr->w_sid, &crie,
454 			    CRYPTOCAP_F_SOFTWARE);
455 			mtx_lock(&sc->sc_queue_mtx);
456 			if (sc->sc_crypto == G_ELI_CRYPTO_UNKNOWN)
457 				sc->sc_crypto = G_ELI_CRYPTO_SW;
458 			mtx_unlock(&sc->sc_queue_mtx);
459 		}
460 		break;
461 	default:
462 		panic("%s: invalid condition", __func__);
463 	}
464 
465 	if ((sc->sc_flags & G_ELI_FLAG_FIRST_KEY) != 0)
466 		g_eli_key_drop(sc, crie.cri_key);
467 
468 	return (error);
469 }
470 
471 static void
g_eli_freesession(struct g_eli_worker * wr)472 g_eli_freesession(struct g_eli_worker *wr)
473 {
474 
475 	crypto_freesession(wr->w_sid);
476 }
477 
478 static void
g_eli_cancel(struct g_eli_softc * sc)479 g_eli_cancel(struct g_eli_softc *sc)
480 {
481 	struct bio *bp;
482 
483 	mtx_assert(&sc->sc_queue_mtx, MA_OWNED);
484 
485 	while ((bp = bioq_takefirst(&sc->sc_queue)) != NULL) {
486 		KASSERT(bp->bio_pflags == G_ELI_NEW_BIO,
487 		    ("Not new bio when canceling (bp=%p).", bp));
488 		g_io_deliver(bp, ENXIO);
489 	}
490 }
491 
492 static struct bio *
g_eli_takefirst(struct g_eli_softc * sc)493 g_eli_takefirst(struct g_eli_softc *sc)
494 {
495 	struct bio *bp;
496 
497 	mtx_assert(&sc->sc_queue_mtx, MA_OWNED);
498 
499 	if (!(sc->sc_flags & G_ELI_FLAG_SUSPEND))
500 		return (bioq_takefirst(&sc->sc_queue));
501 	/*
502 	 * Device suspended, so we skip new I/O requests.
503 	 */
504 	TAILQ_FOREACH(bp, &sc->sc_queue.queue, bio_queue) {
505 		if (bp->bio_pflags != G_ELI_NEW_BIO)
506 			break;
507 	}
508 	if (bp != NULL)
509 		bioq_remove(&sc->sc_queue, bp);
510 	return (bp);
511 }
512 
513 /*
514  * This is the main function for kernel worker thread when we don't have
515  * hardware acceleration and we have to do cryptography in software.
516  * Dedicated thread is needed, so we don't slow down g_up/g_down GEOM
517  * threads with crypto work.
518  */
519 static void
g_eli_worker(void * arg)520 g_eli_worker(void *arg)
521 {
522 	struct g_eli_softc *sc;
523 	struct g_eli_worker *wr;
524 	struct bio *bp;
525 	int error;
526 
527 	wr = arg;
528 	sc = wr->w_softc;
529 #ifdef EARLY_AP_STARTUP
530 	MPASS(!sc->sc_cpubind || smp_started);
531 #elif defined(SMP)
532 	/* Before sched_bind() to a CPU, wait for all CPUs to go on-line. */
533 	if (sc->sc_cpubind) {
534 		while (!smp_started)
535 			tsleep(wr, 0, "geli:smp", hz / 4);
536 	}
537 #endif
538 	thread_lock(curthread);
539 	sched_prio(curthread, PUSER);
540 	if (sc->sc_cpubind)
541 		sched_bind(curthread, wr->w_number % mp_ncpus);
542 	thread_unlock(curthread);
543 
544 	G_ELI_DEBUG(1, "Thread %s started.", curthread->td_proc->p_comm);
545 
546 	for (;;) {
547 		mtx_lock(&sc->sc_queue_mtx);
548 again:
549 		bp = g_eli_takefirst(sc);
550 		if (bp == NULL) {
551 			if (sc->sc_flags & G_ELI_FLAG_DESTROY) {
552 				g_eli_cancel(sc);
553 				LIST_REMOVE(wr, w_next);
554 				g_eli_freesession(wr);
555 				free(wr, M_ELI);
556 				G_ELI_DEBUG(1, "Thread %s exiting.",
557 				    curthread->td_proc->p_comm);
558 				wakeup(&sc->sc_workers);
559 				mtx_unlock(&sc->sc_queue_mtx);
560 				kproc_exit(0);
561 			}
562 			while (sc->sc_flags & G_ELI_FLAG_SUSPEND) {
563 				if (sc->sc_inflight > 0) {
564 					G_ELI_DEBUG(0, "inflight=%d",
565 					    sc->sc_inflight);
566 					/*
567 					 * We still have inflight BIOs, so
568 					 * sleep and retry.
569 					 */
570 					msleep(sc, &sc->sc_queue_mtx, PRIBIO,
571 					    "geli:inf", hz / 5);
572 					goto again;
573 				}
574 				/*
575 				 * Suspend requested, mark the worker as
576 				 * suspended and go to sleep.
577 				 */
578 				if (wr->w_active) {
579 					g_eli_freesession(wr);
580 					wr->w_active = FALSE;
581 				}
582 				wakeup(&sc->sc_workers);
583 				msleep(sc, &sc->sc_queue_mtx, PRIBIO,
584 				    "geli:suspend", 0);
585 				if (!wr->w_active &&
586 				    !(sc->sc_flags & G_ELI_FLAG_SUSPEND)) {
587 					error = g_eli_newsession(wr);
588 					KASSERT(error == 0,
589 					    ("g_eli_newsession() failed on resume (error=%d)",
590 					    error));
591 					wr->w_active = TRUE;
592 				}
593 				goto again;
594 			}
595 			msleep(sc, &sc->sc_queue_mtx, PDROP, "geli:w", 0);
596 			continue;
597 		}
598 		if (bp->bio_pflags == G_ELI_NEW_BIO)
599 			atomic_add_int(&sc->sc_inflight, 1);
600 		mtx_unlock(&sc->sc_queue_mtx);
601 		if (bp->bio_pflags == G_ELI_NEW_BIO) {
602 			bp->bio_pflags = 0;
603 			if (sc->sc_flags & G_ELI_FLAG_AUTH) {
604 				if (bp->bio_cmd == BIO_READ)
605 					g_eli_auth_read(sc, bp);
606 				else
607 					g_eli_auth_run(wr, bp);
608 			} else {
609 				if (bp->bio_cmd == BIO_READ)
610 					g_eli_crypto_read(sc, bp, 1);
611 				else
612 					g_eli_crypto_run(wr, bp);
613 			}
614 		} else {
615 			if (sc->sc_flags & G_ELI_FLAG_AUTH)
616 				g_eli_auth_run(wr, bp);
617 			else
618 				g_eli_crypto_run(wr, bp);
619 		}
620 	}
621 }
622 
623 int
g_eli_read_metadata(struct g_class * mp,struct g_provider * pp,struct g_eli_metadata * md)624 g_eli_read_metadata(struct g_class *mp, struct g_provider *pp,
625     struct g_eli_metadata *md)
626 {
627 	struct g_geom *gp;
628 	struct g_consumer *cp;
629 	u_char *buf = NULL;
630 	int error;
631 
632 	g_topology_assert();
633 
634 	gp = g_new_geomf(mp, "eli:taste");
635 	gp->start = g_eli_start;
636 	gp->access = g_std_access;
637 	/*
638 	 * g_eli_read_metadata() is always called from the event thread.
639 	 * Our geom is created and destroyed in the same event, so there
640 	 * could be no orphan nor spoil event in the meantime.
641 	 */
642 	gp->orphan = g_eli_orphan_spoil_assert;
643 	gp->spoiled = g_eli_orphan_spoil_assert;
644 	cp = g_new_consumer(gp);
645 	cp->flags |= G_CF_DIRECT_SEND | G_CF_DIRECT_RECEIVE;
646 	error = g_attach(cp, pp);
647 	if (error != 0)
648 		goto end;
649 	error = g_access(cp, 1, 0, 0);
650 	if (error != 0)
651 		goto end;
652 	g_topology_unlock();
653 	buf = g_read_data(cp, pp->mediasize - pp->sectorsize, pp->sectorsize,
654 	    &error);
655 	g_topology_lock();
656 	if (buf == NULL)
657 		goto end;
658 	error = eli_metadata_decode(buf, md);
659 	if (error != 0)
660 		goto end;
661 	/* Metadata was read and decoded successfully. */
662 end:
663 	if (buf != NULL)
664 		g_free(buf);
665 	if (cp->provider != NULL) {
666 		if (cp->acr == 1)
667 			g_access(cp, -1, 0, 0);
668 		g_detach(cp);
669 	}
670 	g_destroy_consumer(cp);
671 	g_destroy_geom(gp);
672 	return (error);
673 }
674 
675 /*
676  * The function is called when we had last close on provider and user requested
677  * to close it when this situation occur.
678  */
679 static void
g_eli_last_close(void * arg,int flags __unused)680 g_eli_last_close(void *arg, int flags __unused)
681 {
682 	struct g_geom *gp;
683 	char gpname[64];
684 	int error;
685 
686 	g_topology_assert();
687 	gp = arg;
688 	strlcpy(gpname, gp->name, sizeof(gpname));
689 	error = g_eli_destroy(gp->softc, TRUE);
690 	KASSERT(error == 0, ("Cannot detach %s on last close (error=%d).",
691 	    gpname, error));
692 	G_ELI_DEBUG(0, "Detached %s on last close.", gpname);
693 }
694 
695 int
g_eli_access(struct g_provider * pp,int dr,int dw,int de)696 g_eli_access(struct g_provider *pp, int dr, int dw, int de)
697 {
698 	struct g_eli_softc *sc;
699 	struct g_geom *gp;
700 
701 	gp = pp->geom;
702 	sc = gp->softc;
703 
704 	if (dw > 0) {
705 		if (sc->sc_flags & G_ELI_FLAG_RO) {
706 			/* Deny write attempts. */
707 			return (EROFS);
708 		}
709 		/* Someone is opening us for write, we need to remember that. */
710 		sc->sc_flags |= G_ELI_FLAG_WOPEN;
711 		return (0);
712 	}
713 	/* Is this the last close? */
714 	if (pp->acr + dr > 0 || pp->acw + dw > 0 || pp->ace + de > 0)
715 		return (0);
716 
717 	/*
718 	 * Automatically detach on last close if requested.
719 	 */
720 	if ((sc->sc_flags & G_ELI_FLAG_RW_DETACH) ||
721 	    (sc->sc_flags & G_ELI_FLAG_WOPEN)) {
722 		g_post_event(g_eli_last_close, gp, M_WAITOK, NULL);
723 	}
724 	return (0);
725 }
726 
727 static int
g_eli_cpu_is_disabled(int cpu)728 g_eli_cpu_is_disabled(int cpu)
729 {
730 #ifdef SMP
731 	return (CPU_ISSET(cpu, &hlt_cpus_mask));
732 #else
733 	return (0);
734 #endif
735 }
736 
737 struct g_geom *
g_eli_create(struct gctl_req * req,struct g_class * mp,struct g_provider * bpp,const struct g_eli_metadata * md,const u_char * mkey,int nkey)738 g_eli_create(struct gctl_req *req, struct g_class *mp, struct g_provider *bpp,
739     const struct g_eli_metadata *md, const u_char *mkey, int nkey)
740 {
741 	struct g_eli_softc *sc;
742 	struct g_eli_worker *wr;
743 	struct g_geom *gp;
744 	struct g_provider *pp;
745 	struct g_consumer *cp;
746 	u_int i, threads;
747 	int dcw, error;
748 
749 	G_ELI_DEBUG(1, "Creating device %s%s.", bpp->name, G_ELI_SUFFIX);
750 
751 	gp = g_new_geomf(mp, "%s%s", bpp->name, G_ELI_SUFFIX);
752 	sc = malloc(sizeof(*sc), M_ELI, M_WAITOK | M_ZERO);
753 	gp->start = g_eli_start;
754 	/*
755 	 * Spoiling can happen even though we have the provider open
756 	 * exclusively, e.g. through media change events.
757 	 */
758 	gp->spoiled = g_eli_orphan;
759 	gp->orphan = g_eli_orphan;
760 	gp->dumpconf = g_eli_dumpconf;
761 	/*
762 	 * If detach-on-last-close feature is not enabled and we don't operate
763 	 * on read-only provider, we can simply use g_std_access().
764 	 */
765 	if (md->md_flags & (G_ELI_FLAG_WO_DETACH | G_ELI_FLAG_RO))
766 		gp->access = g_eli_access;
767 	else
768 		gp->access = g_std_access;
769 
770 	eli_metadata_softc(sc, md, bpp->sectorsize, bpp->mediasize);
771 	sc->sc_nkey = nkey;
772 
773 	gp->softc = sc;
774 	sc->sc_geom = gp;
775 
776 	bioq_init(&sc->sc_queue);
777 	mtx_init(&sc->sc_queue_mtx, "geli:queue", NULL, MTX_DEF);
778 	mtx_init(&sc->sc_ekeys_lock, "geli:ekeys", NULL, MTX_DEF);
779 
780 	pp = NULL;
781 	cp = g_new_consumer(gp);
782 	cp->flags |= G_CF_DIRECT_SEND | G_CF_DIRECT_RECEIVE;
783 	error = g_attach(cp, bpp);
784 	if (error != 0) {
785 		if (req != NULL) {
786 			gctl_error(req, "Cannot attach to %s (error=%d).",
787 			    bpp->name, error);
788 		} else {
789 			G_ELI_DEBUG(1, "Cannot attach to %s (error=%d).",
790 			    bpp->name, error);
791 		}
792 		goto failed;
793 	}
794 	/*
795 	 * Keep provider open all the time, so we can run critical tasks,
796 	 * like Master Keys deletion, without wondering if we can open
797 	 * provider or not.
798 	 * We don't open provider for writing only when user requested read-only
799 	 * access.
800 	 */
801 	dcw = (sc->sc_flags & G_ELI_FLAG_RO) ? 0 : 1;
802 	error = g_access(cp, 1, dcw, 1);
803 	if (error != 0) {
804 		if (req != NULL) {
805 			gctl_error(req, "Cannot access %s (error=%d).",
806 			    bpp->name, error);
807 		} else {
808 			G_ELI_DEBUG(1, "Cannot access %s (error=%d).",
809 			    bpp->name, error);
810 		}
811 		goto failed;
812 	}
813 
814 	/*
815 	 * Remember the keys in our softc structure.
816 	 */
817 	g_eli_mkey_propagate(sc, mkey);
818 
819 	LIST_INIT(&sc->sc_workers);
820 
821 	threads = g_eli_threads;
822 	if (threads == 0)
823 		threads = mp_ncpus;
824 	sc->sc_cpubind = (mp_ncpus > 1 && threads == mp_ncpus);
825 	for (i = 0; i < threads; i++) {
826 		if (g_eli_cpu_is_disabled(i)) {
827 			G_ELI_DEBUG(1, "%s: CPU %u disabled, skipping.",
828 			    bpp->name, i);
829 			continue;
830 		}
831 		wr = malloc(sizeof(*wr), M_ELI, M_WAITOK | M_ZERO);
832 		wr->w_softc = sc;
833 		wr->w_number = i;
834 		wr->w_active = TRUE;
835 
836 		error = g_eli_newsession(wr);
837 		if (error != 0) {
838 			free(wr, M_ELI);
839 			if (req != NULL) {
840 				gctl_error(req, "Cannot set up crypto session "
841 				    "for %s (error=%d).", bpp->name, error);
842 			} else {
843 				G_ELI_DEBUG(1, "Cannot set up crypto session "
844 				    "for %s (error=%d).", bpp->name, error);
845 			}
846 			goto failed;
847 		}
848 
849 		error = kproc_create(g_eli_worker, wr, &wr->w_proc, 0, 0,
850 		    "g_eli[%u] %s", i, bpp->name);
851 		if (error != 0) {
852 			g_eli_freesession(wr);
853 			free(wr, M_ELI);
854 			if (req != NULL) {
855 				gctl_error(req, "Cannot create kernel thread "
856 				    "for %s (error=%d).", bpp->name, error);
857 			} else {
858 				G_ELI_DEBUG(1, "Cannot create kernel thread "
859 				    "for %s (error=%d).", bpp->name, error);
860 			}
861 			goto failed;
862 		}
863 		LIST_INSERT_HEAD(&sc->sc_workers, wr, w_next);
864 	}
865 
866 	/*
867 	 * Create decrypted provider.
868 	 */
869 	pp = g_new_providerf(gp, "%s%s", bpp->name, G_ELI_SUFFIX);
870 	pp->flags |= G_PF_DIRECT_SEND | G_PF_DIRECT_RECEIVE;
871 	pp->mediasize = sc->sc_mediasize;
872 	pp->sectorsize = sc->sc_sectorsize;
873 
874 	g_error_provider(pp, 0);
875 
876 	G_ELI_DEBUG(0, "Device %s created.", pp->name);
877 	G_ELI_DEBUG(0, "Encryption: %s %u", g_eli_algo2str(sc->sc_ealgo),
878 	    sc->sc_ekeylen);
879 	switch (sc->sc_ealgo) {
880 	case CRYPTO_3DES_CBC:
881 		gone_in(13,
882 		    "support for GEOM_ELI volumes encrypted with 3des");
883 		break;
884 	case CRYPTO_BLF_CBC:
885 		gone_in(13,
886 		    "support for GEOM_ELI volumes encrypted with blowfish");
887 		break;
888 	}
889 	if (sc->sc_flags & G_ELI_FLAG_AUTH) {
890 		G_ELI_DEBUG(0, " Integrity: %s", g_eli_algo2str(sc->sc_aalgo));
891 		switch (sc->sc_aalgo) {
892 		case CRYPTO_MD5_HMAC:
893 			gone_in(13,
894 		    "support for GEOM_ELI volumes authenticated with hmac/md5");
895 			break;
896 		}
897 	}
898 	G_ELI_DEBUG(0, "    Crypto: %s",
899 	    sc->sc_crypto == G_ELI_CRYPTO_SW ? "software" : "hardware");
900 	return (gp);
901 failed:
902 	mtx_lock(&sc->sc_queue_mtx);
903 	sc->sc_flags |= G_ELI_FLAG_DESTROY;
904 	wakeup(sc);
905 	/*
906 	 * Wait for kernel threads self destruction.
907 	 */
908 	while (!LIST_EMPTY(&sc->sc_workers)) {
909 		msleep(&sc->sc_workers, &sc->sc_queue_mtx, PRIBIO,
910 		    "geli:destroy", 0);
911 	}
912 	mtx_destroy(&sc->sc_queue_mtx);
913 	if (cp->provider != NULL) {
914 		if (cp->acr == 1)
915 			g_access(cp, -1, -dcw, -1);
916 		g_detach(cp);
917 	}
918 	g_destroy_consumer(cp);
919 	g_destroy_geom(gp);
920 	g_eli_key_destroy(sc);
921 	bzero(sc, sizeof(*sc));
922 	free(sc, M_ELI);
923 	return (NULL);
924 }
925 
926 int
g_eli_destroy(struct g_eli_softc * sc,boolean_t force)927 g_eli_destroy(struct g_eli_softc *sc, boolean_t force)
928 {
929 	struct g_geom *gp;
930 	struct g_provider *pp;
931 
932 	g_topology_assert();
933 
934 	if (sc == NULL)
935 		return (ENXIO);
936 
937 	gp = sc->sc_geom;
938 	pp = LIST_FIRST(&gp->provider);
939 	if (pp != NULL && (pp->acr != 0 || pp->acw != 0 || pp->ace != 0)) {
940 		if (force) {
941 			G_ELI_DEBUG(1, "Device %s is still open, so it "
942 			    "cannot be definitely removed.", pp->name);
943 			sc->sc_flags |= G_ELI_FLAG_RW_DETACH;
944 			gp->access = g_eli_access;
945 			g_wither_provider(pp, ENXIO);
946 			return (EBUSY);
947 		} else {
948 			G_ELI_DEBUG(1,
949 			    "Device %s is still open (r%dw%de%d).", pp->name,
950 			    pp->acr, pp->acw, pp->ace);
951 			return (EBUSY);
952 		}
953 	}
954 
955 	mtx_lock(&sc->sc_queue_mtx);
956 	sc->sc_flags |= G_ELI_FLAG_DESTROY;
957 	wakeup(sc);
958 	while (!LIST_EMPTY(&sc->sc_workers)) {
959 		msleep(&sc->sc_workers, &sc->sc_queue_mtx, PRIBIO,
960 		    "geli:destroy", 0);
961 	}
962 	mtx_destroy(&sc->sc_queue_mtx);
963 	gp->softc = NULL;
964 	g_eli_key_destroy(sc);
965 	bzero(sc, sizeof(*sc));
966 	free(sc, M_ELI);
967 
968 	G_ELI_DEBUG(0, "Device %s destroyed.", gp->name);
969 	g_wither_geom_close(gp, ENXIO);
970 
971 	return (0);
972 }
973 
974 static int
g_eli_destroy_geom(struct gctl_req * req __unused,struct g_class * mp __unused,struct g_geom * gp)975 g_eli_destroy_geom(struct gctl_req *req __unused,
976     struct g_class *mp __unused, struct g_geom *gp)
977 {
978 	struct g_eli_softc *sc;
979 
980 	sc = gp->softc;
981 	return (g_eli_destroy(sc, FALSE));
982 }
983 
984 static int
g_eli_keyfiles_load(struct hmac_ctx * ctx,const char * provider)985 g_eli_keyfiles_load(struct hmac_ctx *ctx, const char *provider)
986 {
987 	u_char *keyfile, *data;
988 	char *file, name[64];
989 	size_t size;
990 	int i;
991 
992 	for (i = 0; ; i++) {
993 		snprintf(name, sizeof(name), "%s:geli_keyfile%d", provider, i);
994 		keyfile = preload_search_by_type(name);
995 		if (keyfile == NULL && i == 0) {
996 			/*
997 			 * If there is only one keyfile, allow simpler name.
998 			 */
999 			snprintf(name, sizeof(name), "%s:geli_keyfile", provider);
1000 			keyfile = preload_search_by_type(name);
1001 		}
1002 		if (keyfile == NULL)
1003 			return (i);	/* Return number of loaded keyfiles. */
1004 		data = preload_fetch_addr(keyfile);
1005 		if (data == NULL) {
1006 			G_ELI_DEBUG(0, "Cannot find key file data for %s.",
1007 			    name);
1008 			return (0);
1009 		}
1010 		size = preload_fetch_size(keyfile);
1011 		if (size == 0) {
1012 			G_ELI_DEBUG(0, "Cannot find key file size for %s.",
1013 			    name);
1014 			return (0);
1015 		}
1016 		file = preload_search_info(keyfile, MODINFO_NAME);
1017 		if (file == NULL) {
1018 			G_ELI_DEBUG(0, "Cannot find key file name for %s.",
1019 			    name);
1020 			return (0);
1021 		}
1022 		G_ELI_DEBUG(1, "Loaded keyfile %s for %s (type: %s).", file,
1023 		    provider, name);
1024 		g_eli_crypto_hmac_update(ctx, data, size);
1025 	}
1026 }
1027 
1028 static void
g_eli_keyfiles_clear(const char * provider)1029 g_eli_keyfiles_clear(const char *provider)
1030 {
1031 	u_char *keyfile, *data;
1032 	char name[64];
1033 	size_t size;
1034 	int i;
1035 
1036 	for (i = 0; ; i++) {
1037 		snprintf(name, sizeof(name), "%s:geli_keyfile%d", provider, i);
1038 		keyfile = preload_search_by_type(name);
1039 		if (keyfile == NULL)
1040 			return;
1041 		data = preload_fetch_addr(keyfile);
1042 		size = preload_fetch_size(keyfile);
1043 		if (data != NULL && size != 0)
1044 			bzero(data, size);
1045 	}
1046 }
1047 
1048 /*
1049  * Tasting is only made on boot.
1050  * We detect providers which should be attached before root is mounted.
1051  */
1052 static struct g_geom *
g_eli_taste(struct g_class * mp,struct g_provider * pp,int flags __unused)1053 g_eli_taste(struct g_class *mp, struct g_provider *pp, int flags __unused)
1054 {
1055 	struct g_eli_metadata md;
1056 	struct g_geom *gp;
1057 	struct hmac_ctx ctx;
1058 	char passphrase[256];
1059 	u_char key[G_ELI_USERKEYLEN], mkey[G_ELI_DATAIVKEYLEN];
1060 	u_int i, nkey, nkeyfiles, tries, showpass;
1061 	int error;
1062         struct keybuf *keybuf;
1063 
1064 	g_trace(G_T_TOPOLOGY, "%s(%s, %s)", __func__, mp->name, pp->name);
1065 	g_topology_assert();
1066 
1067 	if (root_mounted() || g_eli_tries == 0)
1068 		return (NULL);
1069 
1070 	G_ELI_DEBUG(3, "Tasting %s.", pp->name);
1071 
1072 	error = g_eli_read_metadata(mp, pp, &md);
1073 	if (error != 0)
1074 		return (NULL);
1075 	gp = NULL;
1076 
1077 	if (strcmp(md.md_magic, G_ELI_MAGIC) != 0)
1078 		return (NULL);
1079 	if (md.md_version > G_ELI_VERSION) {
1080 		printf("geom_eli.ko module is too old to handle %s.\n",
1081 		    pp->name);
1082 		return (NULL);
1083 	}
1084 	if (md.md_provsize != pp->mediasize)
1085 		return (NULL);
1086 	/* Should we attach it on boot? */
1087 	if (!(md.md_flags & G_ELI_FLAG_BOOT) &&
1088 	    !(md.md_flags & G_ELI_FLAG_GELIBOOT))
1089 		return (NULL);
1090 	if (md.md_keys == 0x00) {
1091 		G_ELI_DEBUG(0, "No valid keys on %s.", pp->name);
1092 		return (NULL);
1093 	}
1094 	if (md.md_iterations == -1) {
1095 		/* If there is no passphrase, we try only once. */
1096 		tries = 1;
1097 	} else {
1098 		/* Ask for the passphrase no more than g_eli_tries times. */
1099 		tries = g_eli_tries;
1100 	}
1101 
1102         if ((keybuf = get_keybuf()) != NULL) {
1103                 /* Scan the key buffer, try all GELI keys. */
1104                 for (i = 0; i < keybuf->kb_nents; i++) {
1105                          if (keybuf->kb_ents[i].ke_type == KEYBUF_TYPE_GELI) {
1106                                  memcpy(key, keybuf->kb_ents[i].ke_data,
1107                                      sizeof(key));
1108 
1109                                  if (g_eli_mkey_decrypt_any(&md, key,
1110                                      mkey, &nkey) == 0 ) {
1111                                          explicit_bzero(key, sizeof(key));
1112                                          goto have_key;
1113                                  }
1114                          }
1115                 }
1116         }
1117 
1118         for (i = 0; i <= tries; i++) {
1119                 g_eli_crypto_hmac_init(&ctx, NULL, 0);
1120 
1121                 /*
1122                  * Load all key files.
1123                  */
1124                 nkeyfiles = g_eli_keyfiles_load(&ctx, pp->name);
1125 
1126                 if (nkeyfiles == 0 && md.md_iterations == -1) {
1127                         /*
1128                          * No key files and no passphrase, something is
1129                          * definitely wrong here.
1130                          * geli(8) doesn't allow for such situation, so assume
1131                          * that there was really no passphrase and in that case
1132                          * key files are no properly defined in loader.conf.
1133                          */
1134                         G_ELI_DEBUG(0,
1135                             "Found no key files in loader.conf for %s.",
1136                             pp->name);
1137                         return (NULL);
1138                 }
1139 
1140                 /* Ask for the passphrase if defined. */
1141                 if (md.md_iterations >= 0) {
1142                         /* Try first with cached passphrase. */
1143                         if (i == 0) {
1144                                 if (!g_eli_boot_passcache)
1145                                         continue;
1146                                 memcpy(passphrase, cached_passphrase,
1147                                     sizeof(passphrase));
1148                         } else {
1149                                 printf("Enter passphrase for %s: ", pp->name);
1150 				showpass = g_eli_visible_passphrase;
1151 				if ((md.md_flags & G_ELI_FLAG_GELIDISPLAYPASS) != 0)
1152 					showpass = GETS_ECHOPASS;
1153                                 cngets(passphrase, sizeof(passphrase),
1154 				    showpass);
1155                                 memcpy(cached_passphrase, passphrase,
1156                                     sizeof(passphrase));
1157                         }
1158                 }
1159 
1160                 /*
1161                  * Prepare Derived-Key from the user passphrase.
1162                  */
1163                 if (md.md_iterations == 0) {
1164                         g_eli_crypto_hmac_update(&ctx, md.md_salt,
1165                             sizeof(md.md_salt));
1166                         g_eli_crypto_hmac_update(&ctx, passphrase,
1167                             strlen(passphrase));
1168                         explicit_bzero(passphrase, sizeof(passphrase));
1169                 } else if (md.md_iterations > 0) {
1170                         u_char dkey[G_ELI_USERKEYLEN];
1171 
1172                         pkcs5v2_genkey(dkey, sizeof(dkey), md.md_salt,
1173                             sizeof(md.md_salt), passphrase, md.md_iterations);
1174                         bzero(passphrase, sizeof(passphrase));
1175                         g_eli_crypto_hmac_update(&ctx, dkey, sizeof(dkey));
1176                         explicit_bzero(dkey, sizeof(dkey));
1177                 }
1178 
1179                 g_eli_crypto_hmac_final(&ctx, key, 0);
1180 
1181                 /*
1182                  * Decrypt Master-Key.
1183                  */
1184                 error = g_eli_mkey_decrypt_any(&md, key, mkey, &nkey);
1185                 bzero(key, sizeof(key));
1186                 if (error == -1) {
1187                         if (i == tries) {
1188                                 G_ELI_DEBUG(0,
1189                                     "Wrong key for %s. No tries left.",
1190                                     pp->name);
1191                                 g_eli_keyfiles_clear(pp->name);
1192                                 return (NULL);
1193                         }
1194                         if (i > 0) {
1195                                 G_ELI_DEBUG(0,
1196                                     "Wrong key for %s. Tries left: %u.",
1197                                     pp->name, tries - i);
1198                         }
1199                         /* Try again. */
1200                         continue;
1201                 } else if (error > 0) {
1202                         G_ELI_DEBUG(0,
1203                             "Cannot decrypt Master Key for %s (error=%d).",
1204                             pp->name, error);
1205                         g_eli_keyfiles_clear(pp->name);
1206                         return (NULL);
1207                 }
1208                 g_eli_keyfiles_clear(pp->name);
1209                 G_ELI_DEBUG(1, "Using Master Key %u for %s.", nkey, pp->name);
1210                 break;
1211         }
1212 have_key:
1213 
1214 	/*
1215 	 * We have correct key, let's attach provider.
1216 	 */
1217 	gp = g_eli_create(NULL, mp, pp, &md, mkey, nkey);
1218 	bzero(mkey, sizeof(mkey));
1219 	bzero(&md, sizeof(md));
1220 	if (gp == NULL) {
1221 		G_ELI_DEBUG(0, "Cannot create device %s%s.", pp->name,
1222 		    G_ELI_SUFFIX);
1223 		return (NULL);
1224 	}
1225 	return (gp);
1226 }
1227 
1228 static void
g_eli_dumpconf(struct sbuf * sb,const char * indent,struct g_geom * gp,struct g_consumer * cp,struct g_provider * pp)1229 g_eli_dumpconf(struct sbuf *sb, const char *indent, struct g_geom *gp,
1230     struct g_consumer *cp, struct g_provider *pp)
1231 {
1232 	struct g_eli_softc *sc;
1233 
1234 	g_topology_assert();
1235 	sc = gp->softc;
1236 	if (sc == NULL)
1237 		return;
1238 	if (pp != NULL || cp != NULL)
1239 		return;	/* Nothing here. */
1240 
1241 	sbuf_printf(sb, "%s<KeysTotal>%ju</KeysTotal>\n", indent,
1242 	    (uintmax_t)sc->sc_ekeys_total);
1243 	sbuf_printf(sb, "%s<KeysAllocated>%ju</KeysAllocated>\n", indent,
1244 	    (uintmax_t)sc->sc_ekeys_allocated);
1245 	sbuf_printf(sb, "%s<Flags>", indent);
1246 	if (sc->sc_flags == 0)
1247 		sbuf_cat(sb, "NONE");
1248 	else {
1249 		int first = 1;
1250 
1251 #define ADD_FLAG(flag, name)	do {					\
1252 	if (sc->sc_flags & (flag)) {					\
1253 		if (!first)						\
1254 			sbuf_cat(sb, ", ");				\
1255 		else							\
1256 			first = 0;					\
1257 		sbuf_cat(sb, name);					\
1258 	}								\
1259 } while (0)
1260 		ADD_FLAG(G_ELI_FLAG_SUSPEND, "SUSPEND");
1261 		ADD_FLAG(G_ELI_FLAG_SINGLE_KEY, "SINGLE-KEY");
1262 		ADD_FLAG(G_ELI_FLAG_NATIVE_BYTE_ORDER, "NATIVE-BYTE-ORDER");
1263 		ADD_FLAG(G_ELI_FLAG_ONETIME, "ONETIME");
1264 		ADD_FLAG(G_ELI_FLAG_BOOT, "BOOT");
1265 		ADD_FLAG(G_ELI_FLAG_WO_DETACH, "W-DETACH");
1266 		ADD_FLAG(G_ELI_FLAG_RW_DETACH, "RW-DETACH");
1267 		ADD_FLAG(G_ELI_FLAG_AUTH, "AUTH");
1268 		ADD_FLAG(G_ELI_FLAG_WOPEN, "W-OPEN");
1269 		ADD_FLAG(G_ELI_FLAG_DESTROY, "DESTROY");
1270 		ADD_FLAG(G_ELI_FLAG_RO, "READ-ONLY");
1271 		ADD_FLAG(G_ELI_FLAG_NODELETE, "NODELETE");
1272 		ADD_FLAG(G_ELI_FLAG_GELIBOOT, "GELIBOOT");
1273 		ADD_FLAG(G_ELI_FLAG_GELIDISPLAYPASS, "GELIDISPLAYPASS");
1274 #undef  ADD_FLAG
1275 	}
1276 	sbuf_cat(sb, "</Flags>\n");
1277 
1278 	if (!(sc->sc_flags & G_ELI_FLAG_ONETIME)) {
1279 		sbuf_printf(sb, "%s<UsedKey>%u</UsedKey>\n", indent,
1280 		    sc->sc_nkey);
1281 	}
1282 	sbuf_printf(sb, "%s<Version>%u</Version>\n", indent, sc->sc_version);
1283 	sbuf_printf(sb, "%s<Crypto>", indent);
1284 	switch (sc->sc_crypto) {
1285 	case G_ELI_CRYPTO_HW:
1286 		sbuf_cat(sb, "hardware");
1287 		break;
1288 	case G_ELI_CRYPTO_SW:
1289 		sbuf_cat(sb, "software");
1290 		break;
1291 	default:
1292 		sbuf_cat(sb, "UNKNOWN");
1293 		break;
1294 	}
1295 	sbuf_cat(sb, "</Crypto>\n");
1296 	if (sc->sc_flags & G_ELI_FLAG_AUTH) {
1297 		sbuf_printf(sb,
1298 		    "%s<AuthenticationAlgorithm>%s</AuthenticationAlgorithm>\n",
1299 		    indent, g_eli_algo2str(sc->sc_aalgo));
1300 	}
1301 	sbuf_printf(sb, "%s<KeyLength>%u</KeyLength>\n", indent,
1302 	    sc->sc_ekeylen);
1303 	sbuf_printf(sb, "%s<EncryptionAlgorithm>%s</EncryptionAlgorithm>\n",
1304 	    indent, g_eli_algo2str(sc->sc_ealgo));
1305 	sbuf_printf(sb, "%s<State>%s</State>\n", indent,
1306 	    (sc->sc_flags & G_ELI_FLAG_SUSPEND) ? "SUSPENDED" : "ACTIVE");
1307 }
1308 
1309 static void
g_eli_shutdown_pre_sync(void * arg,int howto)1310 g_eli_shutdown_pre_sync(void *arg, int howto)
1311 {
1312 	struct g_class *mp;
1313 	struct g_geom *gp, *gp2;
1314 	struct g_provider *pp;
1315 	struct g_eli_softc *sc;
1316 	int error;
1317 
1318 	mp = arg;
1319 	g_topology_lock();
1320 	LIST_FOREACH_SAFE(gp, &mp->geom, geom, gp2) {
1321 		sc = gp->softc;
1322 		if (sc == NULL)
1323 			continue;
1324 		pp = LIST_FIRST(&gp->provider);
1325 		KASSERT(pp != NULL, ("No provider? gp=%p (%s)", gp, gp->name));
1326 		if (pp->acr != 0 || pp->acw != 0 || pp->ace != 0 ||
1327 		    SCHEDULER_STOPPED())
1328 		{
1329 			sc->sc_flags |= G_ELI_FLAG_RW_DETACH;
1330 			gp->access = g_eli_access;
1331 		} else {
1332 			error = g_eli_destroy(sc, TRUE);
1333 		}
1334 	}
1335 	g_topology_unlock();
1336 }
1337 
1338 static void
g_eli_init(struct g_class * mp)1339 g_eli_init(struct g_class *mp)
1340 {
1341 
1342 	g_eli_pre_sync = EVENTHANDLER_REGISTER(shutdown_pre_sync,
1343 	    g_eli_shutdown_pre_sync, mp, SHUTDOWN_PRI_FIRST);
1344 	if (g_eli_pre_sync == NULL)
1345 		G_ELI_DEBUG(0, "Warning! Cannot register shutdown event.");
1346 }
1347 
1348 static void
g_eli_fini(struct g_class * mp)1349 g_eli_fini(struct g_class *mp)
1350 {
1351 
1352 	if (g_eli_pre_sync != NULL)
1353 		EVENTHANDLER_DEREGISTER(shutdown_pre_sync, g_eli_pre_sync);
1354 }
1355 
1356 DECLARE_GEOM_CLASS(g_eli_class, g_eli);
1357 MODULE_DEPEND(g_eli, crypto, 1, 1, 1);
1358 MODULE_VERSION(geom_eli, 0);
1359