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