2 * Copyright (c) 2005-2010 Pawel Jakub Dawidek <pjd@FreeBSD.org>
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>
38 #include <sys/sysctl.h>
39 #include <sys/malloc.h>
40 #include <sys/eventhandler.h>
41 #include <sys/kthread.h>
43 #include <sys/sched.h>
46 #include <sys/vnode.h>
50 #include <geom/geom.h>
51 #include <geom/eli/g_eli.h>
52 #include <geom/eli/pkcs5v2.h>
55 MALLOC_DEFINE(M_ELI, "eli data", "GEOM_ELI Data");
57 SYSCTL_DECL(_kern_geom);
58 SYSCTL_NODE(_kern_geom, OID_AUTO, eli, CTLFLAG_RW, 0, "GEOM_ELI stuff");
60 TUNABLE_INT("kern.geom.eli.debug", &g_eli_debug);
61 SYSCTL_INT(_kern_geom_eli, OID_AUTO, debug, CTLFLAG_RW, &g_eli_debug, 0,
63 static u_int g_eli_tries = 3;
64 TUNABLE_INT("kern.geom.eli.tries", &g_eli_tries);
65 SYSCTL_UINT(_kern_geom_eli, OID_AUTO, tries, CTLFLAG_RW, &g_eli_tries, 0,
66 "Number of tries for entering the passphrase");
67 static u_int g_eli_visible_passphrase = 0;
68 TUNABLE_INT("kern.geom.eli.visible_passphrase", &g_eli_visible_passphrase);
69 SYSCTL_UINT(_kern_geom_eli, OID_AUTO, visible_passphrase, CTLFLAG_RW,
70 &g_eli_visible_passphrase, 0,
71 "Turn on echo when entering the passphrase (for debug purposes only!!)");
72 u_int g_eli_overwrites = G_ELI_OVERWRITES;
73 TUNABLE_INT("kern.geom.eli.overwrites", &g_eli_overwrites);
74 SYSCTL_UINT(_kern_geom_eli, OID_AUTO, overwrites, CTLFLAG_RW, &g_eli_overwrites,
75 0, "Number of times on-disk keys should be overwritten when destroying them");
76 static u_int g_eli_threads = 0;
77 TUNABLE_INT("kern.geom.eli.threads", &g_eli_threads);
78 SYSCTL_UINT(_kern_geom_eli, OID_AUTO, threads, CTLFLAG_RW, &g_eli_threads, 0,
79 "Number of threads doing crypto work");
80 u_int g_eli_batch = 0;
81 TUNABLE_INT("kern.geom.eli.batch", &g_eli_batch);
82 SYSCTL_UINT(_kern_geom_eli, OID_AUTO, batch, CTLFLAG_RW, &g_eli_batch, 0,
83 "Use crypto operations batching");
85 static eventhandler_tag g_eli_pre_sync = NULL;
87 static int g_eli_destroy_geom(struct gctl_req *req, struct g_class *mp,
89 static void g_eli_init(struct g_class *mp);
90 static void g_eli_fini(struct g_class *mp);
92 static g_taste_t g_eli_taste;
93 static g_dumpconf_t g_eli_dumpconf;
95 struct g_class g_eli_class = {
96 .name = G_ELI_CLASS_NAME,
98 .ctlreq = g_eli_config,
100 .destroy_geom = g_eli_destroy_geom,
109 * 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
111 * g_eli_start -> g_eli_crypto_run -> g_eli_crypto_write_done -> g_io_request -> g_eli_write_done -> g_io_deliver
116 * EAGAIN from crypto(9) means, that we were probably balanced to another crypto
117 * accelerator or something like this.
118 * The function updates the SID and rerun the operation.
121 g_eli_crypto_rerun(struct cryptop *crp)
123 struct g_eli_softc *sc;
124 struct g_eli_worker *wr;
128 bp = (struct bio *)crp->crp_opaque;
129 sc = bp->bio_to->geom->softc;
130 LIST_FOREACH(wr, &sc->sc_workers, w_next) {
131 if (wr->w_number == bp->bio_pflags)
134 KASSERT(wr != NULL, ("Invalid worker (%u).", bp->bio_pflags));
135 G_ELI_DEBUG(1, "Rerunning crypto %s request (sid: %ju -> %ju).",
136 bp->bio_cmd == BIO_READ ? "READ" : "WRITE", (uintmax_t)wr->w_sid,
137 (uintmax_t)crp->crp_sid);
138 wr->w_sid = crp->crp_sid;
140 error = crypto_dispatch(crp);
143 G_ELI_DEBUG(1, "%s: crypto_dispatch() returned %d.", __func__, error);
144 crp->crp_etype = error;
149 * The function is called afer reading encrypted data from the provider.
151 * 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
154 g_eli_read_done(struct bio *bp)
156 struct g_eli_softc *sc;
159 G_ELI_LOGREQ(2, bp, "Request done.");
160 pbp = bp->bio_parent;
161 if (pbp->bio_error == 0)
162 pbp->bio_error = bp->bio_error;
164 * Do we have all sectors already?
167 if (pbp->bio_inbed < pbp->bio_children)
170 sc = pbp->bio_to->geom->softc;
171 if (pbp->bio_error != 0) {
172 G_ELI_LOGREQ(0, pbp, "%s() failed", __func__);
173 pbp->bio_completed = 0;
174 if (pbp->bio_driver2 != NULL) {
175 free(pbp->bio_driver2, M_ELI);
176 pbp->bio_driver2 = NULL;
178 g_io_deliver(pbp, pbp->bio_error);
179 atomic_subtract_int(&sc->sc_inflight, 1);
182 mtx_lock(&sc->sc_queue_mtx);
183 bioq_insert_tail(&sc->sc_queue, pbp);
184 mtx_unlock(&sc->sc_queue_mtx);
189 * The function is called after we encrypt and write data.
191 * g_eli_start -> g_eli_crypto_run -> g_eli_crypto_write_done -> g_io_request -> G_ELI_WRITE_DONE -> g_io_deliver
194 g_eli_write_done(struct bio *bp)
196 struct g_eli_softc *sc;
199 G_ELI_LOGREQ(2, bp, "Request done.");
200 pbp = bp->bio_parent;
201 if (pbp->bio_error == 0) {
202 if (bp->bio_error != 0)
203 pbp->bio_error = bp->bio_error;
206 * Do we have all sectors already?
209 if (pbp->bio_inbed < pbp->bio_children)
211 free(pbp->bio_driver2, M_ELI);
212 pbp->bio_driver2 = NULL;
213 if (pbp->bio_error != 0) {
214 G_ELI_LOGREQ(0, pbp, "Crypto WRITE request failed (error=%d).",
216 pbp->bio_completed = 0;
220 * Write is finished, send it up.
222 pbp->bio_completed = pbp->bio_length;
223 sc = pbp->bio_to->geom->softc;
224 g_io_deliver(pbp, pbp->bio_error);
225 atomic_subtract_int(&sc->sc_inflight, 1);
229 * This function should never be called, but GEOM made as it set ->orphan()
230 * method for every geom.
233 g_eli_orphan_spoil_assert(struct g_consumer *cp)
236 panic("Function %s() called for %s.", __func__, cp->geom->name);
240 g_eli_orphan(struct g_consumer *cp)
242 struct g_eli_softc *sc;
245 sc = cp->geom->softc;
248 g_eli_destroy(sc, TRUE);
253 * 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
255 * G_ELI_START -> g_eli_crypto_run -> g_eli_crypto_write_done -> g_io_request -> g_eli_write_done -> g_io_deliver
258 g_eli_start(struct bio *bp)
260 struct g_eli_softc *sc;
261 struct g_consumer *cp;
264 sc = bp->bio_to->geom->softc;
266 ("Provider's error should be set (error=%d)(device=%s).",
267 bp->bio_to->error, bp->bio_to->name));
268 G_ELI_LOGREQ(2, bp, "Request received.");
270 switch (bp->bio_cmd) {
278 * We could eventually support BIO_DELETE request.
279 * It could be done by overwritting requested sector with
280 * random data g_eli_overwrites number of times.
283 g_io_deliver(bp, EOPNOTSUPP);
286 cbp = g_clone_bio(bp);
288 g_io_deliver(bp, ENOMEM);
291 bp->bio_driver1 = cbp;
292 bp->bio_pflags = G_ELI_NEW_BIO;
293 switch (bp->bio_cmd) {
295 if (!(sc->sc_flags & G_ELI_FLAG_AUTH)) {
296 g_eli_crypto_read(sc, bp, 0);
301 mtx_lock(&sc->sc_queue_mtx);
302 bioq_insert_tail(&sc->sc_queue, bp);
303 mtx_unlock(&sc->sc_queue_mtx);
308 cbp->bio_done = g_std_done;
309 cp = LIST_FIRST(&sc->sc_geom->consumer);
310 cbp->bio_to = cp->provider;
311 G_ELI_LOGREQ(2, cbp, "Sending request.");
312 g_io_request(cbp, cp);
318 g_eli_newsession(struct g_eli_worker *wr)
320 struct g_eli_softc *sc;
321 struct cryptoini crie, cria;
326 bzero(&crie, sizeof(crie));
327 crie.cri_alg = sc->sc_ealgo;
328 crie.cri_klen = sc->sc_ekeylen;
329 if (sc->sc_ealgo == CRYPTO_AES_XTS)
331 crie.cri_key = sc->sc_ekeys[0];
332 if (sc->sc_flags & G_ELI_FLAG_AUTH) {
333 bzero(&cria, sizeof(cria));
334 cria.cri_alg = sc->sc_aalgo;
335 cria.cri_klen = sc->sc_akeylen;
336 cria.cri_key = sc->sc_akey;
337 crie.cri_next = &cria;
340 switch (sc->sc_crypto) {
341 case G_ELI_CRYPTO_SW:
342 error = crypto_newsession(&wr->w_sid, &crie,
343 CRYPTOCAP_F_SOFTWARE);
345 case G_ELI_CRYPTO_HW:
346 error = crypto_newsession(&wr->w_sid, &crie,
347 CRYPTOCAP_F_HARDWARE);
349 case G_ELI_CRYPTO_UNKNOWN:
350 error = crypto_newsession(&wr->w_sid, &crie,
351 CRYPTOCAP_F_HARDWARE);
353 mtx_lock(&sc->sc_queue_mtx);
354 if (sc->sc_crypto == G_ELI_CRYPTO_UNKNOWN)
355 sc->sc_crypto = G_ELI_CRYPTO_HW;
356 mtx_unlock(&sc->sc_queue_mtx);
358 error = crypto_newsession(&wr->w_sid, &crie,
359 CRYPTOCAP_F_SOFTWARE);
360 mtx_lock(&sc->sc_queue_mtx);
361 if (sc->sc_crypto == G_ELI_CRYPTO_UNKNOWN)
362 sc->sc_crypto = G_ELI_CRYPTO_SW;
363 mtx_unlock(&sc->sc_queue_mtx);
367 panic("%s: invalid condition", __func__);
374 g_eli_freesession(struct g_eli_worker *wr)
377 crypto_freesession(wr->w_sid);
381 g_eli_cancel(struct g_eli_softc *sc)
385 mtx_assert(&sc->sc_queue_mtx, MA_OWNED);
387 while ((bp = bioq_takefirst(&sc->sc_queue)) != NULL) {
388 KASSERT(bp->bio_pflags == G_ELI_NEW_BIO,
389 ("Not new bio when canceling (bp=%p).", bp));
390 g_io_deliver(bp, ENXIO);
395 g_eli_takefirst(struct g_eli_softc *sc)
399 mtx_assert(&sc->sc_queue_mtx, MA_OWNED);
401 if (!(sc->sc_flags & G_ELI_FLAG_SUSPEND))
402 return (bioq_takefirst(&sc->sc_queue));
404 * Device suspended, so we skip new I/O requests.
406 TAILQ_FOREACH(bp, &sc->sc_queue.queue, bio_queue) {
407 if (bp->bio_pflags != G_ELI_NEW_BIO)
411 bioq_remove(&sc->sc_queue, bp);
416 * This is the main function for kernel worker thread when we don't have
417 * hardware acceleration and we have to do cryptography in software.
418 * Dedicated thread is needed, so we don't slow down g_up/g_down GEOM
419 * threads with crypto work.
422 g_eli_worker(void *arg)
424 struct g_eli_softc *sc;
425 struct g_eli_worker *wr;
432 /* Before sched_bind() to a CPU, wait for all CPUs to go on-line. */
433 if (mp_ncpus > 1 && sc->sc_crypto == G_ELI_CRYPTO_SW &&
434 g_eli_threads == 0) {
436 tsleep(wr, 0, "geli:smp", hz / 4);
439 thread_lock(curthread);
440 sched_prio(curthread, PUSER);
441 if (sc->sc_crypto == G_ELI_CRYPTO_SW && g_eli_threads == 0)
442 sched_bind(curthread, wr->w_number);
443 thread_unlock(curthread);
445 G_ELI_DEBUG(1, "Thread %s started.", curthread->td_proc->p_comm);
448 mtx_lock(&sc->sc_queue_mtx);
450 bp = g_eli_takefirst(sc);
452 if (sc->sc_flags & G_ELI_FLAG_DESTROY) {
454 LIST_REMOVE(wr, w_next);
455 g_eli_freesession(wr);
457 G_ELI_DEBUG(1, "Thread %s exiting.",
458 curthread->td_proc->p_comm);
459 wakeup(&sc->sc_workers);
460 mtx_unlock(&sc->sc_queue_mtx);
463 while (sc->sc_flags & G_ELI_FLAG_SUSPEND) {
464 if (sc->sc_inflight > 0) {
465 G_ELI_DEBUG(0, "inflight=%d", sc->sc_inflight);
467 * We still have inflight BIOs, so
470 msleep(sc, &sc->sc_queue_mtx, PRIBIO,
475 * Suspend requested, mark the worker as
476 * suspended and go to sleep.
479 g_eli_freesession(wr);
480 wr->w_active = FALSE;
482 wakeup(&sc->sc_workers);
483 msleep(sc, &sc->sc_queue_mtx, PRIBIO,
486 !(sc->sc_flags & G_ELI_FLAG_SUSPEND)) {
487 error = g_eli_newsession(wr);
489 ("g_eli_newsession() failed on resume (error=%d)",
495 msleep(sc, &sc->sc_queue_mtx, PDROP, "geli:w", 0);
498 if (bp->bio_pflags == G_ELI_NEW_BIO)
499 atomic_add_int(&sc->sc_inflight, 1);
500 mtx_unlock(&sc->sc_queue_mtx);
501 if (bp->bio_pflags == G_ELI_NEW_BIO) {
503 if (sc->sc_flags & G_ELI_FLAG_AUTH) {
504 if (bp->bio_cmd == BIO_READ)
505 g_eli_auth_read(sc, bp);
507 g_eli_auth_run(wr, bp);
509 if (bp->bio_cmd == BIO_READ)
510 g_eli_crypto_read(sc, bp, 1);
512 g_eli_crypto_run(wr, bp);
515 if (sc->sc_flags & G_ELI_FLAG_AUTH)
516 g_eli_auth_run(wr, bp);
518 g_eli_crypto_run(wr, bp);
524 * Select encryption key. If G_ELI_FLAG_SINGLE_KEY is present we only have one
525 * key available for all the data. If the flag is not present select the key
526 * based on data offset.
529 g_eli_crypto_key(struct g_eli_softc *sc, off_t offset, size_t blocksize)
533 if (sc->sc_nekeys == 1)
534 return (sc->sc_ekeys[0]);
536 KASSERT(sc->sc_nekeys > 1, ("%s: sc_nekeys=%u", __func__,
538 KASSERT((sc->sc_flags & G_ELI_FLAG_SINGLE_KEY) == 0,
539 ("%s: SINGLE_KEY flag set, but sc_nekeys=%u", __func__,
542 /* We switch key every 2^G_ELI_KEY_SHIFT blocks. */
543 nkey = (offset >> G_ELI_KEY_SHIFT) / blocksize;
545 KASSERT(nkey < sc->sc_nekeys, ("%s: nkey=%u >= sc_nekeys=%u", __func__,
546 nkey, sc->sc_nekeys));
548 return (sc->sc_ekeys[nkey]);
552 * Here we generate IV. It is unique for every sector.
555 g_eli_crypto_ivgen(struct g_eli_softc *sc, off_t offset, u_char *iv,
560 if ((sc->sc_flags & G_ELI_FLAG_NATIVE_BYTE_ORDER) != 0)
561 bcopy(&offset, off, sizeof(off));
563 le64enc(off, (uint64_t)offset);
565 switch (sc->sc_ealgo) {
567 bcopy(off, iv, sizeof(off));
568 bzero(iv + sizeof(off), size - sizeof(off));
572 u_char hash[SHA256_DIGEST_LENGTH];
575 /* Copy precalculated SHA256 context for IV-Key. */
576 bcopy(&sc->sc_ivctx, &ctx, sizeof(ctx));
577 SHA256_Update(&ctx, off, sizeof(off));
578 SHA256_Final(hash, &ctx);
579 bcopy(hash, iv, MIN(sizeof(hash), size));
586 g_eli_read_metadata(struct g_class *mp, struct g_provider *pp,
587 struct g_eli_metadata *md)
590 struct g_consumer *cp;
596 gp = g_new_geomf(mp, "eli:taste");
597 gp->start = g_eli_start;
598 gp->access = g_std_access;
600 * g_eli_read_metadata() is always called from the event thread.
601 * Our geom is created and destroyed in the same event, so there
602 * could be no orphan nor spoil event in the meantime.
604 gp->orphan = g_eli_orphan_spoil_assert;
605 gp->spoiled = g_eli_orphan_spoil_assert;
606 cp = g_new_consumer(gp);
607 error = g_attach(cp, pp);
610 error = g_access(cp, 1, 0, 0);
614 buf = g_read_data(cp, pp->mediasize - pp->sectorsize, pp->sectorsize,
619 eli_metadata_decode(buf, md);
623 if (cp->provider != NULL) {
625 g_access(cp, -1, 0, 0);
628 g_destroy_consumer(cp);
634 * The function is called when we had last close on provider and user requested
635 * to close it when this situation occur.
638 g_eli_last_close(struct g_eli_softc *sc)
641 struct g_provider *pp;
647 pp = LIST_FIRST(&gp->provider);
648 strlcpy(ppname, pp->name, sizeof(ppname));
649 error = g_eli_destroy(sc, TRUE);
650 KASSERT(error == 0, ("Cannot detach %s on last close (error=%d).",
652 G_ELI_DEBUG(0, "Detached %s on last close.", ppname);
656 g_eli_access(struct g_provider *pp, int dr, int dw, int de)
658 struct g_eli_softc *sc;
665 if (sc->sc_flags & G_ELI_FLAG_RO) {
666 /* Deny write attempts. */
669 /* Someone is opening us for write, we need to remember that. */
670 sc->sc_flags |= G_ELI_FLAG_WOPEN;
673 /* Is this the last close? */
674 if (pp->acr + dr > 0 || pp->acw + dw > 0 || pp->ace + de > 0)
678 * Automatically detach on last close if requested.
680 if ((sc->sc_flags & G_ELI_FLAG_RW_DETACH) ||
681 (sc->sc_flags & G_ELI_FLAG_WOPEN)) {
682 g_eli_last_close(sc);
688 g_eli_cpu_is_disabled(int cpu)
691 return ((hlt_cpus_mask & (1 << cpu)) != 0);
698 g_eli_create(struct gctl_req *req, struct g_class *mp, struct g_provider *bpp,
699 const struct g_eli_metadata *md, const u_char *mkey, int nkey)
701 struct g_eli_softc *sc;
702 struct g_eli_worker *wr;
704 struct g_provider *pp;
705 struct g_consumer *cp;
709 G_ELI_DEBUG(1, "Creating device %s%s.", bpp->name, G_ELI_SUFFIX);
711 gp = g_new_geomf(mp, "%s%s", bpp->name, G_ELI_SUFFIX);
712 gp->softc = NULL; /* for a moment */
714 sc = malloc(sizeof(*sc), M_ELI, M_WAITOK | M_ZERO);
715 gp->start = g_eli_start;
717 * Spoiling cannot happen actually, because we keep provider open for
718 * writing all the time or provider is read-only.
720 gp->spoiled = g_eli_orphan_spoil_assert;
721 gp->orphan = g_eli_orphan;
722 gp->dumpconf = g_eli_dumpconf;
724 * If detach-on-last-close feature is not enabled and we don't operate
725 * on read-only provider, we can simply use g_std_access().
727 if (md->md_flags & (G_ELI_FLAG_WO_DETACH | G_ELI_FLAG_RO))
728 gp->access = g_eli_access;
730 gp->access = g_std_access;
733 sc->sc_crypto = G_ELI_CRYPTO_UNKNOWN;
734 sc->sc_flags = md->md_flags;
735 /* Backward compatibility. */
736 if (md->md_version < 4)
737 sc->sc_flags |= G_ELI_FLAG_NATIVE_BYTE_ORDER;
738 if (md->md_version < 5)
739 sc->sc_flags |= G_ELI_FLAG_SINGLE_KEY;
740 sc->sc_ealgo = md->md_ealgo;
743 if (sc->sc_flags & G_ELI_FLAG_AUTH) {
744 sc->sc_akeylen = sizeof(sc->sc_akey) * 8;
745 sc->sc_aalgo = md->md_aalgo;
746 sc->sc_alen = g_eli_hashlen(sc->sc_aalgo);
748 sc->sc_data_per_sector = bpp->sectorsize - sc->sc_alen;
750 * Some hash functions (like SHA1 and RIPEMD160) generates hash
751 * which length is not multiple of 128 bits, but we want data
752 * length to be multiple of 128, so we can encrypt without
753 * padding. The line below rounds down data length to multiple
756 sc->sc_data_per_sector -= sc->sc_data_per_sector % 16;
758 sc->sc_bytes_per_sector =
759 (md->md_sectorsize - 1) / sc->sc_data_per_sector + 1;
760 sc->sc_bytes_per_sector *= bpp->sectorsize;
766 bioq_init(&sc->sc_queue);
767 mtx_init(&sc->sc_queue_mtx, "geli:queue", NULL, MTX_DEF);
770 cp = g_new_consumer(gp);
771 error = g_attach(cp, bpp);
774 gctl_error(req, "Cannot attach to %s (error=%d).",
777 G_ELI_DEBUG(1, "Cannot attach to %s (error=%d).",
783 * Keep provider open all the time, so we can run critical tasks,
784 * like Master Keys deletion, without wondering if we can open
786 * We don't open provider for writing only when user requested read-only
789 if (sc->sc_flags & G_ELI_FLAG_RO)
790 error = g_access(cp, 1, 0, 1);
792 error = g_access(cp, 1, 1, 1);
795 gctl_error(req, "Cannot access %s (error=%d).",
798 G_ELI_DEBUG(1, "Cannot access %s (error=%d).",
804 sc->sc_sectorsize = md->md_sectorsize;
805 sc->sc_mediasize = bpp->mediasize;
806 if (!(sc->sc_flags & G_ELI_FLAG_ONETIME))
807 sc->sc_mediasize -= bpp->sectorsize;
808 if (!(sc->sc_flags & G_ELI_FLAG_AUTH))
809 sc->sc_mediasize -= (sc->sc_mediasize % sc->sc_sectorsize);
811 sc->sc_mediasize /= sc->sc_bytes_per_sector;
812 sc->sc_mediasize *= sc->sc_sectorsize;
816 * Remember the keys in our softc structure.
818 g_eli_mkey_propagate(sc, mkey);
819 sc->sc_ekeylen = md->md_keylen;
821 LIST_INIT(&sc->sc_workers);
823 threads = g_eli_threads;
826 else if (threads > mp_ncpus) {
827 /* There is really no need for too many worker threads. */
829 G_ELI_DEBUG(0, "Reducing number of threads to %u.", threads);
831 for (i = 0; i < threads; i++) {
832 if (g_eli_cpu_is_disabled(i)) {
833 G_ELI_DEBUG(1, "%s: CPU %u disabled, skipping.",
837 wr = malloc(sizeof(*wr), M_ELI, M_WAITOK | M_ZERO);
842 error = g_eli_newsession(wr);
846 gctl_error(req, "Cannot set up crypto session "
847 "for %s (error=%d).", bpp->name, error);
849 G_ELI_DEBUG(1, "Cannot set up crypto session "
850 "for %s (error=%d).", bpp->name, error);
855 error = kproc_create(g_eli_worker, wr, &wr->w_proc, 0, 0,
856 "g_eli[%u] %s", i, bpp->name);
858 g_eli_freesession(wr);
861 gctl_error(req, "Cannot create kernel thread "
862 "for %s (error=%d).", bpp->name, error);
864 G_ELI_DEBUG(1, "Cannot create kernel thread "
865 "for %s (error=%d).", bpp->name, error);
869 LIST_INSERT_HEAD(&sc->sc_workers, wr, w_next);
870 /* If we have hardware support, one thread is enough. */
871 if (sc->sc_crypto == G_ELI_CRYPTO_HW)
876 * Create decrypted provider.
878 pp = g_new_providerf(gp, "%s%s", bpp->name, G_ELI_SUFFIX);
879 pp->mediasize = sc->sc_mediasize;
880 pp->sectorsize = sc->sc_sectorsize;
882 g_error_provider(pp, 0);
884 G_ELI_DEBUG(0, "Device %s created.", pp->name);
885 G_ELI_DEBUG(0, "Encryption: %s %u", g_eli_algo2str(sc->sc_ealgo),
887 if (sc->sc_flags & G_ELI_FLAG_AUTH)
888 G_ELI_DEBUG(0, " Integrity: %s", g_eli_algo2str(sc->sc_aalgo));
889 G_ELI_DEBUG(0, " Crypto: %s",
890 sc->sc_crypto == G_ELI_CRYPTO_SW ? "software" : "hardware");
893 mtx_lock(&sc->sc_queue_mtx);
894 sc->sc_flags |= G_ELI_FLAG_DESTROY;
897 * Wait for kernel threads self destruction.
899 while (!LIST_EMPTY(&sc->sc_workers)) {
900 msleep(&sc->sc_workers, &sc->sc_queue_mtx, PRIBIO,
903 mtx_destroy(&sc->sc_queue_mtx);
904 if (cp->provider != NULL) {
906 g_access(cp, -1, -1, -1);
909 g_destroy_consumer(cp);
911 if (sc->sc_ekeys != NULL) {
913 sc->sc_nekeys * (sizeof(uint8_t *) + G_ELI_DATAKEYLEN));
914 free(sc->sc_ekeys, M_ELI);
916 bzero(sc, sizeof(*sc));
922 g_eli_destroy(struct g_eli_softc *sc, boolean_t force)
925 struct g_provider *pp;
933 pp = LIST_FIRST(&gp->provider);
934 if (pp != NULL && (pp->acr != 0 || pp->acw != 0 || pp->ace != 0)) {
936 G_ELI_DEBUG(1, "Device %s is still open, so it "
937 "cannot be definitely removed.", pp->name);
940 "Device %s is still open (r%dw%de%d).", pp->name,
941 pp->acr, pp->acw, pp->ace);
946 mtx_lock(&sc->sc_queue_mtx);
947 sc->sc_flags |= G_ELI_FLAG_DESTROY;
949 while (!LIST_EMPTY(&sc->sc_workers)) {
950 msleep(&sc->sc_workers, &sc->sc_queue_mtx, PRIBIO,
953 mtx_destroy(&sc->sc_queue_mtx);
955 if (sc->sc_ekeys != NULL) {
956 /* The sc_ekeys field can be NULL is device is suspended. */
958 sc->sc_nekeys * (sizeof(uint8_t *) + G_ELI_DATAKEYLEN));
959 free(sc->sc_ekeys, M_ELI);
961 bzero(sc, sizeof(*sc));
964 if (pp == NULL || (pp->acr == 0 && pp->acw == 0 && pp->ace == 0))
965 G_ELI_DEBUG(0, "Device %s destroyed.", gp->name);
966 g_wither_geom_close(gp, ENXIO);
972 g_eli_destroy_geom(struct gctl_req *req __unused,
973 struct g_class *mp __unused, struct g_geom *gp)
975 struct g_eli_softc *sc;
978 return (g_eli_destroy(sc, FALSE));
982 g_eli_keyfiles_load(struct hmac_ctx *ctx, const char *provider)
984 u_char *keyfile, *data, *size;
985 char *file, name[64];
989 snprintf(name, sizeof(name), "%s:geli_keyfile%d", provider, i);
990 keyfile = preload_search_by_type(name);
992 return (i); /* Return number of loaded keyfiles. */
993 data = preload_search_info(keyfile, MODINFO_ADDR);
995 G_ELI_DEBUG(0, "Cannot find key file data for %s.",
999 data = *(void **)data;
1000 size = preload_search_info(keyfile, MODINFO_SIZE);
1002 G_ELI_DEBUG(0, "Cannot find key file size for %s.",
1006 file = preload_search_info(keyfile, MODINFO_NAME);
1008 G_ELI_DEBUG(0, "Cannot find key file name for %s.",
1012 G_ELI_DEBUG(1, "Loaded keyfile %s for %s (type: %s).", file,
1014 g_eli_crypto_hmac_update(ctx, data, *(size_t *)size);
1019 g_eli_keyfiles_clear(const char *provider)
1021 u_char *keyfile, *data, *size;
1025 for (i = 0; ; i++) {
1026 snprintf(name, sizeof(name), "%s:geli_keyfile%d", provider, i);
1027 keyfile = preload_search_by_type(name);
1028 if (keyfile == NULL)
1030 data = preload_search_info(keyfile, MODINFO_ADDR);
1031 size = preload_search_info(keyfile, MODINFO_SIZE);
1032 if (data == NULL || size == NULL)
1034 data = *(void **)data;
1035 bzero(data, *(size_t *)size);
1040 * Tasting is only made on boot.
1041 * We detect providers which should be attached before root is mounted.
1043 static struct g_geom *
1044 g_eli_taste(struct g_class *mp, struct g_provider *pp, int flags __unused)
1046 struct g_eli_metadata md;
1048 struct hmac_ctx ctx;
1049 char passphrase[256];
1050 u_char key[G_ELI_USERKEYLEN], mkey[G_ELI_DATAIVKEYLEN];
1051 u_int i, nkey, nkeyfiles, tries;
1054 g_trace(G_T_TOPOLOGY, "%s(%s, %s)", __func__, mp->name, pp->name);
1055 g_topology_assert();
1057 if (root_mounted() || g_eli_tries == 0)
1060 G_ELI_DEBUG(3, "Tasting %s.", pp->name);
1062 error = g_eli_read_metadata(mp, pp, &md);
1067 if (strcmp(md.md_magic, G_ELI_MAGIC) != 0)
1069 if (md.md_version > G_ELI_VERSION) {
1070 printf("geom_eli.ko module is too old to handle %s.\n",
1074 if (md.md_provsize != pp->mediasize)
1076 /* Should we attach it on boot? */
1077 if (!(md.md_flags & G_ELI_FLAG_BOOT))
1079 if (md.md_keys == 0x00) {
1080 G_ELI_DEBUG(0, "No valid keys on %s.", pp->name);
1083 if (md.md_iterations == -1) {
1084 /* If there is no passphrase, we try only once. */
1087 /* Ask for the passphrase no more than g_eli_tries times. */
1088 tries = g_eli_tries;
1091 for (i = 0; i < tries; i++) {
1092 g_eli_crypto_hmac_init(&ctx, NULL, 0);
1095 * Load all key files.
1097 nkeyfiles = g_eli_keyfiles_load(&ctx, pp->name);
1099 if (nkeyfiles == 0 && md.md_iterations == -1) {
1101 * No key files and no passphrase, something is
1102 * definitely wrong here.
1103 * geli(8) doesn't allow for such situation, so assume
1104 * that there was really no passphrase and in that case
1105 * key files are no properly defined in loader.conf.
1108 "Found no key files in loader.conf for %s.",
1113 /* Ask for the passphrase if defined. */
1114 if (md.md_iterations >= 0) {
1115 printf("Enter passphrase for %s: ", pp->name);
1116 gets(passphrase, sizeof(passphrase),
1117 g_eli_visible_passphrase);
1121 * Prepare Derived-Key from the user passphrase.
1123 if (md.md_iterations == 0) {
1124 g_eli_crypto_hmac_update(&ctx, md.md_salt,
1125 sizeof(md.md_salt));
1126 g_eli_crypto_hmac_update(&ctx, passphrase,
1127 strlen(passphrase));
1128 bzero(passphrase, sizeof(passphrase));
1129 } else if (md.md_iterations > 0) {
1130 u_char dkey[G_ELI_USERKEYLEN];
1132 pkcs5v2_genkey(dkey, sizeof(dkey), md.md_salt,
1133 sizeof(md.md_salt), passphrase, md.md_iterations);
1134 bzero(passphrase, sizeof(passphrase));
1135 g_eli_crypto_hmac_update(&ctx, dkey, sizeof(dkey));
1136 bzero(dkey, sizeof(dkey));
1139 g_eli_crypto_hmac_final(&ctx, key, 0);
1142 * Decrypt Master-Key.
1144 error = g_eli_mkey_decrypt(&md, key, mkey, &nkey);
1145 bzero(key, sizeof(key));
1147 if (i == tries - 1) {
1149 "Wrong key for %s. No tries left.",
1151 g_eli_keyfiles_clear(pp->name);
1154 G_ELI_DEBUG(0, "Wrong key for %s. Tries left: %u.",
1155 pp->name, tries - i - 1);
1158 } else if (error > 0) {
1159 G_ELI_DEBUG(0, "Cannot decrypt Master Key for %s (error=%d).",
1161 g_eli_keyfiles_clear(pp->name);
1164 G_ELI_DEBUG(1, "Using Master Key %u for %s.", nkey, pp->name);
1169 * We have correct key, let's attach provider.
1171 gp = g_eli_create(NULL, mp, pp, &md, mkey, nkey);
1172 bzero(mkey, sizeof(mkey));
1173 bzero(&md, sizeof(md));
1175 G_ELI_DEBUG(0, "Cannot create device %s%s.", pp->name,
1183 g_eli_dumpconf(struct sbuf *sb, const char *indent, struct g_geom *gp,
1184 struct g_consumer *cp, struct g_provider *pp)
1186 struct g_eli_softc *sc;
1188 g_topology_assert();
1192 if (pp != NULL || cp != NULL)
1193 return; /* Nothing here. */
1194 sbuf_printf(sb, "%s<Flags>", indent);
1195 if (sc->sc_flags == 0)
1196 sbuf_printf(sb, "NONE");
1200 #define ADD_FLAG(flag, name) do { \
1201 if (sc->sc_flags & (flag)) { \
1203 sbuf_printf(sb, ", "); \
1206 sbuf_printf(sb, name); \
1209 ADD_FLAG(G_ELI_FLAG_SUSPEND, "SUSPEND");
1210 ADD_FLAG(G_ELI_FLAG_SINGLE_KEY, "SINGLE-KEY");
1211 ADD_FLAG(G_ELI_FLAG_NATIVE_BYTE_ORDER, "NATIVE-BYTE-ORDER");
1212 ADD_FLAG(G_ELI_FLAG_ONETIME, "ONETIME");
1213 ADD_FLAG(G_ELI_FLAG_BOOT, "BOOT");
1214 ADD_FLAG(G_ELI_FLAG_WO_DETACH, "W-DETACH");
1215 ADD_FLAG(G_ELI_FLAG_RW_DETACH, "RW-DETACH");
1216 ADD_FLAG(G_ELI_FLAG_AUTH, "AUTH");
1217 ADD_FLAG(G_ELI_FLAG_WOPEN, "W-OPEN");
1218 ADD_FLAG(G_ELI_FLAG_DESTROY, "DESTROY");
1219 ADD_FLAG(G_ELI_FLAG_RO, "READ-ONLY");
1222 sbuf_printf(sb, "</Flags>\n");
1224 if (!(sc->sc_flags & G_ELI_FLAG_ONETIME)) {
1225 sbuf_printf(sb, "%s<UsedKey>%u</UsedKey>\n", indent,
1228 sbuf_printf(sb, "%s<Crypto>", indent);
1229 switch (sc->sc_crypto) {
1230 case G_ELI_CRYPTO_HW:
1231 sbuf_printf(sb, "hardware");
1233 case G_ELI_CRYPTO_SW:
1234 sbuf_printf(sb, "software");
1237 sbuf_printf(sb, "UNKNOWN");
1240 sbuf_printf(sb, "</Crypto>\n");
1241 if (sc->sc_flags & G_ELI_FLAG_AUTH) {
1243 "%s<AuthenticationAlgorithm>%s</AuthenticationAlgorithm>\n",
1244 indent, g_eli_algo2str(sc->sc_aalgo));
1246 sbuf_printf(sb, "%s<KeyLength>%u</KeyLength>\n", indent,
1248 sbuf_printf(sb, "%s<EncryptionAlgorithm>%s</EncryptionAlgorithm>\n", indent,
1249 g_eli_algo2str(sc->sc_ealgo));
1250 sbuf_printf(sb, "%s<State>%s</State>\n", indent,
1251 (sc->sc_flags & G_ELI_FLAG_SUSPEND) ? "SUSPENDED" : "ACTIVE");
1255 g_eli_shutdown_pre_sync(void *arg, int howto)
1258 struct g_geom *gp, *gp2;
1259 struct g_provider *pp;
1260 struct g_eli_softc *sc;
1266 LIST_FOREACH_SAFE(gp, &mp->geom, geom, gp2) {
1270 pp = LIST_FIRST(&gp->provider);
1271 KASSERT(pp != NULL, ("No provider? gp=%p (%s)", gp, gp->name));
1272 if (pp->acr + pp->acw + pp->ace == 0)
1273 error = g_eli_destroy(sc, TRUE);
1275 sc->sc_flags |= G_ELI_FLAG_RW_DETACH;
1276 gp->access = g_eli_access;
1279 g_topology_unlock();
1284 g_eli_init(struct g_class *mp)
1287 g_eli_pre_sync = EVENTHANDLER_REGISTER(shutdown_pre_sync,
1288 g_eli_shutdown_pre_sync, mp, SHUTDOWN_PRI_FIRST);
1289 if (g_eli_pre_sync == NULL)
1290 G_ELI_DEBUG(0, "Warning! Cannot register shutdown event.");
1294 g_eli_fini(struct g_class *mp)
1297 if (g_eli_pre_sync != NULL)
1298 EVENTHANDLER_DEREGISTER(shutdown_pre_sync, g_eli_pre_sync);
1301 DECLARE_GEOM_CLASS(g_eli_class, g_eli);
1302 MODULE_DEPEND(g_eli, crypto, 1, 1, 1);