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