2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * Copyright (c) 2005-2019 Pawel Jakub Dawidek <pawel@dawidek.net>
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
17 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
20 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
32 #include <sys/param.h>
33 #include <sys/systm.h>
35 #include <sys/kernel.h>
36 #include <sys/linker.h>
37 #include <sys/module.h>
39 #include <sys/mutex.h>
42 #include <sys/sysctl.h>
43 #include <sys/malloc.h>
44 #include <sys/eventhandler.h>
45 #include <sys/kthread.h>
47 #include <sys/sched.h>
50 #include <sys/vnode.h>
54 #include <geom/geom.h>
55 #include <geom/geom_dbg.h>
56 #include <geom/eli/g_eli.h>
57 #include <geom/eli/pkcs5v2.h>
59 #include <crypto/intake.h>
61 FEATURE(geom_eli, "GEOM crypto module");
63 MALLOC_DEFINE(M_ELI, "eli data", "GEOM_ELI Data");
65 SYSCTL_DECL(_kern_geom);
66 SYSCTL_NODE(_kern_geom, OID_AUTO, eli, CTLFLAG_RW, 0, "GEOM_ELI stuff");
67 static int g_eli_version = G_ELI_VERSION;
68 SYSCTL_INT(_kern_geom_eli, OID_AUTO, version, CTLFLAG_RD, &g_eli_version, 0,
71 SYSCTL_INT(_kern_geom_eli, OID_AUTO, debug, CTLFLAG_RWTUN, &g_eli_debug, 0,
73 static u_int g_eli_tries = 3;
74 SYSCTL_UINT(_kern_geom_eli, OID_AUTO, tries, CTLFLAG_RWTUN, &g_eli_tries, 0,
75 "Number of tries for entering the passphrase");
76 static u_int g_eli_visible_passphrase = GETS_NOECHO;
77 SYSCTL_UINT(_kern_geom_eli, OID_AUTO, visible_passphrase, CTLFLAG_RWTUN,
78 &g_eli_visible_passphrase, 0,
79 "Visibility of passphrase prompt (0 = invisible, 1 = visible, 2 = asterisk)");
80 u_int g_eli_overwrites = G_ELI_OVERWRITES;
81 SYSCTL_UINT(_kern_geom_eli, OID_AUTO, overwrites, CTLFLAG_RWTUN, &g_eli_overwrites,
82 0, "Number of times on-disk keys should be overwritten when destroying them");
83 static u_int g_eli_threads = 0;
84 SYSCTL_UINT(_kern_geom_eli, OID_AUTO, threads, CTLFLAG_RWTUN, &g_eli_threads, 0,
85 "Number of threads doing crypto work");
86 u_int g_eli_batch = 0;
87 SYSCTL_UINT(_kern_geom_eli, OID_AUTO, batch, CTLFLAG_RWTUN, &g_eli_batch, 0,
88 "Use crypto operations batching");
91 * Passphrase cached during boot, in order to be more user-friendly if
92 * there are multiple providers using the same passphrase.
94 static char cached_passphrase[256];
95 static u_int g_eli_boot_passcache = 1;
96 TUNABLE_INT("kern.geom.eli.boot_passcache", &g_eli_boot_passcache);
97 SYSCTL_UINT(_kern_geom_eli, OID_AUTO, boot_passcache, CTLFLAG_RD,
98 &g_eli_boot_passcache, 0,
99 "Passphrases are cached during boot process for possible reuse");
101 fetch_loader_passphrase(void * dummy)
103 char * env_passphrase;
105 KASSERT(dynamic_kenv, ("need dynamic kenv"));
107 if ((env_passphrase = kern_getenv("kern.geom.eli.passphrase")) != NULL) {
108 /* Extract passphrase from the environment. */
109 strlcpy(cached_passphrase, env_passphrase,
110 sizeof(cached_passphrase));
111 freeenv(env_passphrase);
113 /* Wipe the passphrase from the environment. */
114 kern_unsetenv("kern.geom.eli.passphrase");
117 SYSINIT(geli_fetch_loader_passphrase, SI_SUB_KMEM + 1, SI_ORDER_ANY,
118 fetch_loader_passphrase, NULL);
121 zero_boot_passcache(void)
124 explicit_bzero(cached_passphrase, sizeof(cached_passphrase));
128 zero_geli_intake_keys(void)
130 struct keybuf *keybuf;
133 if ((keybuf = get_keybuf()) != NULL) {
134 /* Scan the key buffer, clear all GELI keys. */
135 for (i = 0; i < keybuf->kb_nents; i++) {
136 if (keybuf->kb_ents[i].ke_type == KEYBUF_TYPE_GELI) {
137 explicit_bzero(keybuf->kb_ents[i].ke_data,
138 sizeof(keybuf->kb_ents[i].ke_data));
139 keybuf->kb_ents[i].ke_type = KEYBUF_TYPE_NONE;
146 zero_intake_passcache(void *dummy)
148 zero_boot_passcache();
149 zero_geli_intake_keys();
151 EVENTHANDLER_DEFINE(mountroot, zero_intake_passcache, NULL, 0);
153 static eventhandler_tag g_eli_pre_sync = NULL;
155 static int g_eli_read_metadata_offset(struct g_class *mp, struct g_provider *pp,
156 off_t offset, struct g_eli_metadata *md);
158 static int g_eli_destroy_geom(struct gctl_req *req, struct g_class *mp,
160 static void g_eli_init(struct g_class *mp);
161 static void g_eli_fini(struct g_class *mp);
163 static g_taste_t g_eli_taste;
164 static g_dumpconf_t g_eli_dumpconf;
166 struct g_class g_eli_class = {
167 .name = G_ELI_CLASS_NAME,
168 .version = G_VERSION,
169 .ctlreq = g_eli_config,
170 .taste = g_eli_taste,
171 .destroy_geom = g_eli_destroy_geom,
180 * g_eli_start -> g_eli_crypto_read -> g_io_request -> g_eli_read_done -> g_eli_crypto_run -> g_eli_crypto_read_done -> g_io_deliver
182 * g_eli_start -> g_eli_crypto_run -> g_eli_crypto_write_done -> g_io_request -> g_eli_write_done -> g_io_deliver
187 * EAGAIN from crypto(9) means, that we were probably balanced to another crypto
188 * accelerator or something like this.
189 * The function updates the SID and rerun the operation.
192 g_eli_crypto_rerun(struct cryptop *crp)
194 struct g_eli_softc *sc;
195 struct g_eli_worker *wr;
199 bp = (struct bio *)crp->crp_opaque;
200 sc = bp->bio_to->geom->softc;
201 LIST_FOREACH(wr, &sc->sc_workers, w_next) {
202 if (wr->w_number == bp->bio_pflags)
205 KASSERT(wr != NULL, ("Invalid worker (%u).", bp->bio_pflags));
206 G_ELI_DEBUG(1, "Rerunning crypto %s request (sid: %p -> %p).",
207 bp->bio_cmd == BIO_READ ? "READ" : "WRITE", wr->w_sid,
209 wr->w_sid = crp->crp_session;
211 error = crypto_dispatch(crp);
214 G_ELI_DEBUG(1, "%s: crypto_dispatch() returned %d.", __func__, error);
215 crp->crp_etype = error;
220 g_eli_getattr_done(struct bio *bp)
222 if (bp->bio_error == 0 &&
223 !strcmp(bp->bio_attribute, "GEOM::physpath")) {
224 strlcat(bp->bio_data, "/eli", bp->bio_length);
230 * The function is called afer reading encrypted data from the provider.
232 * g_eli_start -> g_eli_crypto_read -> g_io_request -> G_ELI_READ_DONE -> g_eli_crypto_run -> g_eli_crypto_read_done -> g_io_deliver
235 g_eli_read_done(struct bio *bp)
237 struct g_eli_softc *sc;
240 G_ELI_LOGREQ(2, bp, "Request done.");
241 pbp = bp->bio_parent;
242 if (pbp->bio_error == 0 && bp->bio_error != 0)
243 pbp->bio_error = bp->bio_error;
246 * Do we have all sectors already?
249 if (pbp->bio_inbed < pbp->bio_children)
251 sc = pbp->bio_to->geom->softc;
252 if (pbp->bio_error != 0) {
253 G_ELI_LOGREQ(0, pbp, "%s() failed (error=%d)", __func__,
255 pbp->bio_completed = 0;
256 if (pbp->bio_driver2 != NULL) {
257 free(pbp->bio_driver2, M_ELI);
258 pbp->bio_driver2 = NULL;
260 g_io_deliver(pbp, pbp->bio_error);
262 atomic_subtract_int(&sc->sc_inflight, 1);
265 mtx_lock(&sc->sc_queue_mtx);
266 bioq_insert_tail(&sc->sc_queue, pbp);
267 mtx_unlock(&sc->sc_queue_mtx);
272 * The function is called after we encrypt and write data.
274 * g_eli_start -> g_eli_crypto_run -> g_eli_crypto_write_done -> g_io_request -> G_ELI_WRITE_DONE -> g_io_deliver
277 g_eli_write_done(struct bio *bp)
279 struct g_eli_softc *sc;
282 G_ELI_LOGREQ(2, bp, "Request done.");
283 pbp = bp->bio_parent;
284 if (pbp->bio_error == 0 && bp->bio_error != 0)
285 pbp->bio_error = bp->bio_error;
288 * Do we have all sectors already?
291 if (pbp->bio_inbed < pbp->bio_children)
293 free(pbp->bio_driver2, M_ELI);
294 pbp->bio_driver2 = NULL;
295 if (pbp->bio_error != 0) {
296 G_ELI_LOGREQ(0, pbp, "%s() failed (error=%d)", __func__,
298 pbp->bio_completed = 0;
300 pbp->bio_completed = pbp->bio_length;
303 * Write is finished, send it up.
305 sc = pbp->bio_to->geom->softc;
306 g_io_deliver(pbp, pbp->bio_error);
308 atomic_subtract_int(&sc->sc_inflight, 1);
312 * This function should never be called, but GEOM made as it set ->orphan()
313 * method for every geom.
316 g_eli_orphan_spoil_assert(struct g_consumer *cp)
319 panic("Function %s() called for %s.", __func__, cp->geom->name);
323 g_eli_orphan(struct g_consumer *cp)
325 struct g_eli_softc *sc;
328 sc = cp->geom->softc;
331 g_eli_destroy(sc, TRUE);
335 g_eli_resize(struct g_consumer *cp)
337 struct g_eli_softc *sc;
338 struct g_provider *epp, *pp;
342 sc = cp->geom->softc;
346 if ((sc->sc_flags & G_ELI_FLAG_AUTORESIZE) == 0) {
347 G_ELI_DEBUG(0, "Autoresize is turned off, old size: %jd.",
348 (intmax_t)sc->sc_provsize);
354 if ((sc->sc_flags & G_ELI_FLAG_ONETIME) == 0) {
355 struct g_eli_metadata md;
361 error = g_eli_read_metadata_offset(cp->geom->class, pp,
362 sc->sc_provsize - pp->sectorsize, &md);
364 G_ELI_DEBUG(0, "Cannot read metadata from %s (error=%d).",
369 md.md_provsize = pp->mediasize;
371 sector = malloc(pp->sectorsize, M_ELI, M_WAITOK | M_ZERO);
372 eli_metadata_encode(&md, sector);
373 error = g_write_data(cp, pp->mediasize - pp->sectorsize, sector,
376 G_ELI_DEBUG(0, "Cannot store metadata on %s (error=%d).",
380 explicit_bzero(sector, pp->sectorsize);
381 error = g_write_data(cp, sc->sc_provsize - pp->sectorsize,
382 sector, pp->sectorsize);
384 G_ELI_DEBUG(0, "Cannot clear old metadata from %s (error=%d).",
389 explicit_bzero(&md, sizeof(md));
390 if (sector != NULL) {
391 explicit_bzero(sector, pp->sectorsize);
396 oldsize = sc->sc_mediasize;
397 sc->sc_mediasize = eli_mediasize(sc, pp->mediasize, pp->sectorsize);
398 g_eli_key_resize(sc);
399 sc->sc_provsize = pp->mediasize;
401 epp = LIST_FIRST(&sc->sc_geom->provider);
402 g_resize_provider(epp, sc->sc_mediasize);
403 G_ELI_DEBUG(0, "Device %s size changed from %jd to %jd.", epp->name,
404 (intmax_t)oldsize, (intmax_t)sc->sc_mediasize);
409 * G_ELI_START -> g_eli_crypto_read -> g_io_request -> g_eli_read_done -> g_eli_crypto_run -> g_eli_crypto_read_done -> g_io_deliver
411 * G_ELI_START -> g_eli_crypto_run -> g_eli_crypto_write_done -> g_io_request -> g_eli_write_done -> g_io_deliver
414 g_eli_start(struct bio *bp)
416 struct g_eli_softc *sc;
417 struct g_consumer *cp;
420 sc = bp->bio_to->geom->softc;
422 ("Provider's error should be set (error=%d)(device=%s).",
423 bp->bio_to->error, bp->bio_to->name));
424 G_ELI_LOGREQ(2, bp, "Request received.");
426 switch (bp->bio_cmd) {
436 * If the user hasn't set the NODELETE flag, we just pass
437 * it down the stack and let the layers beneath us do (or
438 * not) whatever they do with it. If they have, we
439 * reject it. A possible extension would be an
440 * additional flag to take it as a hint to shred the data
441 * with [multiple?] overwrites.
443 if (!(sc->sc_flags & G_ELI_FLAG_NODELETE))
446 g_io_deliver(bp, EOPNOTSUPP);
449 cbp = g_clone_bio(bp);
451 g_io_deliver(bp, ENOMEM);
454 bp->bio_driver1 = cbp;
455 bp->bio_pflags = G_ELI_NEW_BIO;
456 switch (bp->bio_cmd) {
458 if (!(sc->sc_flags & G_ELI_FLAG_AUTH)) {
459 g_eli_crypto_read(sc, bp, 0);
464 mtx_lock(&sc->sc_queue_mtx);
465 bioq_insert_tail(&sc->sc_queue, bp);
466 mtx_unlock(&sc->sc_queue_mtx);
474 if (bp->bio_cmd == BIO_GETATTR)
475 cbp->bio_done = g_eli_getattr_done;
477 cbp->bio_done = g_std_done;
478 cp = LIST_FIRST(&sc->sc_geom->consumer);
479 cbp->bio_to = cp->provider;
480 G_ELI_LOGREQ(2, cbp, "Sending request.");
481 g_io_request(cbp, cp);
487 g_eli_newsession(struct g_eli_worker *wr)
489 struct g_eli_softc *sc;
490 struct cryptoini crie, cria;
495 bzero(&crie, sizeof(crie));
496 crie.cri_alg = sc->sc_ealgo;
497 crie.cri_klen = sc->sc_ekeylen;
498 if (sc->sc_ealgo == CRYPTO_AES_XTS)
500 if ((sc->sc_flags & G_ELI_FLAG_FIRST_KEY) != 0) {
501 crie.cri_key = g_eli_key_hold(sc, 0,
502 LIST_FIRST(&sc->sc_geom->consumer)->provider->sectorsize);
504 crie.cri_key = sc->sc_ekey;
506 if (sc->sc_flags & G_ELI_FLAG_AUTH) {
507 bzero(&cria, sizeof(cria));
508 cria.cri_alg = sc->sc_aalgo;
509 cria.cri_klen = sc->sc_akeylen;
510 cria.cri_key = sc->sc_akey;
511 crie.cri_next = &cria;
514 switch (sc->sc_crypto) {
515 case G_ELI_CRYPTO_SW:
516 error = crypto_newsession(&wr->w_sid, &crie,
517 CRYPTOCAP_F_SOFTWARE);
519 case G_ELI_CRYPTO_HW:
520 error = crypto_newsession(&wr->w_sid, &crie,
521 CRYPTOCAP_F_HARDWARE);
523 case G_ELI_CRYPTO_UNKNOWN:
524 error = crypto_newsession(&wr->w_sid, &crie,
525 CRYPTOCAP_F_HARDWARE);
527 mtx_lock(&sc->sc_queue_mtx);
528 if (sc->sc_crypto == G_ELI_CRYPTO_UNKNOWN)
529 sc->sc_crypto = G_ELI_CRYPTO_HW;
530 mtx_unlock(&sc->sc_queue_mtx);
532 error = crypto_newsession(&wr->w_sid, &crie,
533 CRYPTOCAP_F_SOFTWARE);
534 mtx_lock(&sc->sc_queue_mtx);
535 if (sc->sc_crypto == G_ELI_CRYPTO_UNKNOWN)
536 sc->sc_crypto = G_ELI_CRYPTO_SW;
537 mtx_unlock(&sc->sc_queue_mtx);
541 panic("%s: invalid condition", __func__);
544 if ((sc->sc_flags & G_ELI_FLAG_FIRST_KEY) != 0)
545 g_eli_key_drop(sc, crie.cri_key);
551 g_eli_freesession(struct g_eli_worker *wr)
554 crypto_freesession(wr->w_sid);
558 g_eli_cancel(struct g_eli_softc *sc)
562 mtx_assert(&sc->sc_queue_mtx, MA_OWNED);
564 while ((bp = bioq_takefirst(&sc->sc_queue)) != NULL) {
565 KASSERT(bp->bio_pflags == G_ELI_NEW_BIO,
566 ("Not new bio when canceling (bp=%p).", bp));
567 g_io_deliver(bp, ENXIO);
572 g_eli_takefirst(struct g_eli_softc *sc)
576 mtx_assert(&sc->sc_queue_mtx, MA_OWNED);
578 if (!(sc->sc_flags & G_ELI_FLAG_SUSPEND))
579 return (bioq_takefirst(&sc->sc_queue));
581 * Device suspended, so we skip new I/O requests.
583 TAILQ_FOREACH(bp, &sc->sc_queue.queue, bio_queue) {
584 if (bp->bio_pflags != G_ELI_NEW_BIO)
588 bioq_remove(&sc->sc_queue, bp);
593 * This is the main function for kernel worker thread when we don't have
594 * hardware acceleration and we have to do cryptography in software.
595 * Dedicated thread is needed, so we don't slow down g_up/g_down GEOM
596 * threads with crypto work.
599 g_eli_worker(void *arg)
601 struct g_eli_softc *sc;
602 struct g_eli_worker *wr;
608 #ifdef EARLY_AP_STARTUP
609 MPASS(!sc->sc_cpubind || smp_started);
611 /* Before sched_bind() to a CPU, wait for all CPUs to go on-line. */
612 if (sc->sc_cpubind) {
614 tsleep(wr, 0, "geli:smp", hz / 4);
617 thread_lock(curthread);
618 sched_prio(curthread, PUSER);
620 sched_bind(curthread, wr->w_number % mp_ncpus);
621 thread_unlock(curthread);
623 G_ELI_DEBUG(1, "Thread %s started.", curthread->td_proc->p_comm);
626 mtx_lock(&sc->sc_queue_mtx);
628 bp = g_eli_takefirst(sc);
630 if (sc->sc_flags & G_ELI_FLAG_DESTROY) {
632 LIST_REMOVE(wr, w_next);
633 g_eli_freesession(wr);
635 G_ELI_DEBUG(1, "Thread %s exiting.",
636 curthread->td_proc->p_comm);
637 wakeup(&sc->sc_workers);
638 mtx_unlock(&sc->sc_queue_mtx);
641 while (sc->sc_flags & G_ELI_FLAG_SUSPEND) {
642 if (sc->sc_inflight > 0) {
643 G_ELI_DEBUG(0, "inflight=%d",
646 * We still have inflight BIOs, so
649 msleep(sc, &sc->sc_queue_mtx, PRIBIO,
654 * Suspend requested, mark the worker as
655 * suspended and go to sleep.
658 g_eli_freesession(wr);
659 wr->w_active = FALSE;
661 wakeup(&sc->sc_workers);
662 msleep(sc, &sc->sc_queue_mtx, PRIBIO,
665 !(sc->sc_flags & G_ELI_FLAG_SUSPEND)) {
666 error = g_eli_newsession(wr);
668 ("g_eli_newsession() failed on resume (error=%d)",
674 msleep(sc, &sc->sc_queue_mtx, PDROP, "geli:w", 0);
677 if (bp->bio_pflags == G_ELI_NEW_BIO)
678 atomic_add_int(&sc->sc_inflight, 1);
679 mtx_unlock(&sc->sc_queue_mtx);
680 if (bp->bio_pflags == G_ELI_NEW_BIO) {
682 if (sc->sc_flags & G_ELI_FLAG_AUTH) {
683 if (bp->bio_cmd == BIO_READ)
684 g_eli_auth_read(sc, bp);
686 g_eli_auth_run(wr, bp);
688 if (bp->bio_cmd == BIO_READ)
689 g_eli_crypto_read(sc, bp, 1);
691 g_eli_crypto_run(wr, bp);
694 if (sc->sc_flags & G_ELI_FLAG_AUTH)
695 g_eli_auth_run(wr, bp);
697 g_eli_crypto_run(wr, bp);
703 g_eli_read_metadata_offset(struct g_class *mp, struct g_provider *pp,
704 off_t offset, struct g_eli_metadata *md)
707 struct g_consumer *cp;
713 gp = g_new_geomf(mp, "eli:taste");
714 gp->start = g_eli_start;
715 gp->access = g_std_access;
717 * g_eli_read_metadata() is always called from the event thread.
718 * Our geom is created and destroyed in the same event, so there
719 * could be no orphan nor spoil event in the meantime.
721 gp->orphan = g_eli_orphan_spoil_assert;
722 gp->spoiled = g_eli_orphan_spoil_assert;
723 cp = g_new_consumer(gp);
724 error = g_attach(cp, pp);
727 error = g_access(cp, 1, 0, 0);
731 buf = g_read_data(cp, offset, pp->sectorsize, &error);
735 error = eli_metadata_decode(buf, md);
738 /* Metadata was read and decoded successfully. */
742 if (cp->provider != NULL) {
744 g_access(cp, -1, 0, 0);
747 g_destroy_consumer(cp);
753 g_eli_read_metadata(struct g_class *mp, struct g_provider *pp,
754 struct g_eli_metadata *md)
757 return (g_eli_read_metadata_offset(mp, pp,
758 pp->mediasize - pp->sectorsize, md));
762 * The function is called when we had last close on provider and user requested
763 * to close it when this situation occur.
766 g_eli_last_close(void *arg, int flags __unused)
774 strlcpy(gpname, gp->name, sizeof(gpname));
775 error = g_eli_destroy(gp->softc, TRUE);
776 KASSERT(error == 0, ("Cannot detach %s on last close (error=%d).",
778 G_ELI_DEBUG(0, "Detached %s on last close.", gpname);
782 g_eli_access(struct g_provider *pp, int dr, int dw, int de)
784 struct g_eli_softc *sc;
791 if (sc->sc_flags & G_ELI_FLAG_RO) {
792 /* Deny write attempts. */
795 /* Someone is opening us for write, we need to remember that. */
796 sc->sc_flags |= G_ELI_FLAG_WOPEN;
799 /* Is this the last close? */
800 if (pp->acr + dr > 0 || pp->acw + dw > 0 || pp->ace + de > 0)
804 * Automatically detach on last close if requested.
806 if ((sc->sc_flags & G_ELI_FLAG_RW_DETACH) ||
807 (sc->sc_flags & G_ELI_FLAG_WOPEN)) {
808 g_post_event(g_eli_last_close, gp, M_WAITOK, NULL);
814 g_eli_cpu_is_disabled(int cpu)
817 return (CPU_ISSET(cpu, &hlt_cpus_mask));
824 g_eli_create(struct gctl_req *req, struct g_class *mp, struct g_provider *bpp,
825 const struct g_eli_metadata *md, const u_char *mkey, int nkey)
827 struct g_eli_softc *sc;
828 struct g_eli_worker *wr;
830 struct g_provider *pp;
831 struct g_consumer *cp;
835 G_ELI_DEBUG(1, "Creating device %s%s.", bpp->name, G_ELI_SUFFIX);
837 gp = g_new_geomf(mp, "%s%s", bpp->name, G_ELI_SUFFIX);
838 sc = malloc(sizeof(*sc), M_ELI, M_WAITOK | M_ZERO);
839 gp->start = g_eli_start;
841 * Spoiling can happen even though we have the provider open
842 * exclusively, e.g. through media change events.
844 gp->spoiled = g_eli_orphan;
845 gp->orphan = g_eli_orphan;
846 gp->resize = g_eli_resize;
847 gp->dumpconf = g_eli_dumpconf;
849 * If detach-on-last-close feature is not enabled and we don't operate
850 * on read-only provider, we can simply use g_std_access().
852 if (md->md_flags & (G_ELI_FLAG_WO_DETACH | G_ELI_FLAG_RO))
853 gp->access = g_eli_access;
855 gp->access = g_std_access;
857 eli_metadata_softc(sc, md, bpp->sectorsize, bpp->mediasize);
863 bioq_init(&sc->sc_queue);
864 mtx_init(&sc->sc_queue_mtx, "geli:queue", NULL, MTX_DEF);
865 mtx_init(&sc->sc_ekeys_lock, "geli:ekeys", NULL, MTX_DEF);
868 cp = g_new_consumer(gp);
869 error = g_attach(cp, bpp);
872 gctl_error(req, "Cannot attach to %s (error=%d).",
875 G_ELI_DEBUG(1, "Cannot attach to %s (error=%d).",
881 * Keep provider open all the time, so we can run critical tasks,
882 * like Master Keys deletion, without wondering if we can open
884 * We don't open provider for writing only when user requested read-only
887 dcw = (sc->sc_flags & G_ELI_FLAG_RO) ? 0 : 1;
888 error = g_access(cp, 1, dcw, 1);
891 gctl_error(req, "Cannot access %s (error=%d).",
894 G_ELI_DEBUG(1, "Cannot access %s (error=%d).",
901 * Remember the keys in our softc structure.
903 g_eli_mkey_propagate(sc, mkey);
905 LIST_INIT(&sc->sc_workers);
907 threads = g_eli_threads;
910 sc->sc_cpubind = (mp_ncpus > 1 && threads == mp_ncpus);
911 for (i = 0; i < threads; i++) {
912 if (g_eli_cpu_is_disabled(i)) {
913 G_ELI_DEBUG(1, "%s: CPU %u disabled, skipping.",
917 wr = malloc(sizeof(*wr), M_ELI, M_WAITOK | M_ZERO);
922 error = g_eli_newsession(wr);
926 gctl_error(req, "Cannot set up crypto session "
927 "for %s (error=%d).", bpp->name, error);
929 G_ELI_DEBUG(1, "Cannot set up crypto session "
930 "for %s (error=%d).", bpp->name, error);
935 error = kproc_create(g_eli_worker, wr, &wr->w_proc, 0, 0,
936 "g_eli[%u] %s", i, bpp->name);
938 g_eli_freesession(wr);
941 gctl_error(req, "Cannot create kernel thread "
942 "for %s (error=%d).", bpp->name, error);
944 G_ELI_DEBUG(1, "Cannot create kernel thread "
945 "for %s (error=%d).", bpp->name, error);
949 LIST_INSERT_HEAD(&sc->sc_workers, wr, w_next);
953 * Create decrypted provider.
955 pp = g_new_providerf(gp, "%s%s", bpp->name, G_ELI_SUFFIX);
956 pp->mediasize = sc->sc_mediasize;
957 pp->sectorsize = sc->sc_sectorsize;
959 g_error_provider(pp, 0);
961 G_ELI_DEBUG(0, "Device %s created.", pp->name);
962 G_ELI_DEBUG(0, "Encryption: %s %u", g_eli_algo2str(sc->sc_ealgo),
964 switch (sc->sc_ealgo) {
965 case CRYPTO_3DES_CBC:
967 "support for GEOM_ELI volumes encrypted with 3des");
971 "support for GEOM_ELI volumes encrypted with blowfish");
974 if (sc->sc_flags & G_ELI_FLAG_AUTH) {
975 G_ELI_DEBUG(0, " Integrity: %s", g_eli_algo2str(sc->sc_aalgo));
976 switch (sc->sc_aalgo) {
977 case CRYPTO_MD5_HMAC:
979 "support for GEOM_ELI volumes authenticated with hmac/md5");
983 G_ELI_DEBUG(0, " Crypto: %s",
984 sc->sc_crypto == G_ELI_CRYPTO_SW ? "software" : "hardware");
987 mtx_lock(&sc->sc_queue_mtx);
988 sc->sc_flags |= G_ELI_FLAG_DESTROY;
991 * Wait for kernel threads self destruction.
993 while (!LIST_EMPTY(&sc->sc_workers)) {
994 msleep(&sc->sc_workers, &sc->sc_queue_mtx, PRIBIO,
997 mtx_destroy(&sc->sc_queue_mtx);
998 if (cp->provider != NULL) {
1000 g_access(cp, -1, -dcw, -1);
1003 g_destroy_consumer(cp);
1005 g_eli_key_destroy(sc);
1006 bzero(sc, sizeof(*sc));
1012 g_eli_destroy(struct g_eli_softc *sc, boolean_t force)
1015 struct g_provider *pp;
1017 g_topology_assert();
1023 pp = LIST_FIRST(&gp->provider);
1024 if (pp != NULL && (pp->acr != 0 || pp->acw != 0 || pp->ace != 0)) {
1026 G_ELI_DEBUG(1, "Device %s is still open, so it "
1027 "cannot be definitely removed.", pp->name);
1028 sc->sc_flags |= G_ELI_FLAG_RW_DETACH;
1029 gp->access = g_eli_access;
1030 g_wither_provider(pp, ENXIO);
1034 "Device %s is still open (r%dw%de%d).", pp->name,
1035 pp->acr, pp->acw, pp->ace);
1040 mtx_lock(&sc->sc_queue_mtx);
1041 sc->sc_flags |= G_ELI_FLAG_DESTROY;
1043 while (!LIST_EMPTY(&sc->sc_workers)) {
1044 msleep(&sc->sc_workers, &sc->sc_queue_mtx, PRIBIO,
1047 mtx_destroy(&sc->sc_queue_mtx);
1049 g_eli_key_destroy(sc);
1050 bzero(sc, sizeof(*sc));
1053 G_ELI_DEBUG(0, "Device %s destroyed.", gp->name);
1054 g_wither_geom_close(gp, ENXIO);
1060 g_eli_destroy_geom(struct gctl_req *req __unused,
1061 struct g_class *mp __unused, struct g_geom *gp)
1063 struct g_eli_softc *sc;
1066 return (g_eli_destroy(sc, FALSE));
1070 g_eli_keyfiles_load(struct hmac_ctx *ctx, const char *provider)
1072 u_char *keyfile, *data;
1073 char *file, name[64];
1077 for (i = 0; ; i++) {
1078 snprintf(name, sizeof(name), "%s:geli_keyfile%d", provider, i);
1079 keyfile = preload_search_by_type(name);
1080 if (keyfile == NULL && i == 0) {
1082 * If there is only one keyfile, allow simpler name.
1084 snprintf(name, sizeof(name), "%s:geli_keyfile", provider);
1085 keyfile = preload_search_by_type(name);
1087 if (keyfile == NULL)
1088 return (i); /* Return number of loaded keyfiles. */
1089 data = preload_fetch_addr(keyfile);
1091 G_ELI_DEBUG(0, "Cannot find key file data for %s.",
1095 size = preload_fetch_size(keyfile);
1097 G_ELI_DEBUG(0, "Cannot find key file size for %s.",
1101 file = preload_search_info(keyfile, MODINFO_NAME);
1103 G_ELI_DEBUG(0, "Cannot find key file name for %s.",
1107 G_ELI_DEBUG(1, "Loaded keyfile %s for %s (type: %s).", file,
1109 g_eli_crypto_hmac_update(ctx, data, size);
1114 g_eli_keyfiles_clear(const char *provider)
1116 u_char *keyfile, *data;
1121 for (i = 0; ; i++) {
1122 snprintf(name, sizeof(name), "%s:geli_keyfile%d", provider, i);
1123 keyfile = preload_search_by_type(name);
1124 if (keyfile == NULL)
1126 data = preload_fetch_addr(keyfile);
1127 size = preload_fetch_size(keyfile);
1128 if (data != NULL && size != 0)
1134 * Tasting is only made on boot.
1135 * We detect providers which should be attached before root is mounted.
1137 static struct g_geom *
1138 g_eli_taste(struct g_class *mp, struct g_provider *pp, int flags __unused)
1140 struct g_eli_metadata md;
1142 struct hmac_ctx ctx;
1143 char passphrase[256];
1144 u_char key[G_ELI_USERKEYLEN], mkey[G_ELI_DATAIVKEYLEN];
1145 u_int i, nkey, nkeyfiles, tries, showpass;
1147 struct keybuf *keybuf;
1149 g_trace(G_T_TOPOLOGY, "%s(%s, %s)", __func__, mp->name, pp->name);
1150 g_topology_assert();
1152 if (root_mounted() || g_eli_tries == 0)
1155 G_ELI_DEBUG(3, "Tasting %s.", pp->name);
1157 error = g_eli_read_metadata(mp, pp, &md);
1162 if (strcmp(md.md_magic, G_ELI_MAGIC) != 0)
1164 if (md.md_version > G_ELI_VERSION) {
1165 printf("geom_eli.ko module is too old to handle %s.\n",
1169 if (md.md_provsize != pp->mediasize)
1171 /* Should we attach it on boot? */
1172 if (!(md.md_flags & G_ELI_FLAG_BOOT) &&
1173 !(md.md_flags & G_ELI_FLAG_GELIBOOT))
1175 if (md.md_keys == 0x00) {
1176 G_ELI_DEBUG(0, "No valid keys on %s.", pp->name);
1179 if (md.md_iterations == -1) {
1180 /* If there is no passphrase, we try only once. */
1183 /* Ask for the passphrase no more than g_eli_tries times. */
1184 tries = g_eli_tries;
1187 if ((keybuf = get_keybuf()) != NULL) {
1188 /* Scan the key buffer, try all GELI keys. */
1189 for (i = 0; i < keybuf->kb_nents; i++) {
1190 if (keybuf->kb_ents[i].ke_type == KEYBUF_TYPE_GELI) {
1191 memcpy(key, keybuf->kb_ents[i].ke_data,
1194 if (g_eli_mkey_decrypt_any(&md, key,
1195 mkey, &nkey) == 0 ) {
1196 explicit_bzero(key, sizeof(key));
1203 for (i = 0; i <= tries; i++) {
1204 g_eli_crypto_hmac_init(&ctx, NULL, 0);
1207 * Load all key files.
1209 nkeyfiles = g_eli_keyfiles_load(&ctx, pp->name);
1211 if (nkeyfiles == 0 && md.md_iterations == -1) {
1213 * No key files and no passphrase, something is
1214 * definitely wrong here.
1215 * geli(8) doesn't allow for such situation, so assume
1216 * that there was really no passphrase and in that case
1217 * key files are no properly defined in loader.conf.
1220 "Found no key files in loader.conf for %s.",
1225 /* Ask for the passphrase if defined. */
1226 if (md.md_iterations >= 0) {
1227 /* Try first with cached passphrase. */
1229 if (!g_eli_boot_passcache)
1231 memcpy(passphrase, cached_passphrase,
1232 sizeof(passphrase));
1234 printf("Enter passphrase for %s: ", pp->name);
1235 showpass = g_eli_visible_passphrase;
1236 if ((md.md_flags & G_ELI_FLAG_GELIDISPLAYPASS) != 0)
1237 showpass = GETS_ECHOPASS;
1238 cngets(passphrase, sizeof(passphrase),
1240 memcpy(cached_passphrase, passphrase,
1241 sizeof(passphrase));
1246 * Prepare Derived-Key from the user passphrase.
1248 if (md.md_iterations == 0) {
1249 g_eli_crypto_hmac_update(&ctx, md.md_salt,
1250 sizeof(md.md_salt));
1251 g_eli_crypto_hmac_update(&ctx, passphrase,
1252 strlen(passphrase));
1253 explicit_bzero(passphrase, sizeof(passphrase));
1254 } else if (md.md_iterations > 0) {
1255 u_char dkey[G_ELI_USERKEYLEN];
1257 pkcs5v2_genkey(dkey, sizeof(dkey), md.md_salt,
1258 sizeof(md.md_salt), passphrase, md.md_iterations);
1259 bzero(passphrase, sizeof(passphrase));
1260 g_eli_crypto_hmac_update(&ctx, dkey, sizeof(dkey));
1261 explicit_bzero(dkey, sizeof(dkey));
1264 g_eli_crypto_hmac_final(&ctx, key, 0);
1267 * Decrypt Master-Key.
1269 error = g_eli_mkey_decrypt_any(&md, key, mkey, &nkey);
1270 bzero(key, sizeof(key));
1274 "Wrong key for %s. No tries left.",
1276 g_eli_keyfiles_clear(pp->name);
1281 "Wrong key for %s. Tries left: %u.",
1282 pp->name, tries - i);
1286 } else if (error > 0) {
1288 "Cannot decrypt Master Key for %s (error=%d).",
1290 g_eli_keyfiles_clear(pp->name);
1293 g_eli_keyfiles_clear(pp->name);
1294 G_ELI_DEBUG(1, "Using Master Key %u for %s.", nkey, pp->name);
1300 * We have correct key, let's attach provider.
1302 gp = g_eli_create(NULL, mp, pp, &md, mkey, nkey);
1303 bzero(mkey, sizeof(mkey));
1304 bzero(&md, sizeof(md));
1306 G_ELI_DEBUG(0, "Cannot create device %s%s.", pp->name,
1314 g_eli_dumpconf(struct sbuf *sb, const char *indent, struct g_geom *gp,
1315 struct g_consumer *cp, struct g_provider *pp)
1317 struct g_eli_softc *sc;
1319 g_topology_assert();
1323 if (pp != NULL || cp != NULL)
1324 return; /* Nothing here. */
1326 sbuf_printf(sb, "%s<KeysTotal>%ju</KeysTotal>\n", indent,
1327 (uintmax_t)sc->sc_ekeys_total);
1328 sbuf_printf(sb, "%s<KeysAllocated>%ju</KeysAllocated>\n", indent,
1329 (uintmax_t)sc->sc_ekeys_allocated);
1330 sbuf_printf(sb, "%s<Flags>", indent);
1331 if (sc->sc_flags == 0)
1332 sbuf_cat(sb, "NONE");
1336 #define ADD_FLAG(flag, name) do { \
1337 if (sc->sc_flags & (flag)) { \
1339 sbuf_cat(sb, ", "); \
1342 sbuf_cat(sb, name); \
1345 ADD_FLAG(G_ELI_FLAG_SUSPEND, "SUSPEND");
1346 ADD_FLAG(G_ELI_FLAG_SINGLE_KEY, "SINGLE-KEY");
1347 ADD_FLAG(G_ELI_FLAG_NATIVE_BYTE_ORDER, "NATIVE-BYTE-ORDER");
1348 ADD_FLAG(G_ELI_FLAG_ONETIME, "ONETIME");
1349 ADD_FLAG(G_ELI_FLAG_BOOT, "BOOT");
1350 ADD_FLAG(G_ELI_FLAG_WO_DETACH, "W-DETACH");
1351 ADD_FLAG(G_ELI_FLAG_RW_DETACH, "RW-DETACH");
1352 ADD_FLAG(G_ELI_FLAG_AUTH, "AUTH");
1353 ADD_FLAG(G_ELI_FLAG_WOPEN, "W-OPEN");
1354 ADD_FLAG(G_ELI_FLAG_DESTROY, "DESTROY");
1355 ADD_FLAG(G_ELI_FLAG_RO, "READ-ONLY");
1356 ADD_FLAG(G_ELI_FLAG_NODELETE, "NODELETE");
1357 ADD_FLAG(G_ELI_FLAG_GELIBOOT, "GELIBOOT");
1358 ADD_FLAG(G_ELI_FLAG_GELIDISPLAYPASS, "GELIDISPLAYPASS");
1359 ADD_FLAG(G_ELI_FLAG_AUTORESIZE, "AUTORESIZE");
1362 sbuf_cat(sb, "</Flags>\n");
1364 if (!(sc->sc_flags & G_ELI_FLAG_ONETIME)) {
1365 sbuf_printf(sb, "%s<UsedKey>%u</UsedKey>\n", indent,
1368 sbuf_printf(sb, "%s<Version>%u</Version>\n", indent, sc->sc_version);
1369 sbuf_printf(sb, "%s<Crypto>", indent);
1370 switch (sc->sc_crypto) {
1371 case G_ELI_CRYPTO_HW:
1372 sbuf_cat(sb, "hardware");
1374 case G_ELI_CRYPTO_SW:
1375 sbuf_cat(sb, "software");
1378 sbuf_cat(sb, "UNKNOWN");
1381 sbuf_cat(sb, "</Crypto>\n");
1382 if (sc->sc_flags & G_ELI_FLAG_AUTH) {
1384 "%s<AuthenticationAlgorithm>%s</AuthenticationAlgorithm>\n",
1385 indent, g_eli_algo2str(sc->sc_aalgo));
1387 sbuf_printf(sb, "%s<KeyLength>%u</KeyLength>\n", indent,
1389 sbuf_printf(sb, "%s<EncryptionAlgorithm>%s</EncryptionAlgorithm>\n",
1390 indent, g_eli_algo2str(sc->sc_ealgo));
1391 sbuf_printf(sb, "%s<State>%s</State>\n", indent,
1392 (sc->sc_flags & G_ELI_FLAG_SUSPEND) ? "SUSPENDED" : "ACTIVE");
1396 g_eli_shutdown_pre_sync(void *arg, int howto)
1399 struct g_geom *gp, *gp2;
1400 struct g_provider *pp;
1401 struct g_eli_softc *sc;
1406 LIST_FOREACH_SAFE(gp, &mp->geom, geom, gp2) {
1410 pp = LIST_FIRST(&gp->provider);
1411 KASSERT(pp != NULL, ("No provider? gp=%p (%s)", gp, gp->name));
1412 if (pp->acr + pp->acw + pp->ace == 0)
1413 error = g_eli_destroy(sc, TRUE);
1415 sc->sc_flags |= G_ELI_FLAG_RW_DETACH;
1416 gp->access = g_eli_access;
1419 g_topology_unlock();
1423 g_eli_init(struct g_class *mp)
1426 g_eli_pre_sync = EVENTHANDLER_REGISTER(shutdown_pre_sync,
1427 g_eli_shutdown_pre_sync, mp, SHUTDOWN_PRI_FIRST);
1428 if (g_eli_pre_sync == NULL)
1429 G_ELI_DEBUG(0, "Warning! Cannot register shutdown event.");
1433 g_eli_fini(struct g_class *mp)
1436 if (g_eli_pre_sync != NULL)
1437 EVENTHANDLER_DEREGISTER(shutdown_pre_sync, g_eli_pre_sync);
1440 DECLARE_GEOM_CLASS(g_eli_class, g_eli);
1441 MODULE_DEPEND(g_eli, crypto, 1, 1, 1);
1442 MODULE_VERSION(geom_eli, 0);