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