]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sbin/gbde/gbde.c
THIS BRANCH IS OBSOLETE, PLEASE READ:
[FreeBSD/FreeBSD.git] / sbin / gbde / gbde.c
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2002 Poul-Henning Kamp
5  * Copyright (c) 2002 Networks Associates Technology, Inc.
6  * All rights reserved.
7  *
8  * This software was developed for the FreeBSD Project by Poul-Henning Kamp
9  * and NAI Labs, the Security Research Division of Network Associates, Inc.
10  * under DARPA/SPAWAR contract N66001-01-C-8035 ("CBOSS"), as part of the
11  * DARPA CHATS research program.
12  *
13  * Redistribution and use in source and binary forms, with or without
14  * modification, are permitted provided that the following conditions
15  * are met:
16  * 1. Redistributions of source code must retain the above copyright
17  *    notice, this list of conditions and the following disclaimer.
18  * 2. Redistributions in binary form must reproduce the above copyright
19  *    notice, this list of conditions and the following disclaimer in the
20  *    documentation and/or other materials provided with the distribution.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  * $FreeBSD$
35  *
36  * XXX: Future stuff
37  *
38  * Replace the template file options (-i & -f) with command-line variables
39  * "-v property=foo"
40  *
41  * Introduce -e, extra entropy source (XOR with /dev/random)
42  *
43  * Introduce -E, alternate entropy source (instead of /dev/random)
44  *
45  * Introduce -i take IV from keyboard or
46  *
47  * Introduce -I take IV from file/cmd
48  *
49  * Introduce -m/-M store encrypted+encoded masterkey in file
50  *
51  * Introduce -k/-K get pass-phrase part from file/cmd
52  *
53  * Introduce -d add more dest-devices to worklist.
54  *
55  * Add key-option: selfdestruct bit.
56  *
57  * New/changed verbs:
58  *      "onetime"       attach with onetime nonstored locksector
59  *      "key"/"unkey" to blast memory copy of key without orphaning
60  *      "nuke" blow away everything attached, crash/halt/power-off if possible.
61  *      "blast" destroy all copies of the masterkey
62  *      "destroy" destroy one copy of the masterkey
63  *      "backup"/"restore" of masterkey sectors.
64  *
65  * Make all verbs work on both attached/detached devices.
66  *
67  */
68
69 #include <sys/types.h>
70 #include <sys/queue.h>
71 #include <sys/mutex.h>
72 #include <md5.h>
73 #include <readpassphrase.h>
74 #include <string.h>
75 #include <stdint.h>
76 #include <unistd.h>
77 #include <fcntl.h>
78 #include <paths.h>
79 #include <strings.h>
80 #include <stdlib.h>
81 #include <err.h>
82 #include <stdio.h>
83 #include <libutil.h>
84 #include <libgeom.h>
85 #include <sys/errno.h>
86 #include <sys/disk.h>
87 #include <sys/stat.h>
88 #include <crypto/rijndael/rijndael-api-fst.h>
89 #include <crypto/sha2/sha512.h>
90 #include <sys/param.h>
91 #include <sys/linker.h>
92
93 #define GBDEMOD "geom_bde"
94 #define KASSERT(foo, bar) do { if(!(foo)) { warn bar ; exit (1); } } while (0)
95
96 #include <geom/geom.h>
97 #include <geom/bde/g_bde.h>
98
99 extern const char template[];
100
101
102 #if 0
103 static void
104 g_hexdump(void *ptr, int length)
105 {
106         int i, j, k;
107         unsigned char *cp;
108
109         cp = ptr;
110         for (i = 0; i < length; i+= 16) {
111                 printf("%04x  ", i);
112                 for (j = 0; j < 16; j++) {
113                         k = i + j;
114                         if (k < length)
115                                 printf(" %02x", cp[k]);
116                         else
117                                 printf("   ");
118                 }
119                 printf("  |");
120                 for (j = 0; j < 16; j++) {
121                         k = i + j;
122                         if (k >= length)
123                                 printf(" ");
124                         else if (cp[k] >= ' ' && cp[k] <= '~')
125                                 printf("%c", cp[k]);
126                         else
127                                 printf(".");
128                 }
129                 printf("|\n");
130         }
131 }
132 #endif
133
134 static void __dead2
135 usage(void)
136 {
137
138         (void)fprintf(stderr,
139 "usage: gbde attach destination [-k keyfile] [-l lockfile] [-p pass-phrase]\n"
140 "       gbde detach destination\n"
141 "       gbde init destination [-i] [-f filename] [-K new-keyfile]\n"
142 "            [-L new-lockfile] [-P new-pass-phrase]\n"
143 "       gbde setkey destination [-n key]\n"
144 "            [-k keyfile] [-l lockfile] [-p pass-phrase]\n"
145 "            [-K new-keyfile] [-L new-lockfile] [-P new-pass-phrase]\n"
146 "       gbde nuke destination [-n key]\n"
147 "            [-k keyfile] [-l lockfile] [-p pass-phrase]\n"
148 "       gbde destroy destination [-k keyfile] [-l lockfile] [-p pass-phrase]\n");
149         exit(1);
150 }
151
152 void *
153 g_read_data(struct g_consumer *cp, off_t offset, off_t length, int *error)
154 {
155         void *p;
156         int fd, i;
157         off_t o2;
158
159         p = malloc(length);
160         if (p == NULL)
161                 err(1, "malloc");
162         fd = *(int *)cp;
163         o2 = lseek(fd, offset, SEEK_SET);
164         if (o2 != offset)
165                 err(1, "lseek");
166         i = read(fd, p, length);
167         if (i != length)
168                 err(1, "read");
169         if (error != NULL)
170                 error = 0;
171         return (p);
172 }
173
174 static void
175 random_bits(void *p, u_int len)
176 {
177         arc4random_buf(p, len);
178 }
179
180 /* XXX: not nice */
181 static u_char sha2[SHA512_DIGEST_LENGTH];
182
183 static void
184 reset_passphrase(struct g_bde_softc *sc)
185 {
186
187         memcpy(sc->sha2, sha2, SHA512_DIGEST_LENGTH);
188 }
189
190 static void
191 setup_passphrase(struct g_bde_softc *sc, int sure, const char *input,
192     const char *keyfile)
193 {
194         char buf1[BUFSIZ + SHA512_DIGEST_LENGTH];
195         char buf2[BUFSIZ + SHA512_DIGEST_LENGTH];
196         char *p;
197         int kfd, klen, bpos = 0;
198
199         if (keyfile != NULL) {
200                 /* Read up to BUFSIZ bytes from keyfile */
201                 kfd = open(keyfile, O_RDONLY, 0);
202                 if (kfd < 0)
203                         err(1, "%s", keyfile);
204                 klen = read(kfd, buf1, BUFSIZ);
205                 if (klen == -1)
206                         err(1, "%s", keyfile);
207                 close(kfd);
208
209                 /* Prepend the passphrase with the hash of the key read */
210                 g_bde_hash_pass(sc, buf1, klen);
211                 memcpy(buf1, sc->sha2, SHA512_DIGEST_LENGTH);
212                 memcpy(buf2, sc->sha2, SHA512_DIGEST_LENGTH);
213                 bpos = SHA512_DIGEST_LENGTH;
214         }
215
216         if (input != NULL) {
217                 if (strlen(input) >= BUFSIZ)
218                         errx(1, "Passphrase too long");
219                 strcpy(buf1 + bpos, input);
220
221                 g_bde_hash_pass(sc, buf1, strlen(buf1 + bpos) + bpos);
222                 memcpy(sha2, sc->sha2, SHA512_DIGEST_LENGTH);
223                 return;
224         }
225         for (;;) {
226                 p = readpassphrase(
227                     sure ? "Enter new passphrase:" : "Enter passphrase: ",
228                     buf1 + bpos, sizeof buf1 - bpos,
229                     RPP_ECHO_OFF | RPP_REQUIRE_TTY);
230                 if (p == NULL)
231                         err(1, "readpassphrase");
232
233                 if (sure) {
234                         p = readpassphrase("Reenter new passphrase: ",
235                             buf2 + bpos, sizeof buf2 - bpos,
236                             RPP_ECHO_OFF | RPP_REQUIRE_TTY);
237                         if (p == NULL)
238                                 err(1, "readpassphrase");
239
240                         if (strcmp(buf1 + bpos, buf2 + bpos)) {
241                                 printf("They didn't match.\n");
242                                 continue;
243                         }
244                 }
245                 if (strlen(buf1 + bpos) < 3) {
246                         printf("Too short passphrase.\n");
247                         continue;
248                 }
249                 break;
250         }
251         g_bde_hash_pass(sc, buf1, strlen(buf1 + bpos) + bpos);
252         memcpy(sha2, sc->sha2, SHA512_DIGEST_LENGTH);
253 }
254
255 static void
256 encrypt_sector(void *d, int len, int klen, void *key)
257 {
258         keyInstance ki;
259         cipherInstance ci;
260         int error;
261
262         error = rijndael_cipherInit(&ci, MODE_CBC, NULL);
263         if (error <= 0)
264                 errx(1, "rijndael_cipherInit=%d", error);
265         error = rijndael_makeKey(&ki, DIR_ENCRYPT, klen, key);
266         if (error <= 0)
267                 errx(1, "rijndael_makeKeY=%d", error);
268         error = rijndael_blockEncrypt(&ci, &ki, d, len * 8, d);
269         if (error <= 0)
270                 errx(1, "rijndael_blockEncrypt=%d", error);
271 }
272
273 static void
274 cmd_attach(const struct g_bde_softc *sc, const char *dest, const char *lfile)
275 {
276         int ffd;
277         u_char buf[16];
278         struct gctl_req *r;
279         const char *errstr;
280
281         r = gctl_get_handle();
282         gctl_ro_param(r, "verb", -1, "create geom");
283         gctl_ro_param(r, "class", -1, "BDE");
284         gctl_ro_param(r, "provider", -1, dest);
285         gctl_ro_param(r, "pass", SHA512_DIGEST_LENGTH, sc->sha2);
286         if (lfile != NULL) {
287                 ffd = open(lfile, O_RDONLY, 0);
288                 if (ffd < 0)
289                         err(1, "%s", lfile);
290                 read(ffd, buf, 16);
291                 gctl_ro_param(r, "key", 16, buf);
292                 close(ffd);
293         }
294         errstr = gctl_issue(r);
295         if (errstr != NULL)
296                 errx(1, "Attach to %s failed: %s", dest, errstr);
297
298         exit (0);
299 }
300
301 static void
302 cmd_detach(const char *dest)
303 {
304         struct gctl_req *r;
305         const char *errstr;
306         char buf[BUFSIZ];
307
308         r = gctl_get_handle();
309         gctl_ro_param(r, "verb", -1, "destroy geom");
310         gctl_ro_param(r, "class", -1, "BDE");
311         sprintf(buf, "%s.bde", dest);
312         gctl_ro_param(r, "geom", -1, buf);
313         /* gctl_dump(r, stdout); */
314         errstr = gctl_issue(r);
315         if (errstr != NULL)
316                 errx(1, "Detach of %s failed: %s", dest, errstr);
317         exit (0);
318 }
319
320 static void
321 cmd_open(struct g_bde_softc *sc, int dfd , const char *l_opt, u_int *nkey)
322 {
323         int error;
324         int ffd;
325         u_char keyloc[16];
326         u_int sectorsize;
327         off_t mediasize;
328         struct stat st;
329
330         error = ioctl(dfd, DIOCGSECTORSIZE, &sectorsize);
331         if (error)
332                 sectorsize = 512;
333         error = ioctl(dfd, DIOCGMEDIASIZE, &mediasize);
334         if (error) {
335                 error = fstat(dfd, &st);
336                 if (error == 0 && S_ISREG(st.st_mode))
337                         mediasize = st.st_size;
338                 else
339                         error = ENOENT;
340         }
341         if (error)
342                 mediasize = (off_t)-1;
343         if (l_opt != NULL) {
344                 ffd = open(l_opt, O_RDONLY, 0);
345                 if (ffd < 0)
346                         err(1, "%s", l_opt);
347                 read(ffd, keyloc, sizeof keyloc);
348                 close(ffd);
349         } else {
350                 memset(keyloc, 0, sizeof keyloc);
351         }
352
353         error = g_bde_decrypt_lock(sc, sc->sha2, keyloc, mediasize,
354             sectorsize, nkey);
355         if (error == ENOENT)
356                 errx(1, "Lock was destroyed.");
357         if (error == ESRCH)
358                 errx(1, "Lock was nuked.");
359         if (error == ENOTDIR)
360                 errx(1, "Lock not found");
361         if (error != 0)
362                 errx(1, "Error %d decrypting lock", error);
363         if (nkey)
364                 printf("Opened with key %u\n", 1 + *nkey);
365         return;
366 }
367
368 static void
369 cmd_nuke(struct g_bde_key *gl, int dfd , int key)
370 {
371         int i;
372         u_char *sbuf;
373         off_t offset, offset2;
374
375         sbuf = malloc(gl->sectorsize);
376         memset(sbuf, 0, gl->sectorsize);
377         offset = (gl->lsector[key] & ~(gl->sectorsize - 1));
378         offset2 = lseek(dfd, offset, SEEK_SET);
379         if (offset2 != offset)
380                 err(1, "lseek");
381         i = write(dfd, sbuf, gl->sectorsize);
382         free(sbuf);
383         if (i != (int)gl->sectorsize)
384                 err(1, "write");
385         printf("Nuked key %d\n", 1 + key);
386 }
387
388 static void
389 cmd_write(struct g_bde_key *gl, struct g_bde_softc *sc, int dfd , int key, const char *l_opt)
390 {
391         int i, ffd;
392         uint64_t off[2];
393         u_char keyloc[16];
394         u_char *sbuf, *q;
395         off_t offset, offset2;
396
397         sbuf = malloc(gl->sectorsize);
398         /*
399          * Find the byte-offset in the lock sector where we will put the lock
400          * data structure.  We can put it any random place as long as the
401          * structure fits.
402          */
403         for(;;) {
404                 random_bits(off, sizeof off);
405                 off[0] &= (gl->sectorsize - 1);
406                 if (off[0] + G_BDE_LOCKSIZE > gl->sectorsize)
407                         continue;
408                 break;
409         }
410
411         /* Add the sector offset in bytes */
412         off[0] += (gl->lsector[key] & ~(gl->sectorsize - 1));
413         gl->lsector[key] = off[0];
414
415         i = g_bde_keyloc_encrypt(sc->sha2, off[0], off[1], keyloc);
416         if (i)
417                 errx(1, "g_bde_keyloc_encrypt()");
418         if (l_opt != NULL) {
419                 ffd = open(l_opt, O_WRONLY | O_CREAT | O_TRUNC, 0600);
420                 if (ffd < 0)
421                         err(1, "%s", l_opt);
422                 write(ffd, keyloc, sizeof keyloc);
423                 close(ffd);
424         } else if (gl->flags & GBDE_F_SECT0) {
425                 offset2 = lseek(dfd, 0, SEEK_SET);
426                 if (offset2 != 0)
427                         err(1, "lseek");
428                 i = read(dfd, sbuf, gl->sectorsize);
429                 if (i != (int)gl->sectorsize)
430                         err(1, "read");
431                 memcpy(sbuf + key * 16, keyloc, sizeof keyloc);
432                 offset2 = lseek(dfd, 0, SEEK_SET);
433                 if (offset2 != 0)
434                         err(1, "lseek");
435                 i = write(dfd, sbuf, gl->sectorsize);
436                 if (i != (int)gl->sectorsize)
437                         err(1, "write");
438         } else {
439                 errx(1, "No -L option and no space in sector 0 for lockfile");
440         }
441
442         /* Allocate a sectorbuffer and fill it with random junk */
443         if (sbuf == NULL)
444                 err(1, "malloc");
445         random_bits(sbuf, gl->sectorsize);
446
447         /* Fill random bits in the spare field */
448         random_bits(gl->spare, sizeof(gl->spare));
449
450         /* Encode the structure where we want it */
451         q = sbuf + (off[0] % gl->sectorsize);
452         i = g_bde_encode_lock(sc->sha2, gl, q);
453         if (i < 0)
454                 errx(1, "programming error encoding lock");
455
456         encrypt_sector(q, G_BDE_LOCKSIZE, 256, sc->sha2 + 16);
457         offset = gl->lsector[key] & ~(gl->sectorsize - 1);
458         offset2 = lseek(dfd, offset, SEEK_SET);
459         if (offset2 != offset)
460                 err(1, "lseek");
461         i = write(dfd, sbuf, gl->sectorsize);
462         if (i != (int)gl->sectorsize)
463                 err(1, "write");
464         free(sbuf);
465 #if 0
466         printf("Wrote key %d at %jd\n", key, (intmax_t)offset);
467         printf("s0 = %jd\n", (intmax_t)gl->sector0);
468         printf("sN = %jd\n", (intmax_t)gl->sectorN);
469         printf("l[0] = %jd\n", (intmax_t)gl->lsector[0]);
470         printf("l[1] = %jd\n", (intmax_t)gl->lsector[1]);
471         printf("l[2] = %jd\n", (intmax_t)gl->lsector[2]);
472         printf("l[3] = %jd\n", (intmax_t)gl->lsector[3]);
473         printf("k = %jd\n", (intmax_t)gl->keyoffset);
474         printf("ss = %jd\n", (intmax_t)gl->sectorsize);
475 #endif
476 }
477
478 static void
479 cmd_destroy(struct g_bde_key *gl, int nkey)
480 {
481         int i;
482
483         bzero(&gl->sector0, sizeof gl->sector0);
484         bzero(&gl->sectorN, sizeof gl->sectorN);
485         bzero(&gl->keyoffset, sizeof gl->keyoffset);
486         gl->flags &= GBDE_F_SECT0;
487         bzero(gl->mkey, sizeof gl->mkey);
488         for (i = 0; i < G_BDE_MAXKEYS; i++)
489                 if (i != nkey)
490                         gl->lsector[i] = ~0;
491 }
492
493 static int
494 sorthelp(const void *a, const void *b)
495 {
496         const uint64_t *oa, *ob;
497
498         oa = a;
499         ob = b;
500         if (*oa > *ob)
501                 return 1;
502         if (*oa < *ob)
503                 return -1;
504         return 0;
505 }
506
507 static void
508 cmd_init(struct g_bde_key *gl, int dfd, const char *f_opt, int i_opt, const char *l_opt)
509 {
510         int i;
511         u_char *buf;
512         unsigned sector_size;
513         uint64_t        first_sector;
514         uint64_t        last_sector;
515         uint64_t        total_sectors;
516         off_t   off, off2;
517         unsigned nkeys;
518         const char *p;
519         char *q, cbuf[BUFSIZ];
520         unsigned u, u2;
521         uint64_t o;
522         properties      params;
523
524         bzero(gl, sizeof *gl);
525         if (f_opt != NULL) {
526                 i = open(f_opt, O_RDONLY);
527                 if (i < 0)
528                         err(1, "%s", f_opt);
529                 params = properties_read(i);
530                 close (i);
531         } else if (i_opt) {
532                 /* XXX: Polish */
533                 asprintf(&q, "%stemp.XXXXXXXXXX", _PATH_TMP);
534                 if (q == NULL)
535                         err(1, "asprintf");
536                 i = mkstemp(q);
537                 if (i < 0)
538                         err(1, "%s", q);
539                 write(i, template, strlen(template));
540                 close (i);
541                 p = getenv("EDITOR");
542                 if (p == NULL)
543                         p = "vi";
544                 if (snprintf(cbuf, sizeof(cbuf), "%s %s\n", p, q) >=
545                     (ssize_t)sizeof(cbuf)) {
546                         unlink(q);
547                         errx(1, "EDITOR is too long");
548                 }
549                 system(cbuf);
550                 i = open(q, O_RDONLY);
551                 if (i < 0)
552                         err(1, "%s", f_opt);
553                 params = properties_read(i);
554                 close (i);
555                 unlink(q);
556                 free(q);
557         } else {
558                 /* XXX: Hack */
559                 i = open(_PATH_DEVNULL, O_RDONLY);
560                 if (i < 0)
561                         err(1, "%s", _PATH_DEVNULL);
562                 params = properties_read(i);
563                 close (i);
564         }
565
566         /* <sector_size> */
567         p = property_find(params, "sector_size");
568         i = ioctl(dfd, DIOCGSECTORSIZE, &u);
569         if (p != NULL) {
570                 sector_size = strtoul(p, &q, 0);
571                 if (!*p || *q)
572                         errx(1, "sector_size not a proper number");
573         } else if (i == 0) {
574                 sector_size = u;
575         } else {
576                 errx(1, "Missing sector_size property");
577         }
578         if (sector_size & (sector_size - 1))
579                 errx(1, "sector_size not a power of 2");
580         if (sector_size < 512)
581                 errx(1, "sector_size is smaller than 512");
582         buf = malloc(sector_size);
583         if (buf == NULL)
584                 err(1, "Failed to malloc sector buffer");
585         gl->sectorsize = sector_size;
586
587         i = ioctl(dfd, DIOCGMEDIASIZE, &off);
588         if (i == 0) {
589                 first_sector = 0;
590                 total_sectors = off / sector_size;
591                 last_sector = total_sectors - 1;
592         } else {
593                 first_sector = 0;
594                 last_sector = 0;
595                 total_sectors = 0;
596         }
597
598         /* <first_sector> */
599         p = property_find(params, "first_sector");
600         if (p != NULL) {
601                 first_sector = strtoul(p, &q, 0);
602                 if (!*p || *q)
603                         errx(1, "first_sector not a proper number");
604         }
605
606         /* <last_sector> */
607         p = property_find(params, "last_sector");
608         if (p != NULL) {
609                 last_sector = strtoul(p, &q, 0);
610                 if (!*p || *q)
611                         errx(1, "last_sector not a proper number");
612                 if (last_sector <= first_sector)
613                         errx(1, "last_sector not larger than first_sector");
614                 total_sectors = last_sector + 1;
615         }
616
617         /* <total_sectors> */
618         p = property_find(params, "total_sectors");
619         if (p != NULL) {
620                 total_sectors = strtoul(p, &q, 0);
621                 if (!*p || *q)
622                         errx(1, "total_sectors not a proper number");
623                 if (last_sector == 0)
624                         last_sector = first_sector + total_sectors - 1;
625         }
626
627         if (l_opt == NULL && first_sector != 0)
628                 errx(1, "No -L new-lockfile argument and first_sector != 0");
629         else if (l_opt == NULL) {
630                 first_sector++;
631                 total_sectors--;
632                 gl->flags |= GBDE_F_SECT0;
633         }
634         gl->sector0 = first_sector * gl->sectorsize;
635
636         if (total_sectors != (last_sector - first_sector) + 1)
637                 errx(1, "total_sectors disagree with first_sector and last_sector");
638         if (total_sectors == 0)
639                 errx(1, "missing last_sector or total_sectors");
640
641         gl->sectorN = (last_sector + 1) * gl->sectorsize;
642
643         /* Find a random keyoffset */
644         random_bits(&o, sizeof o);
645         o %= (gl->sectorN - gl->sector0);
646         o &= ~(gl->sectorsize - 1);
647         gl->keyoffset = o;
648
649         /* <number_of_keys> */
650         p = property_find(params, "number_of_keys");
651         if (p != NULL) {
652                 nkeys = strtoul(p, &q, 0);
653                 if (!*p || *q)
654                         errx(1, "number_of_keys not a proper number");
655                 if (nkeys < 1 || nkeys > G_BDE_MAXKEYS)
656                         errx(1, "number_of_keys out of range");
657         } else {
658                 nkeys = 4;
659         }
660         for (u = 0; u < nkeys; u++) {
661                 for(;;) {
662                         do {
663                                 random_bits(&o, sizeof o);
664                                 o %= gl->sectorN;
665                                 o &= ~(gl->sectorsize - 1);
666                         } while(o < gl->sector0);
667                         for (u2 = 0; u2 < u; u2++)
668                                 if (o == gl->lsector[u2])
669                                         break;
670                         if (u2 < u)
671                                 continue;
672                         break;
673                 }
674                 gl->lsector[u] = o;
675         }
676         for (; u < G_BDE_MAXKEYS; u++) {
677                 do
678                         random_bits(&o, sizeof o);
679                 while (o < gl->sectorN);
680                 gl->lsector[u] = o;
681         }
682         qsort(gl->lsector, G_BDE_MAXKEYS, sizeof gl->lsector[0], sorthelp);
683
684         /* Flush sector zero if we use it for lockfile data */
685         if (gl->flags & GBDE_F_SECT0) {
686                 off2 = lseek(dfd, 0, SEEK_SET);
687                 if (off2 != 0)
688                         err(1, "lseek(2) to sector 0");
689                 random_bits(buf, sector_size);
690                 i = write(dfd, buf, sector_size);
691                 if (i != (int)sector_size)
692                         err(1, "write sector 0");
693         }
694
695         /* <random_flush> */
696         p = property_find(params, "random_flush");
697         if (p != NULL) {
698                 off = first_sector * sector_size;
699                 off2 = lseek(dfd, off, SEEK_SET);
700                 if (off2 != off)
701                         err(1, "lseek(2) to first_sector");
702                 off2 = last_sector * sector_size;
703                 while (off <= off2) {
704                         random_bits(buf, sector_size);
705                         i = write(dfd, buf, sector_size);
706                         if (i != (int)sector_size)
707                                 err(1, "write to $device_name");
708                         off += sector_size;
709                 }
710         }
711
712         random_bits(gl->mkey, sizeof gl->mkey);
713         random_bits(gl->salt, sizeof gl->salt);
714
715         return;
716 }
717
718 static enum action {
719         ACT_HUH,
720         ACT_ATTACH, ACT_DETACH,
721         ACT_INIT, ACT_SETKEY, ACT_DESTROY, ACT_NUKE
722 } action;
723
724 int
725 main(int argc, char **argv)
726 {
727         const char *opts;
728         const char *k_opt, *K_opt;
729         const char *l_opt, *L_opt;
730         const char *p_opt, *P_opt;
731         const char *f_opt;
732         char *dest;
733         int i_opt, n_opt, ch, dfd, doopen;
734         u_int nkey;
735         int i;
736         char *q, buf[BUFSIZ];
737         struct g_bde_key *gl;
738         struct g_bde_softc sc;
739
740         if (argc < 3)
741                 usage();
742
743         if (modfind("g_bde") < 0) {
744                 /* need to load the gbde module */
745                 if (kldload(GBDEMOD) < 0 || modfind("g_bde") < 0)
746                         err(1, GBDEMOD ": Kernel module not available");
747         }
748         doopen = 0;
749         if (!strcmp(argv[1], "attach")) {
750                 action = ACT_ATTACH;
751                 opts = "k:l:p:";
752         } else if (!strcmp(argv[1], "detach")) {
753                 action = ACT_DETACH;
754                 opts = "";
755         } else if (!strcmp(argv[1], "init")) {
756                 action = ACT_INIT;
757                 doopen = 1;
758                 opts = "f:iK:L:P:";
759         } else if (!strcmp(argv[1], "setkey")) {
760                 action = ACT_SETKEY;
761                 doopen = 1;
762                 opts = "k:K:l:L:n:p:P:";
763         } else if (!strcmp(argv[1], "destroy")) {
764                 action = ACT_DESTROY;
765                 doopen = 1;
766                 opts = "k:l:p:";
767         } else if (!strcmp(argv[1], "nuke")) {
768                 action = ACT_NUKE;
769                 doopen = 1;
770                 opts = "k:l:n:p:";
771         } else {
772                 usage();
773         }
774         argc--;
775         argv++;
776
777         dest = strdup(argv[1]);
778         argc--;
779         argv++;
780
781         p_opt = NULL;
782         P_opt = NULL;
783         k_opt = NULL;
784         K_opt = NULL;
785         l_opt = NULL;
786         L_opt = NULL;
787         f_opt = NULL;
788         n_opt = 0;
789         i_opt = 0;
790
791         while((ch = getopt(argc, argv, opts)) != -1)
792                 switch (ch) {
793                 case 'f':
794                         f_opt = optarg;
795                         break;
796                 case 'i':
797                         i_opt = !i_opt;
798                         break;
799                 case 'k':
800                         k_opt = optarg;
801                         break;
802                 case 'K':
803                         K_opt = optarg;
804                         break;
805                 case 'l':
806                         l_opt = optarg;
807                         break;
808                 case 'L':
809                         L_opt = optarg;
810                         break;
811                 case 'n':
812                         n_opt = strtoul(optarg, &q, 0);
813                         if (!*optarg || *q)
814                                 errx(1, "-n argument not numeric");
815                         if (n_opt < -1 || n_opt > G_BDE_MAXKEYS)
816                                 errx(1, "-n argument out of range");
817                         break;
818                 case 'p':
819                         p_opt = optarg;
820                         break;
821                 case 'P':
822                         P_opt = optarg;
823                         break;
824                 default:
825                         usage();
826                 }
827
828         if (doopen) {
829                 dfd = open(dest, O_RDWR);
830                 if (dfd < 0 && dest[0] != '/') {
831                         if (snprintf(buf, sizeof(buf), "%s%s",
832                             _PATH_DEV, dest) >= (ssize_t)sizeof(buf))
833                                 errno = ENAMETOOLONG;
834                         else
835                                 dfd = open(buf, O_RDWR);
836                 }
837                 if (dfd < 0)
838                         err(1, "%s", dest);
839         } else {
840                 if (!memcmp(dest, _PATH_DEV, strlen(_PATH_DEV)))
841                         strcpy(dest, dest + strlen(_PATH_DEV));
842         }
843
844         memset(&sc, 0, sizeof sc);
845         sc.consumer = (void *)&dfd;
846         gl = &sc.key;
847         switch(action) {
848         case ACT_ATTACH:
849                 setup_passphrase(&sc, 0, p_opt, k_opt);
850                 cmd_attach(&sc, dest, l_opt);
851                 break;
852         case ACT_DETACH:
853                 cmd_detach(dest);
854                 break;
855         case ACT_INIT:
856                 cmd_init(gl, dfd, f_opt, i_opt, L_opt);
857                 setup_passphrase(&sc, 1, P_opt, K_opt);
858                 cmd_write(gl, &sc, dfd, 0, L_opt);
859                 break;
860         case ACT_SETKEY:
861                 setup_passphrase(&sc, 0, p_opt, k_opt);
862                 cmd_open(&sc, dfd, l_opt, &nkey);
863                 if (n_opt == 0)
864                         n_opt = nkey + 1;
865                 setup_passphrase(&sc, 1, P_opt, K_opt);
866                 cmd_write(gl, &sc, dfd, n_opt - 1, L_opt);
867                 break;
868         case ACT_DESTROY:
869                 setup_passphrase(&sc, 0, p_opt, k_opt);
870                 cmd_open(&sc, dfd, l_opt, &nkey);
871                 cmd_destroy(gl, nkey);
872                 reset_passphrase(&sc);
873                 cmd_write(gl, &sc, dfd, nkey, l_opt);
874                 break;
875         case ACT_NUKE:
876                 setup_passphrase(&sc, 0, p_opt, k_opt);
877                 cmd_open(&sc, dfd, l_opt, &nkey);
878                 if (n_opt == 0)
879                         n_opt = nkey + 1;
880                 if (n_opt == -1) {
881                         for(i = 0; i < G_BDE_MAXKEYS; i++)
882                                 cmd_nuke(gl, dfd, i);
883                 } else {
884                                 cmd_nuke(gl, dfd, n_opt - 1);
885                 }
886                 break;
887         default:
888                 errx(1, "internal error");
889         }
890
891         return(0);
892 }