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>
33 #include <sys/kernel.h>
34 #include <sys/linker.h>
35 #include <sys/module.h>
37 #include <sys/mutex.h>
40 #include <sys/sysctl.h>
41 #include <sys/malloc.h>
42 #include <sys/eventhandler.h>
43 #include <sys/kthread.h>
45 #include <sys/sched.h>
48 #include <sys/vnode.h>
52 #include <geom/geom.h>
53 #include <geom/eli/g_eli.h>
54 #include <geom/eli/pkcs5v2.h>
56 FEATURE(geom_eli, "GEOM crypto module");
58 MALLOC_DEFINE(M_ELI, "eli data", "GEOM_ELI Data");
60 SYSCTL_DECL(_kern_geom);
61 SYSCTL_NODE(_kern_geom, OID_AUTO, eli, CTLFLAG_RW, 0, "GEOM_ELI stuff");
62 static int g_eli_version = G_ELI_VERSION;
63 SYSCTL_INT(_kern_geom_eli, OID_AUTO, version, CTLFLAG_RD, &g_eli_version, 0,
66 TUNABLE_INT("kern.geom.eli.debug", &g_eli_debug);
67 SYSCTL_INT(_kern_geom_eli, OID_AUTO, debug, CTLFLAG_RW, &g_eli_debug, 0,
69 static u_int g_eli_tries = 3;
70 TUNABLE_INT("kern.geom.eli.tries", &g_eli_tries);
71 SYSCTL_UINT(_kern_geom_eli, OID_AUTO, tries, CTLFLAG_RW, &g_eli_tries, 0,
72 "Number of tries for entering the passphrase");
73 static u_int g_eli_visible_passphrase = GETS_NOECHO;
74 TUNABLE_INT("kern.geom.eli.visible_passphrase", &g_eli_visible_passphrase);
75 SYSCTL_UINT(_kern_geom_eli, OID_AUTO, visible_passphrase, CTLFLAG_RW,
76 &g_eli_visible_passphrase, 0,
77 "Visibility of passphrase prompt (0 = invisible, 1 = visible, 2 = asterisk)");
78 u_int g_eli_overwrites = G_ELI_OVERWRITES;
79 TUNABLE_INT("kern.geom.eli.overwrites", &g_eli_overwrites);
80 SYSCTL_UINT(_kern_geom_eli, OID_AUTO, overwrites, CTLFLAG_RW, &g_eli_overwrites,
81 0, "Number of times on-disk keys should be overwritten when destroying them");
82 static u_int g_eli_threads = 0;
83 TUNABLE_INT("kern.geom.eli.threads", &g_eli_threads);
84 SYSCTL_UINT(_kern_geom_eli, OID_AUTO, threads, CTLFLAG_RW, &g_eli_threads, 0,
85 "Number of threads doing crypto work");
86 u_int g_eli_batch = 0;
87 TUNABLE_INT("kern.geom.eli.batch", &g_eli_batch);
88 SYSCTL_UINT(_kern_geom_eli, OID_AUTO, batch, CTLFLAG_RW, &g_eli_batch, 0,
89 "Use crypto operations batching");
91 static eventhandler_tag g_eli_pre_sync = NULL;
93 static int g_eli_destroy_geom(struct gctl_req *req, struct g_class *mp,
95 static void g_eli_init(struct g_class *mp);
96 static void g_eli_fini(struct g_class *mp);
98 static g_taste_t g_eli_taste;
99 static g_dumpconf_t g_eli_dumpconf;
101 struct g_class g_eli_class = {
102 .name = G_ELI_CLASS_NAME,
103 .version = G_VERSION,
104 .ctlreq = g_eli_config,
105 .taste = g_eli_taste,
106 .destroy_geom = g_eli_destroy_geom,
115 * 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
117 * g_eli_start -> g_eli_crypto_run -> g_eli_crypto_write_done -> g_io_request -> g_eli_write_done -> g_io_deliver
122 * EAGAIN from crypto(9) means, that we were probably balanced to another crypto
123 * accelerator or something like this.
124 * The function updates the SID and rerun the operation.
127 g_eli_crypto_rerun(struct cryptop *crp)
129 struct g_eli_softc *sc;
130 struct g_eli_worker *wr;
134 bp = (struct bio *)crp->crp_opaque;
135 sc = bp->bio_to->geom->softc;
136 LIST_FOREACH(wr, &sc->sc_workers, w_next) {
137 if (wr->w_number == bp->bio_pflags)
140 KASSERT(wr != NULL, ("Invalid worker (%u).", bp->bio_pflags));
141 G_ELI_DEBUG(1, "Rerunning crypto %s request (sid: %ju -> %ju).",
142 bp->bio_cmd == BIO_READ ? "READ" : "WRITE", (uintmax_t)wr->w_sid,
143 (uintmax_t)crp->crp_sid);
144 wr->w_sid = crp->crp_sid;
146 error = crypto_dispatch(crp);
149 G_ELI_DEBUG(1, "%s: crypto_dispatch() returned %d.", __func__, error);
150 crp->crp_etype = error;
155 * The function is called afer reading encrypted data from the provider.
157 * 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
160 g_eli_read_done(struct bio *bp)
162 struct g_eli_softc *sc;
165 G_ELI_LOGREQ(2, bp, "Request done.");
166 pbp = bp->bio_parent;
167 if (pbp->bio_error == 0)
168 pbp->bio_error = bp->bio_error;
171 * Do we have all sectors already?
174 if (pbp->bio_inbed < pbp->bio_children)
176 sc = pbp->bio_to->geom->softc;
177 if (pbp->bio_error != 0) {
178 G_ELI_LOGREQ(0, pbp, "%s() failed", __func__);
179 pbp->bio_completed = 0;
180 if (pbp->bio_driver2 != NULL) {
181 free(pbp->bio_driver2, M_ELI);
182 pbp->bio_driver2 = NULL;
184 g_io_deliver(pbp, pbp->bio_error);
185 atomic_subtract_int(&sc->sc_inflight, 1);
188 mtx_lock(&sc->sc_queue_mtx);
189 bioq_insert_tail(&sc->sc_queue, pbp);
190 mtx_unlock(&sc->sc_queue_mtx);
195 * The function is called after we encrypt and write data.
197 * g_eli_start -> g_eli_crypto_run -> g_eli_crypto_write_done -> g_io_request -> G_ELI_WRITE_DONE -> g_io_deliver
200 g_eli_write_done(struct bio *bp)
202 struct g_eli_softc *sc;
205 G_ELI_LOGREQ(2, bp, "Request done.");
206 pbp = bp->bio_parent;
207 if (pbp->bio_error == 0) {
208 if (bp->bio_error != 0)
209 pbp->bio_error = bp->bio_error;
213 * Do we have all sectors already?
216 if (pbp->bio_inbed < pbp->bio_children)
218 free(pbp->bio_driver2, M_ELI);
219 pbp->bio_driver2 = NULL;
220 if (pbp->bio_error != 0) {
221 G_ELI_LOGREQ(0, pbp, "Crypto WRITE request failed (error=%d).",
223 pbp->bio_completed = 0;
226 * Write is finished, send it up.
228 pbp->bio_completed = pbp->bio_length;
229 sc = pbp->bio_to->geom->softc;
230 g_io_deliver(pbp, pbp->bio_error);
231 atomic_subtract_int(&sc->sc_inflight, 1);
235 * This function should never be called, but GEOM made as it set ->orphan()
236 * method for every geom.
239 g_eli_orphan_spoil_assert(struct g_consumer *cp)
242 panic("Function %s() called for %s.", __func__, cp->geom->name);
246 g_eli_orphan(struct g_consumer *cp)
248 struct g_eli_softc *sc;
251 sc = cp->geom->softc;
254 g_eli_destroy(sc, TRUE);
259 * 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
261 * G_ELI_START -> g_eli_crypto_run -> g_eli_crypto_write_done -> g_io_request -> g_eli_write_done -> g_io_deliver
264 g_eli_start(struct bio *bp)
266 struct g_eli_softc *sc;
267 struct g_consumer *cp;
270 sc = bp->bio_to->geom->softc;
272 ("Provider's error should be set (error=%d)(device=%s).",
273 bp->bio_to->error, bp->bio_to->name));
274 G_ELI_LOGREQ(2, bp, "Request received.");
276 switch (bp->bio_cmd) {
284 * We could eventually support BIO_DELETE request.
285 * It could be done by overwritting requested sector with
286 * random data g_eli_overwrites number of times.
289 g_io_deliver(bp, EOPNOTSUPP);
292 cbp = g_clone_bio(bp);
294 g_io_deliver(bp, ENOMEM);
297 bp->bio_driver1 = cbp;
298 bp->bio_pflags = G_ELI_NEW_BIO;
299 switch (bp->bio_cmd) {
301 if (!(sc->sc_flags & G_ELI_FLAG_AUTH)) {
302 g_eli_crypto_read(sc, bp, 0);
307 mtx_lock(&sc->sc_queue_mtx);
308 bioq_insert_tail(&sc->sc_queue, bp);
309 mtx_unlock(&sc->sc_queue_mtx);
314 cbp->bio_done = g_std_done;
315 cp = LIST_FIRST(&sc->sc_geom->consumer);
316 cbp->bio_to = cp->provider;
317 G_ELI_LOGREQ(2, cbp, "Sending request.");
318 g_io_request(cbp, cp);
324 g_eli_newsession(struct g_eli_worker *wr)
326 struct g_eli_softc *sc;
327 struct cryptoini crie, cria;
332 bzero(&crie, sizeof(crie));
333 crie.cri_alg = sc->sc_ealgo;
334 crie.cri_klen = sc->sc_ekeylen;
335 if (sc->sc_ealgo == CRYPTO_AES_XTS)
337 if ((sc->sc_flags & G_ELI_FLAG_FIRST_KEY) != 0) {
338 crie.cri_key = g_eli_key_hold(sc, 0,
339 LIST_FIRST(&sc->sc_geom->consumer)->provider->sectorsize);
341 crie.cri_key = sc->sc_ekey;
343 if (sc->sc_flags & G_ELI_FLAG_AUTH) {
344 bzero(&cria, sizeof(cria));
345 cria.cri_alg = sc->sc_aalgo;
346 cria.cri_klen = sc->sc_akeylen;
347 cria.cri_key = sc->sc_akey;
348 crie.cri_next = &cria;
351 switch (sc->sc_crypto) {
352 case G_ELI_CRYPTO_SW:
353 error = crypto_newsession(&wr->w_sid, &crie,
354 CRYPTOCAP_F_SOFTWARE);
356 case G_ELI_CRYPTO_HW:
357 error = crypto_newsession(&wr->w_sid, &crie,
358 CRYPTOCAP_F_HARDWARE);
360 case G_ELI_CRYPTO_UNKNOWN:
361 error = crypto_newsession(&wr->w_sid, &crie,
362 CRYPTOCAP_F_HARDWARE);
364 mtx_lock(&sc->sc_queue_mtx);
365 if (sc->sc_crypto == G_ELI_CRYPTO_UNKNOWN)
366 sc->sc_crypto = G_ELI_CRYPTO_HW;
367 mtx_unlock(&sc->sc_queue_mtx);
369 error = crypto_newsession(&wr->w_sid, &crie,
370 CRYPTOCAP_F_SOFTWARE);
371 mtx_lock(&sc->sc_queue_mtx);
372 if (sc->sc_crypto == G_ELI_CRYPTO_UNKNOWN)
373 sc->sc_crypto = G_ELI_CRYPTO_SW;
374 mtx_unlock(&sc->sc_queue_mtx);
378 panic("%s: invalid condition", __func__);
381 if ((sc->sc_flags & G_ELI_FLAG_FIRST_KEY) != 0)
382 g_eli_key_drop(sc, crie.cri_key);
388 g_eli_freesession(struct g_eli_worker *wr)
391 crypto_freesession(wr->w_sid);
395 g_eli_cancel(struct g_eli_softc *sc)
399 mtx_assert(&sc->sc_queue_mtx, MA_OWNED);
401 while ((bp = bioq_takefirst(&sc->sc_queue)) != NULL) {
402 KASSERT(bp->bio_pflags == G_ELI_NEW_BIO,
403 ("Not new bio when canceling (bp=%p).", bp));
404 g_io_deliver(bp, ENXIO);
409 g_eli_takefirst(struct g_eli_softc *sc)
413 mtx_assert(&sc->sc_queue_mtx, MA_OWNED);
415 if (!(sc->sc_flags & G_ELI_FLAG_SUSPEND))
416 return (bioq_takefirst(&sc->sc_queue));
418 * Device suspended, so we skip new I/O requests.
420 TAILQ_FOREACH(bp, &sc->sc_queue.queue, bio_queue) {
421 if (bp->bio_pflags != G_ELI_NEW_BIO)
425 bioq_remove(&sc->sc_queue, bp);
430 * This is the main function for kernel worker thread when we don't have
431 * hardware acceleration and we have to do cryptography in software.
432 * Dedicated thread is needed, so we don't slow down g_up/g_down GEOM
433 * threads with crypto work.
436 g_eli_worker(void *arg)
438 struct g_eli_softc *sc;
439 struct g_eli_worker *wr;
446 /* Before sched_bind() to a CPU, wait for all CPUs to go on-line. */
447 if (sc->sc_cpubind) {
449 tsleep(wr, 0, "geli:smp", hz / 4);
452 thread_lock(curthread);
453 sched_prio(curthread, PUSER);
455 sched_bind(curthread, wr->w_number % mp_ncpus);
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(void *arg, int flags __unused)
631 strlcpy(gpname, gp->name, sizeof(gpname));
632 error = g_eli_destroy(gp->softc, TRUE);
633 KASSERT(error == 0, ("Cannot detach %s on last close (error=%d).",
635 G_ELI_DEBUG(0, "Detached %s on last close.", gpname);
639 g_eli_access(struct g_provider *pp, int dr, int dw, int de)
641 struct g_eli_softc *sc;
648 if (sc->sc_flags & G_ELI_FLAG_RO) {
649 /* Deny write attempts. */
652 /* Someone is opening us for write, we need to remember that. */
653 sc->sc_flags |= G_ELI_FLAG_WOPEN;
656 /* Is this the last close? */
657 if (pp->acr + dr > 0 || pp->acw + dw > 0 || pp->ace + de > 0)
661 * Automatically detach on last close if requested.
663 if ((sc->sc_flags & G_ELI_FLAG_RW_DETACH) ||
664 (sc->sc_flags & G_ELI_FLAG_WOPEN)) {
665 g_post_event(g_eli_last_close, gp, M_WAITOK, NULL);
671 g_eli_cpu_is_disabled(int cpu)
674 return (CPU_ISSET(cpu, &hlt_cpus_mask));
681 g_eli_create(struct gctl_req *req, struct g_class *mp, struct g_provider *bpp,
682 const struct g_eli_metadata *md, const u_char *mkey, int nkey)
684 struct g_eli_softc *sc;
685 struct g_eli_worker *wr;
687 struct g_provider *pp;
688 struct g_consumer *cp;
692 G_ELI_DEBUG(1, "Creating device %s%s.", bpp->name, G_ELI_SUFFIX);
694 gp = g_new_geomf(mp, "%s%s", bpp->name, G_ELI_SUFFIX);
695 sc = malloc(sizeof(*sc), M_ELI, M_WAITOK | M_ZERO);
696 gp->start = g_eli_start;
698 * Spoiling cannot happen actually, because we keep provider open for
699 * writing all the time or provider is read-only.
701 gp->spoiled = g_eli_orphan_spoil_assert;
702 gp->orphan = g_eli_orphan;
703 gp->dumpconf = g_eli_dumpconf;
705 * If detach-on-last-close feature is not enabled and we don't operate
706 * on read-only provider, we can simply use g_std_access().
708 if (md->md_flags & (G_ELI_FLAG_WO_DETACH | G_ELI_FLAG_RO))
709 gp->access = g_eli_access;
711 gp->access = g_std_access;
714 sc->sc_crypto = G_ELI_CRYPTO_UNKNOWN;
715 sc->sc_flags = md->md_flags;
716 /* Backward compatibility. */
717 if (md->md_version < 4)
718 sc->sc_flags |= G_ELI_FLAG_NATIVE_BYTE_ORDER;
719 if (md->md_version < 5)
720 sc->sc_flags |= G_ELI_FLAG_SINGLE_KEY;
721 if (md->md_version < 6 && (sc->sc_flags & G_ELI_FLAG_AUTH) != 0)
722 sc->sc_flags |= G_ELI_FLAG_FIRST_KEY;
723 sc->sc_ealgo = md->md_ealgo;
726 if (sc->sc_flags & G_ELI_FLAG_AUTH) {
727 sc->sc_akeylen = sizeof(sc->sc_akey) * 8;
728 sc->sc_aalgo = md->md_aalgo;
729 sc->sc_alen = g_eli_hashlen(sc->sc_aalgo);
731 sc->sc_data_per_sector = bpp->sectorsize - sc->sc_alen;
733 * Some hash functions (like SHA1 and RIPEMD160) generates hash
734 * which length is not multiple of 128 bits, but we want data
735 * length to be multiple of 128, so we can encrypt without
736 * padding. The line below rounds down data length to multiple
739 sc->sc_data_per_sector -= sc->sc_data_per_sector % 16;
741 sc->sc_bytes_per_sector =
742 (md->md_sectorsize - 1) / sc->sc_data_per_sector + 1;
743 sc->sc_bytes_per_sector *= bpp->sectorsize;
749 bioq_init(&sc->sc_queue);
750 mtx_init(&sc->sc_queue_mtx, "geli:queue", NULL, MTX_DEF);
751 mtx_init(&sc->sc_ekeys_lock, "geli:ekeys", NULL, MTX_DEF);
754 cp = g_new_consumer(gp);
755 error = g_attach(cp, bpp);
758 gctl_error(req, "Cannot attach to %s (error=%d).",
761 G_ELI_DEBUG(1, "Cannot attach to %s (error=%d).",
767 * Keep provider open all the time, so we can run critical tasks,
768 * like Master Keys deletion, without wondering if we can open
770 * We don't open provider for writing only when user requested read-only
773 if (sc->sc_flags & G_ELI_FLAG_RO)
774 error = g_access(cp, 1, 0, 1);
776 error = g_access(cp, 1, 1, 1);
779 gctl_error(req, "Cannot access %s (error=%d).",
782 G_ELI_DEBUG(1, "Cannot access %s (error=%d).",
788 sc->sc_sectorsize = md->md_sectorsize;
789 sc->sc_mediasize = bpp->mediasize;
790 if (!(sc->sc_flags & G_ELI_FLAG_ONETIME))
791 sc->sc_mediasize -= bpp->sectorsize;
792 if (!(sc->sc_flags & G_ELI_FLAG_AUTH))
793 sc->sc_mediasize -= (sc->sc_mediasize % sc->sc_sectorsize);
795 sc->sc_mediasize /= sc->sc_bytes_per_sector;
796 sc->sc_mediasize *= sc->sc_sectorsize;
800 * Remember the keys in our softc structure.
802 g_eli_mkey_propagate(sc, mkey);
803 sc->sc_ekeylen = md->md_keylen;
805 LIST_INIT(&sc->sc_workers);
807 threads = g_eli_threads;
810 sc->sc_cpubind = (mp_ncpus > 1 && threads == mp_ncpus);
811 for (i = 0; i < threads; i++) {
812 if (g_eli_cpu_is_disabled(i)) {
813 G_ELI_DEBUG(1, "%s: CPU %u disabled, skipping.",
817 wr = malloc(sizeof(*wr), M_ELI, M_WAITOK | M_ZERO);
822 error = g_eli_newsession(wr);
826 gctl_error(req, "Cannot set up crypto session "
827 "for %s (error=%d).", bpp->name, error);
829 G_ELI_DEBUG(1, "Cannot set up crypto session "
830 "for %s (error=%d).", bpp->name, error);
835 error = kproc_create(g_eli_worker, wr, &wr->w_proc, 0, 0,
836 "g_eli[%u] %s", i, bpp->name);
838 g_eli_freesession(wr);
841 gctl_error(req, "Cannot create kernel thread "
842 "for %s (error=%d).", bpp->name, error);
844 G_ELI_DEBUG(1, "Cannot create kernel thread "
845 "for %s (error=%d).", bpp->name, error);
849 LIST_INSERT_HEAD(&sc->sc_workers, wr, w_next);
853 * Create decrypted provider.
855 pp = g_new_providerf(gp, "%s%s", bpp->name, G_ELI_SUFFIX);
856 pp->mediasize = sc->sc_mediasize;
857 pp->sectorsize = sc->sc_sectorsize;
859 g_error_provider(pp, 0);
861 G_ELI_DEBUG(0, "Device %s created.", pp->name);
862 G_ELI_DEBUG(0, "Encryption: %s %u", g_eli_algo2str(sc->sc_ealgo),
864 if (sc->sc_flags & G_ELI_FLAG_AUTH)
865 G_ELI_DEBUG(0, " Integrity: %s", g_eli_algo2str(sc->sc_aalgo));
866 G_ELI_DEBUG(0, " Crypto: %s",
867 sc->sc_crypto == G_ELI_CRYPTO_SW ? "software" : "hardware");
870 mtx_lock(&sc->sc_queue_mtx);
871 sc->sc_flags |= G_ELI_FLAG_DESTROY;
874 * Wait for kernel threads self destruction.
876 while (!LIST_EMPTY(&sc->sc_workers)) {
877 msleep(&sc->sc_workers, &sc->sc_queue_mtx, PRIBIO,
880 mtx_destroy(&sc->sc_queue_mtx);
881 if (cp->provider != NULL) {
883 g_access(cp, -1, -1, -1);
886 g_destroy_consumer(cp);
888 g_eli_key_destroy(sc);
889 bzero(sc, sizeof(*sc));
895 g_eli_destroy(struct g_eli_softc *sc, boolean_t force)
898 struct g_provider *pp;
906 pp = LIST_FIRST(&gp->provider);
907 if (pp != NULL && (pp->acr != 0 || pp->acw != 0 || pp->ace != 0)) {
909 G_ELI_DEBUG(1, "Device %s is still open, so it "
910 "cannot be definitely removed.", pp->name);
911 sc->sc_flags |= G_ELI_FLAG_RW_DETACH;
912 gp->access = g_eli_access;
913 g_wither_provider(pp, ENXIO);
917 "Device %s is still open (r%dw%de%d).", pp->name,
918 pp->acr, pp->acw, pp->ace);
923 mtx_lock(&sc->sc_queue_mtx);
924 sc->sc_flags |= G_ELI_FLAG_DESTROY;
926 while (!LIST_EMPTY(&sc->sc_workers)) {
927 msleep(&sc->sc_workers, &sc->sc_queue_mtx, PRIBIO,
930 mtx_destroy(&sc->sc_queue_mtx);
932 g_eli_key_destroy(sc);
933 bzero(sc, sizeof(*sc));
936 if (pp == NULL || (pp->acr == 0 && pp->acw == 0 && pp->ace == 0))
937 G_ELI_DEBUG(0, "Device %s destroyed.", gp->name);
938 g_wither_geom_close(gp, ENXIO);
944 g_eli_destroy_geom(struct gctl_req *req __unused,
945 struct g_class *mp __unused, struct g_geom *gp)
947 struct g_eli_softc *sc;
950 return (g_eli_destroy(sc, FALSE));
954 g_eli_keyfiles_load(struct hmac_ctx *ctx, const char *provider)
956 u_char *keyfile, *data;
957 char *file, name[64];
962 snprintf(name, sizeof(name), "%s:geli_keyfile%d", provider, i);
963 keyfile = preload_search_by_type(name);
965 return (i); /* Return number of loaded keyfiles. */
966 data = preload_fetch_addr(keyfile);
968 G_ELI_DEBUG(0, "Cannot find key file data for %s.",
972 size = preload_fetch_size(keyfile);
974 G_ELI_DEBUG(0, "Cannot find key file size for %s.",
978 file = preload_search_info(keyfile, MODINFO_NAME);
980 G_ELI_DEBUG(0, "Cannot find key file name for %s.",
984 G_ELI_DEBUG(1, "Loaded keyfile %s for %s (type: %s).", file,
986 g_eli_crypto_hmac_update(ctx, data, size);
991 g_eli_keyfiles_clear(const char *provider)
993 u_char *keyfile, *data;
999 snprintf(name, sizeof(name), "%s:geli_keyfile%d", provider, i);
1000 keyfile = preload_search_by_type(name);
1001 if (keyfile == NULL)
1003 data = preload_fetch_addr(keyfile);
1004 size = preload_fetch_size(keyfile);
1005 if (data != NULL && size != 0)
1011 * Tasting is only made on boot.
1012 * We detect providers which should be attached before root is mounted.
1014 static struct g_geom *
1015 g_eli_taste(struct g_class *mp, struct g_provider *pp, int flags __unused)
1017 struct g_eli_metadata md;
1019 struct hmac_ctx ctx;
1020 char passphrase[256];
1021 u_char key[G_ELI_USERKEYLEN], mkey[G_ELI_DATAIVKEYLEN];
1022 u_int i, nkey, nkeyfiles, tries;
1025 g_trace(G_T_TOPOLOGY, "%s(%s, %s)", __func__, mp->name, pp->name);
1026 g_topology_assert();
1028 if (root_mounted() || g_eli_tries == 0)
1031 G_ELI_DEBUG(3, "Tasting %s.", pp->name);
1033 error = g_eli_read_metadata(mp, pp, &md);
1038 if (strcmp(md.md_magic, G_ELI_MAGIC) != 0)
1040 if (md.md_version > G_ELI_VERSION) {
1041 printf("geom_eli.ko module is too old to handle %s.\n",
1045 if (md.md_provsize != pp->mediasize)
1047 /* Should we attach it on boot? */
1048 if (!(md.md_flags & G_ELI_FLAG_BOOT))
1050 if (md.md_keys == 0x00) {
1051 G_ELI_DEBUG(0, "No valid keys on %s.", pp->name);
1054 if (md.md_iterations == -1) {
1055 /* If there is no passphrase, we try only once. */
1058 /* Ask for the passphrase no more than g_eli_tries times. */
1059 tries = g_eli_tries;
1062 for (i = 0; i < tries; i++) {
1063 g_eli_crypto_hmac_init(&ctx, NULL, 0);
1066 * Load all key files.
1068 nkeyfiles = g_eli_keyfiles_load(&ctx, pp->name);
1070 if (nkeyfiles == 0 && md.md_iterations == -1) {
1072 * No key files and no passphrase, something is
1073 * definitely wrong here.
1074 * geli(8) doesn't allow for such situation, so assume
1075 * that there was really no passphrase and in that case
1076 * key files are no properly defined in loader.conf.
1079 "Found no key files in loader.conf for %s.",
1084 /* Ask for the passphrase if defined. */
1085 if (md.md_iterations >= 0) {
1086 printf("Enter passphrase for %s: ", pp->name);
1087 cngets(passphrase, sizeof(passphrase),
1088 g_eli_visible_passphrase);
1092 * Prepare Derived-Key from the user passphrase.
1094 if (md.md_iterations == 0) {
1095 g_eli_crypto_hmac_update(&ctx, md.md_salt,
1096 sizeof(md.md_salt));
1097 g_eli_crypto_hmac_update(&ctx, passphrase,
1098 strlen(passphrase));
1099 bzero(passphrase, sizeof(passphrase));
1100 } else if (md.md_iterations > 0) {
1101 u_char dkey[G_ELI_USERKEYLEN];
1103 pkcs5v2_genkey(dkey, sizeof(dkey), md.md_salt,
1104 sizeof(md.md_salt), passphrase, md.md_iterations);
1105 bzero(passphrase, sizeof(passphrase));
1106 g_eli_crypto_hmac_update(&ctx, dkey, sizeof(dkey));
1107 bzero(dkey, sizeof(dkey));
1110 g_eli_crypto_hmac_final(&ctx, key, 0);
1113 * Decrypt Master-Key.
1115 error = g_eli_mkey_decrypt(&md, key, mkey, &nkey);
1116 bzero(key, sizeof(key));
1118 if (i == tries - 1) {
1120 "Wrong key for %s. No tries left.",
1122 g_eli_keyfiles_clear(pp->name);
1125 G_ELI_DEBUG(0, "Wrong key for %s. Tries left: %u.",
1126 pp->name, tries - i - 1);
1129 } else if (error > 0) {
1130 G_ELI_DEBUG(0, "Cannot decrypt Master Key for %s (error=%d).",
1132 g_eli_keyfiles_clear(pp->name);
1135 g_eli_keyfiles_clear(pp->name);
1136 G_ELI_DEBUG(1, "Using Master Key %u for %s.", nkey, pp->name);
1141 * We have correct key, let's attach provider.
1143 gp = g_eli_create(NULL, mp, pp, &md, mkey, nkey);
1144 bzero(mkey, sizeof(mkey));
1145 bzero(&md, sizeof(md));
1147 G_ELI_DEBUG(0, "Cannot create device %s%s.", pp->name,
1155 g_eli_dumpconf(struct sbuf *sb, const char *indent, struct g_geom *gp,
1156 struct g_consumer *cp, struct g_provider *pp)
1158 struct g_eli_softc *sc;
1160 g_topology_assert();
1164 if (pp != NULL || cp != NULL)
1165 return; /* Nothing here. */
1167 sbuf_printf(sb, "%s<KeysTotal>%ju</KeysTotal>\n", indent,
1168 (uintmax_t)sc->sc_ekeys_total);
1169 sbuf_printf(sb, "%s<KeysAllocated>%ju</KeysAllocated>\n", indent,
1170 (uintmax_t)sc->sc_ekeys_allocated);
1171 sbuf_printf(sb, "%s<Flags>", indent);
1172 if (sc->sc_flags == 0)
1173 sbuf_printf(sb, "NONE");
1177 #define ADD_FLAG(flag, name) do { \
1178 if (sc->sc_flags & (flag)) { \
1180 sbuf_printf(sb, ", "); \
1183 sbuf_printf(sb, name); \
1186 ADD_FLAG(G_ELI_FLAG_SUSPEND, "SUSPEND");
1187 ADD_FLAG(G_ELI_FLAG_SINGLE_KEY, "SINGLE-KEY");
1188 ADD_FLAG(G_ELI_FLAG_NATIVE_BYTE_ORDER, "NATIVE-BYTE-ORDER");
1189 ADD_FLAG(G_ELI_FLAG_ONETIME, "ONETIME");
1190 ADD_FLAG(G_ELI_FLAG_BOOT, "BOOT");
1191 ADD_FLAG(G_ELI_FLAG_WO_DETACH, "W-DETACH");
1192 ADD_FLAG(G_ELI_FLAG_RW_DETACH, "RW-DETACH");
1193 ADD_FLAG(G_ELI_FLAG_AUTH, "AUTH");
1194 ADD_FLAG(G_ELI_FLAG_WOPEN, "W-OPEN");
1195 ADD_FLAG(G_ELI_FLAG_DESTROY, "DESTROY");
1196 ADD_FLAG(G_ELI_FLAG_RO, "READ-ONLY");
1199 sbuf_printf(sb, "</Flags>\n");
1201 if (!(sc->sc_flags & G_ELI_FLAG_ONETIME)) {
1202 sbuf_printf(sb, "%s<UsedKey>%u</UsedKey>\n", indent,
1205 sbuf_printf(sb, "%s<Crypto>", indent);
1206 switch (sc->sc_crypto) {
1207 case G_ELI_CRYPTO_HW:
1208 sbuf_printf(sb, "hardware");
1210 case G_ELI_CRYPTO_SW:
1211 sbuf_printf(sb, "software");
1214 sbuf_printf(sb, "UNKNOWN");
1217 sbuf_printf(sb, "</Crypto>\n");
1218 if (sc->sc_flags & G_ELI_FLAG_AUTH) {
1220 "%s<AuthenticationAlgorithm>%s</AuthenticationAlgorithm>\n",
1221 indent, g_eli_algo2str(sc->sc_aalgo));
1223 sbuf_printf(sb, "%s<KeyLength>%u</KeyLength>\n", indent,
1225 sbuf_printf(sb, "%s<EncryptionAlgorithm>%s</EncryptionAlgorithm>\n", indent,
1226 g_eli_algo2str(sc->sc_ealgo));
1227 sbuf_printf(sb, "%s<State>%s</State>\n", indent,
1228 (sc->sc_flags & G_ELI_FLAG_SUSPEND) ? "SUSPENDED" : "ACTIVE");
1232 g_eli_shutdown_pre_sync(void *arg, int howto)
1235 struct g_geom *gp, *gp2;
1236 struct g_provider *pp;
1237 struct g_eli_softc *sc;
1243 LIST_FOREACH_SAFE(gp, &mp->geom, geom, gp2) {
1247 pp = LIST_FIRST(&gp->provider);
1248 KASSERT(pp != NULL, ("No provider? gp=%p (%s)", gp, gp->name));
1249 if (pp->acr + pp->acw + pp->ace == 0)
1250 error = g_eli_destroy(sc, TRUE);
1252 sc->sc_flags |= G_ELI_FLAG_RW_DETACH;
1253 gp->access = g_eli_access;
1256 g_topology_unlock();
1261 g_eli_init(struct g_class *mp)
1264 g_eli_pre_sync = EVENTHANDLER_REGISTER(shutdown_pre_sync,
1265 g_eli_shutdown_pre_sync, mp, SHUTDOWN_PRI_FIRST);
1266 if (g_eli_pre_sync == NULL)
1267 G_ELI_DEBUG(0, "Warning! Cannot register shutdown event.");
1271 g_eli_fini(struct g_class *mp)
1274 if (g_eli_pre_sync != NULL)
1275 EVENTHANDLER_DEREGISTER(shutdown_pre_sync, g_eli_pre_sync);
1278 DECLARE_GEOM_CLASS(g_eli_class, g_eli);
1279 MODULE_DEPEND(g_eli, crypto, 1, 1, 1);