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