gbde.c revision 125477
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: head/sbin/gbde/gbde.c 125477 2004-02-05 10:57:29Z des $
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
97extern const char template[];
98
99
100#if 0
101static void
102g_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
132static void __dead2
133usage(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
148void *
149g_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
170static void
171random_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 */
188static u_char sha2[SHA512_DIGEST_LENGTH];
189
190static void
191reset_passphrase(struct g_bde_softc *sc)
192{
193
194	memcpy(sc->sha2, sha2, SHA512_DIGEST_LENGTH);
195}
196
197static void
198setup_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
237static void
238encrypt_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
255static void
256cmd_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
284static void
285cmd_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
303static void
304cmd_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
351static void
352cmd_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
371static void
372cmd_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	printf("Wrote key %d at %jd\n", key, (intmax_t)offset);
448	free(sbuf);
449#if 0
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
461static void
462cmd_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
476static int
477sorthelp(const void *a, const void *b)
478{
479	const off_t *oa, *ob;
480
481	oa = a;
482	ob = b;
483	return (*oa > *ob);
484}
485
486static void
487cmd_init(struct g_bde_key *gl, int dfd, const char *f_opt, int i_opt, const char *l_opt)
488{
489	int i;
490	u_char *buf;
491	unsigned sector_size;
492	uint64_t	first_sector;
493	uint64_t	last_sector;
494	uint64_t	total_sectors;
495	off_t	off, off2;
496	unsigned nkeys;
497	const char *p;
498	char *q, cbuf[BUFSIZ];
499	unsigned u, u2;
500	uint64_t o;
501	properties	params;
502
503	bzero(gl, sizeof *gl);
504	if (f_opt != NULL) {
505		i = open(f_opt, O_RDONLY);
506		if (i < 0)
507			err(1, "%s", f_opt);
508		params = properties_read(i);
509		close (i);
510	} else if (i_opt) {
511		/* XXX: Polish */
512		asprintf(&q, "%stemp.XXXXXXXXXX", _PATH_TMP);
513		if (q == NULL)
514			err(1, "asprintf");
515		i = mkstemp(q);
516		if (i < 0)
517			err(1, "%s", q);
518		write(i, template, strlen(template));
519		close (i);
520		p = getenv("EDITOR");
521		if (p == NULL)
522			p = "vi";
523		if (snprintf(cbuf, sizeof(cbuf), "%s %s\n", p, q) >=
524		    (ssize_t)sizeof(cbuf)) {
525			unlink(q);
526			errx(1, "EDITOR is too long");
527		}
528		system(cbuf);
529		i = open(q, O_RDONLY);
530		if (i < 0)
531			err(1, "%s", f_opt);
532		params = properties_read(i);
533		close (i);
534		unlink(q);
535		free(q);
536	} else {
537		/* XXX: Hack */
538		i = open(_PATH_DEVNULL, O_RDONLY);
539		if (i < 0)
540			err(1, "%s", _PATH_DEVNULL);
541		params = properties_read(i);
542		close (i);
543	}
544
545	/* <sector_size> */
546	p = property_find(params, "sector_size");
547	i = ioctl(dfd, DIOCGSECTORSIZE, &u);
548	if (p != NULL) {
549		sector_size = strtoul(p, &q, 0);
550		if (!*p || *q)
551			errx(1, "sector_size not a proper number");
552	} else if (i == 0) {
553		sector_size = u;
554	} else {
555		errx(1, "Missing sector_size property");
556	}
557	if (sector_size & (sector_size - 1))
558		errx(1, "sector_size not a power of 2");
559	if (sector_size < 512)
560		errx(1, "sector_size is smaller than 512");
561	buf = malloc(sector_size);
562	if (buf == NULL)
563		err(1, "Failed to malloc sector buffer");
564	gl->sectorsize = sector_size;
565
566	i = ioctl(dfd, DIOCGMEDIASIZE, &off);
567	if (i == 0) {
568		first_sector = 0;
569		total_sectors = off / sector_size;
570		last_sector = total_sectors - 1;
571	} else {
572		first_sector = 0;
573		last_sector = 0;
574		total_sectors = 0;
575	}
576
577	/* <first_sector> */
578	p = property_find(params, "first_sector");
579	if (p != NULL) {
580		first_sector = strtoul(p, &q, 0);
581		if (!*p || *q)
582			errx(1, "first_sector not a proper number");
583	}
584
585	/* <last_sector> */
586	p = property_find(params, "last_sector");
587	if (p != NULL) {
588		last_sector = strtoul(p, &q, 0);
589		if (!*p || *q)
590			errx(1, "last_sector not a proper number");
591		if (last_sector <= first_sector)
592			errx(1, "last_sector not larger than first_sector");
593		total_sectors = last_sector + 1;
594	}
595
596	/* <total_sectors> */
597	p = property_find(params, "total_sectors");
598	if (p != NULL) {
599		total_sectors = strtoul(p, &q, 0);
600		if (!*p || *q)
601			errx(1, "total_sectors not a proper number");
602		if (last_sector == 0)
603			last_sector = first_sector + total_sectors - 1;
604	}
605
606	if (l_opt == NULL && first_sector != 0)
607		errx(1, "No -L new-lockfile argument and first_sector != 0");
608	else if (l_opt == NULL) {
609		first_sector++;
610		total_sectors--;
611		gl->flags |= GBDE_F_SECT0;
612	}
613	gl->sector0 = first_sector * gl->sectorsize;
614
615	if (total_sectors != (last_sector - first_sector) + 1)
616		errx(1, "total_sectors disagree with first_sector and last_sector");
617	if (total_sectors == 0)
618		errx(1, "missing last_sector or total_sectors");
619
620	gl->sectorN = (last_sector + 1) * gl->sectorsize;
621
622	/* Find a random keyoffset */
623	random_bits(&o, sizeof o);
624	o %= (gl->sectorN - gl->sector0);
625	o &= ~(gl->sectorsize - 1);
626	gl->keyoffset = o;
627
628	/* <number_of_keys> */
629	p = property_find(params, "number_of_keys");
630	if (p != NULL) {
631		nkeys = strtoul(p, &q, 0);
632		if (!*p || *q)
633			errx(1, "number_of_keys not a proper number");
634		if (nkeys < 1 || nkeys > G_BDE_MAXKEYS)
635			errx(1, "number_of_keys out of range");
636	} else {
637		nkeys = 4;
638	}
639	for (u = 0; u < nkeys; u++) {
640		for(;;) {
641			do {
642				random_bits(&o, sizeof o);
643				o %= gl->sectorN;
644				o &= ~(gl->sectorsize - 1);
645			} while(o < gl->sector0);
646			for (u2 = 0; u2 < u; u2++)
647				if (o == gl->lsector[u2])
648					break;
649			if (u2 < u)
650				continue;
651			break;
652		}
653		gl->lsector[u] = o;
654	}
655	for (; u < G_BDE_MAXKEYS; u++) {
656		do
657			random_bits(&o, sizeof o);
658		while (o < gl->sectorN);
659		gl->lsector[u] = o;
660	}
661	qsort(gl->lsector, G_BDE_MAXKEYS, sizeof gl->lsector[0], sorthelp);
662
663	/* Flush sector zero if we use it for lockfile data */
664	if (gl->flags & GBDE_F_SECT0) {
665		off2 = lseek(dfd, 0, SEEK_SET);
666		if (off2 != 0)
667			err(1, "lseek(2) to sector 0");
668		random_bits(buf, sector_size);
669		i = write(dfd, buf, sector_size);
670		if (i != (int)sector_size)
671			err(1, "write sector 0");
672	}
673
674	/* <random_flush> */
675	p = property_find(params, "random_flush");
676	if (p != NULL) {
677		off = first_sector * sector_size;
678		off2 = lseek(dfd, off, SEEK_SET);
679		if (off2 != off)
680			err(1, "lseek(2) to first_sector");
681		off2 = last_sector * sector_size;
682		while (off <= off2) {
683			random_bits(buf, sector_size);
684			i = write(dfd, buf, sector_size);
685			if (i != (int)sector_size)
686				err(1, "write to $device_name");
687			off += sector_size;
688		}
689	}
690
691	random_bits(gl->mkey, sizeof gl->mkey);
692	random_bits(gl->salt, sizeof gl->salt);
693
694	return;
695}
696
697static enum action {
698	ACT_HUH,
699	ACT_ATTACH, ACT_DETACH,
700	ACT_INIT, ACT_SETKEY, ACT_DESTROY, ACT_NUKE
701} action;
702
703int
704main(int argc, char **argv)
705{
706	const char *opts;
707	const char *l_opt, *L_opt;
708	const char *p_opt, *P_opt;
709	const char *f_opt;
710	char *dest;
711	int i_opt, n_opt, ch, dfd, doopen;
712	u_int nkey;
713	int i;
714	char *q, buf[BUFSIZ];
715	struct g_bde_key *gl;
716	struct g_bde_softc sc;
717
718	if (argc < 3)
719		usage("Too few arguments\n");
720
721       if ((i = modfind("g_bde")) < 0) {
722	       /* need to load the gbde module */
723	       if (kldload(GBDEMOD) < 0 || modfind("g_bde") < 0) {
724		       usage(GBDEMOD ": Kernel module not available");
725	       }
726       }
727	doopen = 0;
728	if (!strcmp(argv[1], "attach")) {
729		action = ACT_ATTACH;
730		opts = "l:p:";
731	} else if (!strcmp(argv[1], "detach")) {
732		action = ACT_DETACH;
733		opts = "";
734	} else if (!strcmp(argv[1], "init")) {
735		action = ACT_INIT;
736		doopen = 1;
737		opts = "f:iL:P:";
738	} else if (!strcmp(argv[1], "setkey")) {
739		action = ACT_SETKEY;
740		doopen = 1;
741		opts = "n:l:L:p:P:";
742	} else if (!strcmp(argv[1], "destroy")) {
743		action = ACT_DESTROY;
744		doopen = 1;
745		opts = "l:p:";
746	} else if (!strcmp(argv[1], "nuke")) {
747		action = ACT_NUKE;
748		doopen = 1;
749		opts = "l:p:n:";
750	} else {
751		usage("Unknown sub command\n");
752	}
753	argc--;
754	argv++;
755
756	dest = strdup(argv[1]);
757	argc--;
758	argv++;
759
760	p_opt = NULL;
761	P_opt = NULL;
762	l_opt = NULL;
763	L_opt = NULL;
764	f_opt = NULL;
765	n_opt = 0;
766	i_opt = 0;
767
768	while((ch = getopt(argc, argv, opts)) != -1)
769		switch (ch) {
770		case 'f':
771			f_opt = optarg;
772			break;
773		case 'i':
774			i_opt = !i_opt;
775		case 'l':
776			l_opt = optarg;
777			break;
778		case 'L':
779			L_opt = optarg;
780			break;
781		case 'p':
782			p_opt = optarg;
783			break;
784		case 'P':
785			P_opt = optarg;
786			break;
787		case 'n':
788			n_opt = strtoul(optarg, &q, 0);
789			if (!*optarg || *q)
790				usage("-n argument not numeric\n");
791			if (n_opt < -1 || n_opt > G_BDE_MAXKEYS)
792				usage("-n argument out of range\n"); break;
793		default:
794			usage("Invalid option\n");
795		}
796
797	if (doopen) {
798		dfd = open(dest, O_RDWR | O_CREAT, 0644);
799		if (dfd < 0) {
800			if (snprintf(buf, sizeof(buf), "%s%s",
801			    _PATH_DEV, dest) >= (ssize_t)sizeof(buf))
802				errno = ENAMETOOLONG;
803			else
804				dfd = open(buf, O_RDWR | O_CREAT, 0644);
805		}
806		if (dfd < 0)
807			err(1, "%s", dest);
808	} else {
809		if (!memcmp(dest, _PATH_DEV, strlen(_PATH_DEV)))
810			strcpy(dest, dest + strlen(_PATH_DEV));
811		if (strchr(dest, '/'))
812			usage("\"dest\" argument must be geom-name\n");
813	}
814
815	memset(&sc, 0, sizeof sc);
816	sc.consumer = (void *)&dfd;
817	gl = &sc.key;
818	switch(action) {
819	case ACT_ATTACH:
820		setup_passphrase(&sc, 0, p_opt);
821		cmd_attach(&sc, dest, l_opt);
822		break;
823	case ACT_DETACH:
824		cmd_detach(dest);
825		break;
826	case ACT_INIT:
827		cmd_init(gl, dfd, f_opt, i_opt, L_opt);
828		setup_passphrase(&sc, 1, P_opt);
829		cmd_write(gl, &sc, dfd, 0, L_opt);
830		break;
831	case ACT_SETKEY:
832		setup_passphrase(&sc, 0, p_opt);
833		cmd_open(&sc, dfd, l_opt, &nkey);
834		if (n_opt == 0)
835			n_opt = nkey + 1;
836		setup_passphrase(&sc, 1, P_opt);
837		cmd_write(gl, &sc, dfd, n_opt - 1, L_opt);
838		break;
839	case ACT_DESTROY:
840		setup_passphrase(&sc, 0, p_opt);
841		cmd_open(&sc, dfd, l_opt, &nkey);
842		cmd_destroy(gl, nkey);
843		reset_passphrase(&sc);
844		cmd_write(gl, &sc, dfd, nkey, l_opt);
845		break;
846	case ACT_NUKE:
847		setup_passphrase(&sc, 0, p_opt);
848		cmd_open(&sc, dfd, l_opt, &nkey);
849		if (n_opt == 0)
850			n_opt = nkey + 1;
851		if (n_opt == -1) {
852			for(i = 0; i < G_BDE_MAXKEYS; i++)
853				cmd_nuke(gl, dfd, i);
854		} else {
855				cmd_nuke(gl, dfd, n_opt - 1);
856		}
857		break;
858	default:
859		usage("Internal error\n");
860	}
861
862	return(0);
863}
864