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