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