2 * Copyright (c) 2005-2011 Pawel Jakub Dawidek <pawel@dawidek.net>
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
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.
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
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
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>
36 #include <sys/mutex.h>
39 #include <sys/sysctl.h>
40 #include <sys/malloc.h>
41 #include <sys/eventhandler.h>
42 #include <sys/kthread.h>
44 #include <sys/sched.h>
47 #include <sys/vnode.h>
51 #include <geom/geom.h>
52 #include <geom/eli/g_eli.h>
53 #include <geom/eli/pkcs5v2.h>
55 FEATURE(geom_eli, "GEOM crypto module");
57 MALLOC_DEFINE(M_ELI, "eli data", "GEOM_ELI Data");
59 SYSCTL_DECL(_kern_geom);
60 SYSCTL_NODE(_kern_geom, OID_AUTO, eli, CTLFLAG_RW, 0, "GEOM_ELI stuff");
61 static int g_eli_version = G_ELI_VERSION;
62 SYSCTL_INT(_kern_geom_eli, OID_AUTO, version, CTLFLAG_RD, &g_eli_version, 0,
65 TUNABLE_INT("kern.geom.eli.debug", &g_eli_debug);
66 SYSCTL_INT(_kern_geom_eli, OID_AUTO, debug, CTLFLAG_RW, &g_eli_debug, 0,
68 static u_int g_eli_tries = 3;
69 TUNABLE_INT("kern.geom.eli.tries", &g_eli_tries);
70 SYSCTL_UINT(_kern_geom_eli, OID_AUTO, tries, CTLFLAG_RW, &g_eli_tries, 0,
71 "Number of tries for entering the passphrase");
72 static u_int g_eli_visible_passphrase = GETS_NOECHO;
73 TUNABLE_INT("kern.geom.eli.visible_passphrase", &g_eli_visible_passphrase);
74 SYSCTL_UINT(_kern_geom_eli, OID_AUTO, visible_passphrase, CTLFLAG_RW,
75 &g_eli_visible_passphrase, 0,
76 "Visibility of passphrase prompt (0 = invisible, 1 = visible, 2 = asterisk)");
77 u_int g_eli_overwrites = G_ELI_OVERWRITES;
78 TUNABLE_INT("kern.geom.eli.overwrites", &g_eli_overwrites);
79 SYSCTL_UINT(_kern_geom_eli, OID_AUTO, overwrites, CTLFLAG_RW, &g_eli_overwrites,
80 0, "Number of times on-disk keys should be overwritten when destroying them");
81 static u_int g_eli_threads = 0;
82 TUNABLE_INT("kern.geom.eli.threads", &g_eli_threads);
83 SYSCTL_UINT(_kern_geom_eli, OID_AUTO, threads, CTLFLAG_RW, &g_eli_threads, 0,
84 "Number of threads doing crypto work");
85 u_int g_eli_batch = 0;
86 TUNABLE_INT("kern.geom.eli.batch", &g_eli_batch);
87 SYSCTL_UINT(_kern_geom_eli, OID_AUTO, batch, CTLFLAG_RW, &g_eli_batch, 0,
88 "Use crypto operations batching");
90 static eventhandler_tag g_eli_pre_sync = NULL;
92 static int g_eli_destroy_geom(struct gctl_req *req, struct g_class *mp,
94 static void g_eli_init(struct g_class *mp);
95 static void g_eli_fini(struct g_class *mp);
97 static g_taste_t g_eli_taste;
98 static g_dumpconf_t g_eli_dumpconf;
100 struct g_class g_eli_class = {
101 .name = G_ELI_CLASS_NAME,
102 .version = G_VERSION,
103 .ctlreq = g_eli_config,
104 .taste = g_eli_taste,
105 .destroy_geom = g_eli_destroy_geom,
114 * 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
116 * g_eli_start -> g_eli_crypto_run -> g_eli_crypto_write_done -> g_io_request -> g_eli_write_done -> g_io_deliver
121 * EAGAIN from crypto(9) means, that we were probably balanced to another crypto
122 * accelerator or something like this.
123 * The function updates the SID and rerun the operation.
126 g_eli_crypto_rerun(struct cryptop *crp)
128 struct g_eli_softc *sc;
129 struct g_eli_worker *wr;
133 bp = (struct bio *)crp->crp_opaque;
134 sc = bp->bio_to->geom->softc;
135 LIST_FOREACH(wr, &sc->sc_workers, w_next) {
136 if (wr->w_number == bp->bio_pflags)
139 KASSERT(wr != NULL, ("Invalid worker (%u).", bp->bio_pflags));
140 G_ELI_DEBUG(1, "Rerunning crypto %s request (sid: %ju -> %ju).",
141 bp->bio_cmd == BIO_READ ? "READ" : "WRITE", (uintmax_t)wr->w_sid,
142 (uintmax_t)crp->crp_sid);
143 wr->w_sid = crp->crp_sid;
145 error = crypto_dispatch(crp);
148 G_ELI_DEBUG(1, "%s: crypto_dispatch() returned %d.", __func__, error);
149 crp->crp_etype = error;
154 * The function is called afer reading encrypted data from the provider.
156 * 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
159 g_eli_read_done(struct bio *bp)
161 struct g_eli_softc *sc;
164 G_ELI_LOGREQ(2, bp, "Request done.");
165 pbp = bp->bio_parent;
166 if (pbp->bio_error == 0)
167 pbp->bio_error = bp->bio_error;
170 * Do we have all sectors already?
173 if (pbp->bio_inbed < pbp->bio_children)
175 sc = pbp->bio_to->geom->softc;
176 if (pbp->bio_error != 0) {
177 G_ELI_LOGREQ(0, pbp, "%s() failed", __func__);
178 pbp->bio_completed = 0;
179 if (pbp->bio_driver2 != NULL) {
180 free(pbp->bio_driver2, M_ELI);
181 pbp->bio_driver2 = NULL;
183 g_io_deliver(pbp, pbp->bio_error);
184 atomic_subtract_int(&sc->sc_inflight, 1);
187 mtx_lock(&sc->sc_queue_mtx);
188 bioq_insert_tail(&sc->sc_queue, pbp);
189 mtx_unlock(&sc->sc_queue_mtx);
194 * The function is called after we encrypt and write data.
196 * g_eli_start -> g_eli_crypto_run -> g_eli_crypto_write_done -> g_io_request -> G_ELI_WRITE_DONE -> g_io_deliver
199 g_eli_write_done(struct bio *bp)
201 struct g_eli_softc *sc;
204 G_ELI_LOGREQ(2, bp, "Request done.");
205 pbp = bp->bio_parent;
206 if (pbp->bio_error == 0) {
207 if (bp->bio_error != 0)
208 pbp->bio_error = bp->bio_error;
212 * Do we have all sectors already?
215 if (pbp->bio_inbed < pbp->bio_children)
217 free(pbp->bio_driver2, M_ELI);
218 pbp->bio_driver2 = NULL;
219 if (pbp->bio_error != 0) {
220 G_ELI_LOGREQ(0, pbp, "Crypto WRITE request failed (error=%d).",
222 pbp->bio_completed = 0;
225 * Write is finished, send it up.
227 pbp->bio_completed = pbp->bio_length;
228 sc = pbp->bio_to->geom->softc;
229 g_io_deliver(pbp, pbp->bio_error);
230 atomic_subtract_int(&sc->sc_inflight, 1);
234 * This function should never be called, but GEOM made as it set ->orphan()
235 * method for every geom.
238 g_eli_orphan_spoil_assert(struct g_consumer *cp)
241 panic("Function %s() called for %s.", __func__, cp->geom->name);
245 g_eli_orphan(struct g_consumer *cp)
247 struct g_eli_softc *sc;
250 sc = cp->geom->softc;
253 g_eli_destroy(sc, TRUE);
258 * 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
260 * G_ELI_START -> g_eli_crypto_run -> g_eli_crypto_write_done -> g_io_request -> g_eli_write_done -> g_io_deliver
263 g_eli_start(struct bio *bp)
265 struct g_eli_softc *sc;
266 struct g_consumer *cp;
269 sc = bp->bio_to->geom->softc;
271 ("Provider's error should be set (error=%d)(device=%s).",
272 bp->bio_to->error, bp->bio_to->name));
273 G_ELI_LOGREQ(2, bp, "Request received.");
275 switch (bp->bio_cmd) {
283 * We could eventually support BIO_DELETE request.
284 * It could be done by overwritting requested sector with
285 * random data g_eli_overwrites number of times.
288 g_io_deliver(bp, EOPNOTSUPP);
291 cbp = g_clone_bio(bp);
293 g_io_deliver(bp, ENOMEM);
296 bp->bio_driver1 = cbp;
297 bp->bio_pflags = G_ELI_NEW_BIO;
298 switch (bp->bio_cmd) {
300 if (!(sc->sc_flags & G_ELI_FLAG_AUTH)) {
301 g_eli_crypto_read(sc, bp, 0);
306 mtx_lock(&sc->sc_queue_mtx);
307 bioq_insert_tail(&sc->sc_queue, bp);
308 mtx_unlock(&sc->sc_queue_mtx);
313 cbp->bio_done = g_std_done;
314 cp = LIST_FIRST(&sc->sc_geom->consumer);
315 cbp->bio_to = cp->provider;
316 G_ELI_LOGREQ(2, cbp, "Sending request.");
317 g_io_request(cbp, cp);
323 g_eli_newsession(struct g_eli_worker *wr)
325 struct g_eli_softc *sc;
326 struct cryptoini crie, cria;
331 bzero(&crie, sizeof(crie));
332 crie.cri_alg = sc->sc_ealgo;
333 crie.cri_klen = sc->sc_ekeylen;
334 if (sc->sc_ealgo == CRYPTO_AES_XTS)
336 if ((sc->sc_flags & G_ELI_FLAG_FIRST_KEY) != 0) {
337 crie.cri_key = g_eli_key_hold(sc, 0,
338 LIST_FIRST(&sc->sc_geom->consumer)->provider->sectorsize);
340 crie.cri_key = sc->sc_ekey;
342 if (sc->sc_flags & G_ELI_FLAG_AUTH) {
343 bzero(&cria, sizeof(cria));
344 cria.cri_alg = sc->sc_aalgo;
345 cria.cri_klen = sc->sc_akeylen;
346 cria.cri_key = sc->sc_akey;
347 crie.cri_next = &cria;
350 switch (sc->sc_crypto) {
351 case G_ELI_CRYPTO_SW:
352 error = crypto_newsession(&wr->w_sid, &crie,
353 CRYPTOCAP_F_SOFTWARE);
355 case G_ELI_CRYPTO_HW:
356 error = crypto_newsession(&wr->w_sid, &crie,
357 CRYPTOCAP_F_HARDWARE);
359 case G_ELI_CRYPTO_UNKNOWN:
360 error = crypto_newsession(&wr->w_sid, &crie,
361 CRYPTOCAP_F_HARDWARE);
363 mtx_lock(&sc->sc_queue_mtx);
364 if (sc->sc_crypto == G_ELI_CRYPTO_UNKNOWN)
365 sc->sc_crypto = G_ELI_CRYPTO_HW;
366 mtx_unlock(&sc->sc_queue_mtx);
368 error = crypto_newsession(&wr->w_sid, &crie,
369 CRYPTOCAP_F_SOFTWARE);
370 mtx_lock(&sc->sc_queue_mtx);
371 if (sc->sc_crypto == G_ELI_CRYPTO_UNKNOWN)
372 sc->sc_crypto = G_ELI_CRYPTO_SW;
373 mtx_unlock(&sc->sc_queue_mtx);
377 panic("%s: invalid condition", __func__);
380 if ((sc->sc_flags & G_ELI_FLAG_FIRST_KEY) != 0)
381 g_eli_key_drop(sc, crie.cri_key);
387 g_eli_freesession(struct g_eli_worker *wr)
390 crypto_freesession(wr->w_sid);
394 g_eli_cancel(struct g_eli_softc *sc)
398 mtx_assert(&sc->sc_queue_mtx, MA_OWNED);
400 while ((bp = bioq_takefirst(&sc->sc_queue)) != NULL) {
401 KASSERT(bp->bio_pflags == G_ELI_NEW_BIO,
402 ("Not new bio when canceling (bp=%p).", bp));
403 g_io_deliver(bp, ENXIO);
408 g_eli_takefirst(struct g_eli_softc *sc)
412 mtx_assert(&sc->sc_queue_mtx, MA_OWNED);
414 if (!(sc->sc_flags & G_ELI_FLAG_SUSPEND))
415 return (bioq_takefirst(&sc->sc_queue));
417 * Device suspended, so we skip new I/O requests.
419 TAILQ_FOREACH(bp, &sc->sc_queue.queue, bio_queue) {
420 if (bp->bio_pflags != G_ELI_NEW_BIO)
424 bioq_remove(&sc->sc_queue, bp);
429 * This is the main function for kernel worker thread when we don't have
430 * hardware acceleration and we have to do cryptography in software.
431 * Dedicated thread is needed, so we don't slow down g_up/g_down GEOM
432 * threads with crypto work.
435 g_eli_worker(void *arg)
437 struct g_eli_softc *sc;
438 struct g_eli_worker *wr;
445 /* Before sched_bind() to a CPU, wait for all CPUs to go on-line. */
446 if (mp_ncpus > 1 && sc->sc_crypto == G_ELI_CRYPTO_SW &&
447 g_eli_threads == 0) {
449 tsleep(wr, 0, "geli:smp", hz / 4);
452 thread_lock(curthread);
453 sched_prio(curthread, PUSER);
454 if (sc->sc_crypto == G_ELI_CRYPTO_SW && g_eli_threads == 0)
455 sched_bind(curthread, wr->w_number);
456 thread_unlock(curthread);
458 G_ELI_DEBUG(1, "Thread %s started.", curthread->td_proc->p_comm);
461 mtx_lock(&sc->sc_queue_mtx);
463 bp = g_eli_takefirst(sc);
465 if (sc->sc_flags & G_ELI_FLAG_DESTROY) {
467 LIST_REMOVE(wr, w_next);
468 g_eli_freesession(wr);
470 G_ELI_DEBUG(1, "Thread %s exiting.",
471 curthread->td_proc->p_comm);
472 wakeup(&sc->sc_workers);
473 mtx_unlock(&sc->sc_queue_mtx);
476 while (sc->sc_flags & G_ELI_FLAG_SUSPEND) {
477 if (sc->sc_inflight > 0) {
478 G_ELI_DEBUG(0, "inflight=%d", sc->sc_inflight);
480 * We still have inflight BIOs, so
483 msleep(sc, &sc->sc_queue_mtx, PRIBIO,
488 * Suspend requested, mark the worker as
489 * suspended and go to sleep.
492 g_eli_freesession(wr);
493 wr->w_active = FALSE;
495 wakeup(&sc->sc_workers);
496 msleep(sc, &sc->sc_queue_mtx, PRIBIO,
499 !(sc->sc_flags & G_ELI_FLAG_SUSPEND)) {
500 error = g_eli_newsession(wr);
502 ("g_eli_newsession() failed on resume (error=%d)",
508 msleep(sc, &sc->sc_queue_mtx, PDROP, "geli:w", 0);
511 if (bp->bio_pflags == G_ELI_NEW_BIO)
512 atomic_add_int(&sc->sc_inflight, 1);
513 mtx_unlock(&sc->sc_queue_mtx);
514 if (bp->bio_pflags == G_ELI_NEW_BIO) {
516 if (sc->sc_flags & G_ELI_FLAG_AUTH) {
517 if (bp->bio_cmd == BIO_READ)
518 g_eli_auth_read(sc, bp);
520 g_eli_auth_run(wr, bp);
522 if (bp->bio_cmd == BIO_READ)
523 g_eli_crypto_read(sc, bp, 1);
525 g_eli_crypto_run(wr, bp);
528 if (sc->sc_flags & G_ELI_FLAG_AUTH)
529 g_eli_auth_run(wr, bp);
531 g_eli_crypto_run(wr, bp);
537 * Here we generate IV. It is unique for every sector.
540 g_eli_crypto_ivgen(struct g_eli_softc *sc, off_t offset, u_char *iv,
545 if ((sc->sc_flags & G_ELI_FLAG_NATIVE_BYTE_ORDER) != 0)
546 bcopy(&offset, off, sizeof(off));
548 le64enc(off, (uint64_t)offset);
550 switch (sc->sc_ealgo) {
552 bcopy(off, iv, sizeof(off));
553 bzero(iv + sizeof(off), size - sizeof(off));
557 u_char hash[SHA256_DIGEST_LENGTH];
560 /* Copy precalculated SHA256 context for IV-Key. */
561 bcopy(&sc->sc_ivctx, &ctx, sizeof(ctx));
562 SHA256_Update(&ctx, off, sizeof(off));
563 SHA256_Final(hash, &ctx);
564 bcopy(hash, iv, MIN(sizeof(hash), size));
571 g_eli_read_metadata(struct g_class *mp, struct g_provider *pp,
572 struct g_eli_metadata *md)
575 struct g_consumer *cp;
581 gp = g_new_geomf(mp, "eli:taste");
582 gp->start = g_eli_start;
583 gp->access = g_std_access;
585 * g_eli_read_metadata() is always called from the event thread.
586 * Our geom is created and destroyed in the same event, so there
587 * could be no orphan nor spoil event in the meantime.
589 gp->orphan = g_eli_orphan_spoil_assert;
590 gp->spoiled = g_eli_orphan_spoil_assert;
591 cp = g_new_consumer(gp);
592 error = g_attach(cp, pp);
595 error = g_access(cp, 1, 0, 0);
599 buf = g_read_data(cp, pp->mediasize - pp->sectorsize, pp->sectorsize,
604 eli_metadata_decode(buf, md);
608 if (cp->provider != NULL) {
610 g_access(cp, -1, 0, 0);
613 g_destroy_consumer(cp);
619 * The function is called when we had last close on provider and user requested
620 * to close it when this situation occur.
623 g_eli_last_close(struct g_eli_softc *sc)
626 struct g_provider *pp;
632 pp = LIST_FIRST(&gp->provider);
633 strlcpy(ppname, pp->name, sizeof(ppname));
634 error = g_eli_destroy(sc, TRUE);
635 KASSERT(error == 0, ("Cannot detach %s on last close (error=%d).",
637 G_ELI_DEBUG(0, "Detached %s on last close.", ppname);
641 g_eli_access(struct g_provider *pp, int dr, int dw, int de)
643 struct g_eli_softc *sc;
650 if (sc->sc_flags & G_ELI_FLAG_RO) {
651 /* Deny write attempts. */
654 /* Someone is opening us for write, we need to remember that. */
655 sc->sc_flags |= G_ELI_FLAG_WOPEN;
658 /* Is this the last close? */
659 if (pp->acr + dr > 0 || pp->acw + dw > 0 || pp->ace + de > 0)
663 * Automatically detach on last close if requested.
665 if ((sc->sc_flags & G_ELI_FLAG_RW_DETACH) ||
666 (sc->sc_flags & G_ELI_FLAG_WOPEN)) {
667 g_eli_last_close(sc);
673 g_eli_cpu_is_disabled(int cpu)
676 return (CPU_ISSET(cpu, &hlt_cpus_mask));
683 g_eli_create(struct gctl_req *req, struct g_class *mp, struct g_provider *bpp,
684 const struct g_eli_metadata *md, const u_char *mkey, int nkey)
686 struct g_eli_softc *sc;
687 struct g_eli_worker *wr;
689 struct g_provider *pp;
690 struct g_consumer *cp;
694 G_ELI_DEBUG(1, "Creating device %s%s.", bpp->name, G_ELI_SUFFIX);
696 gp = g_new_geomf(mp, "%s%s", bpp->name, G_ELI_SUFFIX);
697 sc = malloc(sizeof(*sc), M_ELI, M_WAITOK | M_ZERO);
698 gp->start = g_eli_start;
700 * Spoiling cannot happen actually, because we keep provider open for
701 * writing all the time or provider is read-only.
703 gp->spoiled = g_eli_orphan_spoil_assert;
704 gp->orphan = g_eli_orphan;
705 gp->dumpconf = g_eli_dumpconf;
707 * If detach-on-last-close feature is not enabled and we don't operate
708 * on read-only provider, we can simply use g_std_access().
710 if (md->md_flags & (G_ELI_FLAG_WO_DETACH | G_ELI_FLAG_RO))
711 gp->access = g_eli_access;
713 gp->access = g_std_access;
716 sc->sc_crypto = G_ELI_CRYPTO_UNKNOWN;
717 sc->sc_flags = md->md_flags;
718 /* Backward compatibility. */
719 if (md->md_version < 4)
720 sc->sc_flags |= G_ELI_FLAG_NATIVE_BYTE_ORDER;
721 if (md->md_version < 5)
722 sc->sc_flags |= G_ELI_FLAG_SINGLE_KEY;
723 if (md->md_version < 6 && (sc->sc_flags & G_ELI_FLAG_AUTH) != 0)
724 sc->sc_flags |= G_ELI_FLAG_FIRST_KEY;
725 sc->sc_ealgo = md->md_ealgo;
728 if (sc->sc_flags & G_ELI_FLAG_AUTH) {
729 sc->sc_akeylen = sizeof(sc->sc_akey) * 8;
730 sc->sc_aalgo = md->md_aalgo;
731 sc->sc_alen = g_eli_hashlen(sc->sc_aalgo);
733 sc->sc_data_per_sector = bpp->sectorsize - sc->sc_alen;
735 * Some hash functions (like SHA1 and RIPEMD160) generates hash
736 * which length is not multiple of 128 bits, but we want data
737 * length to be multiple of 128, so we can encrypt without
738 * padding. The line below rounds down data length to multiple
741 sc->sc_data_per_sector -= sc->sc_data_per_sector % 16;
743 sc->sc_bytes_per_sector =
744 (md->md_sectorsize - 1) / sc->sc_data_per_sector + 1;
745 sc->sc_bytes_per_sector *= bpp->sectorsize;
751 bioq_init(&sc->sc_queue);
752 mtx_init(&sc->sc_queue_mtx, "geli:queue", NULL, MTX_DEF);
753 mtx_init(&sc->sc_ekeys_lock, "geli:ekeys", NULL, MTX_DEF);
756 cp = g_new_consumer(gp);
757 error = g_attach(cp, bpp);
760 gctl_error(req, "Cannot attach to %s (error=%d).",
763 G_ELI_DEBUG(1, "Cannot attach to %s (error=%d).",
769 * Keep provider open all the time, so we can run critical tasks,
770 * like Master Keys deletion, without wondering if we can open
772 * We don't open provider for writing only when user requested read-only
775 if (sc->sc_flags & G_ELI_FLAG_RO)
776 error = g_access(cp, 1, 0, 1);
778 error = g_access(cp, 1, 1, 1);
781 gctl_error(req, "Cannot access %s (error=%d).",
784 G_ELI_DEBUG(1, "Cannot access %s (error=%d).",
790 sc->sc_sectorsize = md->md_sectorsize;
791 sc->sc_mediasize = bpp->mediasize;
792 if (!(sc->sc_flags & G_ELI_FLAG_ONETIME))
793 sc->sc_mediasize -= bpp->sectorsize;
794 if (!(sc->sc_flags & G_ELI_FLAG_AUTH))
795 sc->sc_mediasize -= (sc->sc_mediasize % sc->sc_sectorsize);
797 sc->sc_mediasize /= sc->sc_bytes_per_sector;
798 sc->sc_mediasize *= sc->sc_sectorsize;
802 * Remember the keys in our softc structure.
804 g_eli_mkey_propagate(sc, mkey);
805 sc->sc_ekeylen = md->md_keylen;
807 LIST_INIT(&sc->sc_workers);
809 threads = g_eli_threads;
812 else if (threads > mp_ncpus) {
813 /* There is really no need for too many worker threads. */
815 G_ELI_DEBUG(0, "Reducing number of threads to %u.", threads);
817 for (i = 0; i < threads; i++) {
818 if (g_eli_cpu_is_disabled(i)) {
819 G_ELI_DEBUG(1, "%s: CPU %u disabled, skipping.",
823 wr = malloc(sizeof(*wr), M_ELI, M_WAITOK | M_ZERO);
828 error = g_eli_newsession(wr);
832 gctl_error(req, "Cannot set up crypto session "
833 "for %s (error=%d).", bpp->name, error);
835 G_ELI_DEBUG(1, "Cannot set up crypto session "
836 "for %s (error=%d).", bpp->name, error);
841 error = kproc_create(g_eli_worker, wr, &wr->w_proc, 0, 0,
842 "g_eli[%u] %s", i, bpp->name);
844 g_eli_freesession(wr);
847 gctl_error(req, "Cannot create kernel thread "
848 "for %s (error=%d).", bpp->name, error);
850 G_ELI_DEBUG(1, "Cannot create kernel thread "
851 "for %s (error=%d).", bpp->name, error);
855 LIST_INSERT_HEAD(&sc->sc_workers, wr, w_next);
856 /* If we have hardware support, one thread is enough. */
857 if (sc->sc_crypto == G_ELI_CRYPTO_HW)
862 * Create decrypted provider.
864 pp = g_new_providerf(gp, "%s%s", bpp->name, G_ELI_SUFFIX);
865 pp->mediasize = sc->sc_mediasize;
866 pp->sectorsize = sc->sc_sectorsize;
868 g_error_provider(pp, 0);
870 G_ELI_DEBUG(0, "Device %s created.", pp->name);
871 G_ELI_DEBUG(0, "Encryption: %s %u", g_eli_algo2str(sc->sc_ealgo),
873 if (sc->sc_flags & G_ELI_FLAG_AUTH)
874 G_ELI_DEBUG(0, " Integrity: %s", g_eli_algo2str(sc->sc_aalgo));
875 G_ELI_DEBUG(0, " Crypto: %s",
876 sc->sc_crypto == G_ELI_CRYPTO_SW ? "software" : "hardware");
879 mtx_lock(&sc->sc_queue_mtx);
880 sc->sc_flags |= G_ELI_FLAG_DESTROY;
883 * Wait for kernel threads self destruction.
885 while (!LIST_EMPTY(&sc->sc_workers)) {
886 msleep(&sc->sc_workers, &sc->sc_queue_mtx, PRIBIO,
889 mtx_destroy(&sc->sc_queue_mtx);
890 if (cp->provider != NULL) {
892 g_access(cp, -1, -1, -1);
895 g_destroy_consumer(cp);
897 g_eli_key_destroy(sc);
898 bzero(sc, sizeof(*sc));
904 g_eli_destroy(struct g_eli_softc *sc, boolean_t force)
907 struct g_provider *pp;
915 pp = LIST_FIRST(&gp->provider);
916 if (pp != NULL && (pp->acr != 0 || pp->acw != 0 || pp->ace != 0)) {
918 G_ELI_DEBUG(1, "Device %s is still open, so it "
919 "cannot be definitely removed.", pp->name);
922 "Device %s is still open (r%dw%de%d).", pp->name,
923 pp->acr, pp->acw, pp->ace);
928 mtx_lock(&sc->sc_queue_mtx);
929 sc->sc_flags |= G_ELI_FLAG_DESTROY;
931 while (!LIST_EMPTY(&sc->sc_workers)) {
932 msleep(&sc->sc_workers, &sc->sc_queue_mtx, PRIBIO,
935 mtx_destroy(&sc->sc_queue_mtx);
937 g_eli_key_destroy(sc);
938 bzero(sc, sizeof(*sc));
941 if (pp == NULL || (pp->acr == 0 && pp->acw == 0 && pp->ace == 0))
942 G_ELI_DEBUG(0, "Device %s destroyed.", gp->name);
943 g_wither_geom_close(gp, ENXIO);
949 g_eli_destroy_geom(struct gctl_req *req __unused,
950 struct g_class *mp __unused, struct g_geom *gp)
952 struct g_eli_softc *sc;
955 return (g_eli_destroy(sc, FALSE));
959 g_eli_keyfiles_load(struct hmac_ctx *ctx, const char *provider)
961 u_char *keyfile, *data;
962 char *file, name[64];
967 snprintf(name, sizeof(name), "%s:geli_keyfile%d", provider, i);
968 keyfile = preload_search_by_type(name);
970 return (i); /* Return number of loaded keyfiles. */
971 data = preload_fetch_addr(keyfile);
973 G_ELI_DEBUG(0, "Cannot find key file data for %s.",
977 size = preload_fetch_size(keyfile);
979 G_ELI_DEBUG(0, "Cannot find key file size for %s.",
983 file = preload_search_info(keyfile, MODINFO_NAME);
985 G_ELI_DEBUG(0, "Cannot find key file name for %s.",
989 G_ELI_DEBUG(1, "Loaded keyfile %s for %s (type: %s).", file,
991 g_eli_crypto_hmac_update(ctx, data, size);
996 g_eli_keyfiles_clear(const char *provider)
998 u_char *keyfile, *data;
1003 for (i = 0; ; i++) {
1004 snprintf(name, sizeof(name), "%s:geli_keyfile%d", provider, i);
1005 keyfile = preload_search_by_type(name);
1006 if (keyfile == NULL)
1008 data = preload_fetch_addr(keyfile);
1009 size = preload_fetch_size(keyfile);
1010 if (data != NULL && size != 0)
1016 * Tasting is only made on boot.
1017 * We detect providers which should be attached before root is mounted.
1019 static struct g_geom *
1020 g_eli_taste(struct g_class *mp, struct g_provider *pp, int flags __unused)
1022 struct g_eli_metadata md;
1024 struct hmac_ctx ctx;
1025 char passphrase[256];
1026 u_char key[G_ELI_USERKEYLEN], mkey[G_ELI_DATAIVKEYLEN];
1027 u_int i, nkey, nkeyfiles, tries;
1030 g_trace(G_T_TOPOLOGY, "%s(%s, %s)", __func__, mp->name, pp->name);
1031 g_topology_assert();
1033 if (root_mounted() || g_eli_tries == 0)
1036 G_ELI_DEBUG(3, "Tasting %s.", pp->name);
1038 error = g_eli_read_metadata(mp, pp, &md);
1043 if (strcmp(md.md_magic, G_ELI_MAGIC) != 0)
1045 if (md.md_version > G_ELI_VERSION) {
1046 printf("geom_eli.ko module is too old to handle %s.\n",
1050 if (md.md_provsize != pp->mediasize)
1052 /* Should we attach it on boot? */
1053 if (!(md.md_flags & G_ELI_FLAG_BOOT))
1055 if (md.md_keys == 0x00) {
1056 G_ELI_DEBUG(0, "No valid keys on %s.", pp->name);
1059 if (md.md_iterations == -1) {
1060 /* If there is no passphrase, we try only once. */
1063 /* Ask for the passphrase no more than g_eli_tries times. */
1064 tries = g_eli_tries;
1067 for (i = 0; i < tries; i++) {
1068 g_eli_crypto_hmac_init(&ctx, NULL, 0);
1071 * Load all key files.
1073 nkeyfiles = g_eli_keyfiles_load(&ctx, pp->name);
1075 if (nkeyfiles == 0 && md.md_iterations == -1) {
1077 * No key files and no passphrase, something is
1078 * definitely wrong here.
1079 * geli(8) doesn't allow for such situation, so assume
1080 * that there was really no passphrase and in that case
1081 * key files are no properly defined in loader.conf.
1084 "Found no key files in loader.conf for %s.",
1089 /* Ask for the passphrase if defined. */
1090 if (md.md_iterations >= 0) {
1091 printf("Enter passphrase for %s: ", pp->name);
1092 gets(passphrase, sizeof(passphrase),
1093 g_eli_visible_passphrase);
1097 * Prepare Derived-Key from the user passphrase.
1099 if (md.md_iterations == 0) {
1100 g_eli_crypto_hmac_update(&ctx, md.md_salt,
1101 sizeof(md.md_salt));
1102 g_eli_crypto_hmac_update(&ctx, passphrase,
1103 strlen(passphrase));
1104 bzero(passphrase, sizeof(passphrase));
1105 } else if (md.md_iterations > 0) {
1106 u_char dkey[G_ELI_USERKEYLEN];
1108 pkcs5v2_genkey(dkey, sizeof(dkey), md.md_salt,
1109 sizeof(md.md_salt), passphrase, md.md_iterations);
1110 bzero(passphrase, sizeof(passphrase));
1111 g_eli_crypto_hmac_update(&ctx, dkey, sizeof(dkey));
1112 bzero(dkey, sizeof(dkey));
1115 g_eli_crypto_hmac_final(&ctx, key, 0);
1118 * Decrypt Master-Key.
1120 error = g_eli_mkey_decrypt(&md, key, mkey, &nkey);
1121 bzero(key, sizeof(key));
1123 if (i == tries - 1) {
1125 "Wrong key for %s. No tries left.",
1127 g_eli_keyfiles_clear(pp->name);
1130 G_ELI_DEBUG(0, "Wrong key for %s. Tries left: %u.",
1131 pp->name, tries - i - 1);
1134 } else if (error > 0) {
1135 G_ELI_DEBUG(0, "Cannot decrypt Master Key for %s (error=%d).",
1137 g_eli_keyfiles_clear(pp->name);
1140 G_ELI_DEBUG(1, "Using Master Key %u for %s.", nkey, pp->name);
1145 * We have correct key, let's attach provider.
1147 gp = g_eli_create(NULL, mp, pp, &md, mkey, nkey);
1148 bzero(mkey, sizeof(mkey));
1149 bzero(&md, sizeof(md));
1151 G_ELI_DEBUG(0, "Cannot create device %s%s.", pp->name,
1159 g_eli_dumpconf(struct sbuf *sb, const char *indent, struct g_geom *gp,
1160 struct g_consumer *cp, struct g_provider *pp)
1162 struct g_eli_softc *sc;
1164 g_topology_assert();
1168 if (pp != NULL || cp != NULL)
1169 return; /* Nothing here. */
1171 sbuf_printf(sb, "%s<KeysTotal>%ju</KeysTotal>", indent,
1172 (uintmax_t)sc->sc_ekeys_total);
1173 sbuf_printf(sb, "%s<KeysAllocated>%ju</KeysAllocated>", indent,
1174 (uintmax_t)sc->sc_ekeys_allocated);
1175 sbuf_printf(sb, "%s<Flags>", indent);
1176 if (sc->sc_flags == 0)
1177 sbuf_printf(sb, "NONE");
1181 #define ADD_FLAG(flag, name) do { \
1182 if (sc->sc_flags & (flag)) { \
1184 sbuf_printf(sb, ", "); \
1187 sbuf_printf(sb, name); \
1190 ADD_FLAG(G_ELI_FLAG_SUSPEND, "SUSPEND");
1191 ADD_FLAG(G_ELI_FLAG_SINGLE_KEY, "SINGLE-KEY");
1192 ADD_FLAG(G_ELI_FLAG_NATIVE_BYTE_ORDER, "NATIVE-BYTE-ORDER");
1193 ADD_FLAG(G_ELI_FLAG_ONETIME, "ONETIME");
1194 ADD_FLAG(G_ELI_FLAG_BOOT, "BOOT");
1195 ADD_FLAG(G_ELI_FLAG_WO_DETACH, "W-DETACH");
1196 ADD_FLAG(G_ELI_FLAG_RW_DETACH, "RW-DETACH");
1197 ADD_FLAG(G_ELI_FLAG_AUTH, "AUTH");
1198 ADD_FLAG(G_ELI_FLAG_WOPEN, "W-OPEN");
1199 ADD_FLAG(G_ELI_FLAG_DESTROY, "DESTROY");
1200 ADD_FLAG(G_ELI_FLAG_RO, "READ-ONLY");
1203 sbuf_printf(sb, "</Flags>\n");
1205 if (!(sc->sc_flags & G_ELI_FLAG_ONETIME)) {
1206 sbuf_printf(sb, "%s<UsedKey>%u</UsedKey>\n", indent,
1209 sbuf_printf(sb, "%s<Crypto>", indent);
1210 switch (sc->sc_crypto) {
1211 case G_ELI_CRYPTO_HW:
1212 sbuf_printf(sb, "hardware");
1214 case G_ELI_CRYPTO_SW:
1215 sbuf_printf(sb, "software");
1218 sbuf_printf(sb, "UNKNOWN");
1221 sbuf_printf(sb, "</Crypto>\n");
1222 if (sc->sc_flags & G_ELI_FLAG_AUTH) {
1224 "%s<AuthenticationAlgorithm>%s</AuthenticationAlgorithm>\n",
1225 indent, g_eli_algo2str(sc->sc_aalgo));
1227 sbuf_printf(sb, "%s<KeyLength>%u</KeyLength>\n", indent,
1229 sbuf_printf(sb, "%s<EncryptionAlgorithm>%s</EncryptionAlgorithm>\n", indent,
1230 g_eli_algo2str(sc->sc_ealgo));
1231 sbuf_printf(sb, "%s<State>%s</State>\n", indent,
1232 (sc->sc_flags & G_ELI_FLAG_SUSPEND) ? "SUSPENDED" : "ACTIVE");
1236 g_eli_shutdown_pre_sync(void *arg, int howto)
1239 struct g_geom *gp, *gp2;
1240 struct g_provider *pp;
1241 struct g_eli_softc *sc;
1247 LIST_FOREACH_SAFE(gp, &mp->geom, geom, gp2) {
1251 pp = LIST_FIRST(&gp->provider);
1252 KASSERT(pp != NULL, ("No provider? gp=%p (%s)", gp, gp->name));
1253 if (pp->acr + pp->acw + pp->ace == 0)
1254 error = g_eli_destroy(sc, TRUE);
1256 sc->sc_flags |= G_ELI_FLAG_RW_DETACH;
1257 gp->access = g_eli_access;
1260 g_topology_unlock();
1265 g_eli_init(struct g_class *mp)
1268 g_eli_pre_sync = EVENTHANDLER_REGISTER(shutdown_pre_sync,
1269 g_eli_shutdown_pre_sync, mp, SHUTDOWN_PRI_FIRST);
1270 if (g_eli_pre_sync == NULL)
1271 G_ELI_DEBUG(0, "Warning! Cannot register shutdown event.");
1275 g_eli_fini(struct g_class *mp)
1278 if (g_eli_pre_sync != NULL)
1279 EVENTHANDLER_DEREGISTER(shutdown_pre_sync, g_eli_pre_sync);
1282 DECLARE_GEOM_CLASS(g_eli_class, g_eli);
1283 MODULE_DEPEND(g_eli, crypto, 1, 1, 1);