gbde.c revision 120877
1104476Ssam/*-
2139825Simp * Copyright (c) 2002 Poul-Henning Kamp
3104476Ssam * Copyright (c) 2002 Networks Associates Technology, Inc.
4247061Spjd * All rights reserved.
5247061Spjd *
6247061Spjd * This software was developed for the FreeBSD Project by Poul-Henning Kamp
7104476Ssam * and NAI Labs, the Security Research Division of Network Associates, Inc.
8104476Ssam * under DARPA/SPAWAR contract N66001-01-C-8035 ("CBOSS"), as part of the
9104476Ssam * DARPA CHATS research program.
10104476Ssam *
11104476Ssam * Redistribution and use in source and binary forms, with or without
12104476Ssam * modification, are permitted provided that the following conditions
13104476Ssam * are met:
14104476Ssam * 1. Redistributions of source code must retain the above copyright
15104476Ssam *    notice, this list of conditions and the following disclaimer.
16104476Ssam * 2. Redistributions in binary form must reproduce the above copyright
17104476Ssam *    notice, this list of conditions and the following disclaimer in the
18104476Ssam *    documentation and/or other materials provided with the distribution.
19247061Spjd *
20247061Spjd * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
21104476Ssam * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22104476Ssam * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23104476Ssam * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
24104476Ssam * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25104476Ssam * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26247061Spjd * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27275732Sjmg * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28275732Sjmg * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29247061Spjd * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30275732Sjmg * SUCH DAMAGE.
31275732Sjmg *
32275732Sjmg * $FreeBSD: head/sbin/gbde/gbde.c 120877 2003-10-07 09:29:59Z phk $
33275732Sjmg */
34104476Ssam
35104476Ssam#include <sys/types.h>
36104476Ssam#include <sys/queue.h>
37104476Ssam#include <sys/mutex.h>
38104476Ssam#include <md5.h>
39104476Ssam#include <readpassphrase.h>
40104476Ssam#include <string.h>
41104476Ssam#include <stdint.h>
42104476Ssam#include <unistd.h>
43104476Ssam#include <fcntl.h>
44104476Ssam#include <paths.h>
45104476Ssam#include <strings.h>
46104476Ssam#include <stdlib.h>
47104476Ssam#include <err.h>
48104476Ssam#include <stdio.h>
49104476Ssam#include <libutil.h>
50116191Sobrien#include <libgeom.h>
51116191Sobrien#include <sys/errno.h>
52116191Sobrien#include <sys/disk.h>
53292963Sallanjude#include <sys/stat.h>
54104476Ssam#include <crypto/rijndael/rijndael.h>
55213068Spjd#include <crypto/sha2/sha2.h>
56213068Spjd#include <sys/param.h>
57213068Spjd#include <sys/linker.h>
58213068Spjd
59213068Spjd#define GBDEMOD "geom_bde"
60213068Spjd#define KASSERT(foo, bar) do { if(!(foo)) { warn bar ; exit (1); } } while (0)
61104476Ssam
62213068Spjd#include <geom/geom.h>
63213068Spjd#include <geom/bde/g_bde.h>
64285526Sjmg
65213068Spjdextern const char template[];
66213068Spjd
67213068Spjd
68213068Spjd#if 0
69213068Spjdstatic void
70213068Spjdg_hexdump(void *ptr, int length)
71213068Spjd{
72104476Ssam	int i, j, k;
73104476Ssam	unsigned char *cp;
74104476Ssam
75104476Ssam	cp = ptr;
76213068Spjd	for (i = 0; i < length; i+= 16) {
77213068Spjd		printf("%04x  ", i);
78213068Spjd		for (j = 0; j < 16; j++) {
79213068Spjd			k = i + j;
80213068Spjd			if (k < length)
81213068Spjd				printf(" %02x", cp[k]);
82213068Spjd			else
83213068Spjd				printf("   ");
84213068Spjd		}
85213068Spjd		printf("  |");
86213068Spjd		for (j = 0; j < 16; j++) {
87213068Spjd			k = i + j;
88213068Spjd			if (k >= length)
89213068Spjd				printf(" ");
90213068Spjd			else if (cp[k] >= ' ' && cp[k] <= '~')
91213068Spjd				printf("%c", cp[k]);
92213068Spjd			else
93213068Spjd				printf(".");
94213068Spjd		}
95213068Spjd		printf("|\n");
96213068Spjd	}
97169425Sgnn}
98213068Spjd#endif
99213068Spjd
100213068Spjdstatic void __dead2
101213068Spjdusage(const char *reason)
102213068Spjd{
103213068Spjd	const char *p;
104213068Spjd
105213068Spjd	p = getprogname();
106213068Spjd	fprintf(stderr, "Usage error: %s", reason);
107213068Spjd	fprintf(stderr, "Usage:\n");
108213068Spjd	fprintf(stderr, "\t%s attach dest [-l lockfile]\n", p);
109213068Spjd	fprintf(stderr, "\t%s detach dest\n", p);
110213068Spjd	fprintf(stderr, "\t%s init /dev/dest [-i] [-f filename] [-L lockfile]\n", p);
111213068Spjd	fprintf(stderr, "\t%s setkey dest [-n key] [-l lockfile] [-L lockfile]\n", p);
112213068Spjd	fprintf(stderr, "\t%s destroy dest [-n key] [-l lockfile] [-L lockfile]\n", p);
113213068Spjd	exit (1);
114213068Spjd}
115213068Spjd
116213068Spjdvoid *
117213068Spjdg_read_data(struct g_consumer *cp, off_t offset, off_t length, int *error)
118213068Spjd{
119213068Spjd	void *p;
120213068Spjd	int fd, i;
121213068Spjd	off_t o2;
122213068Spjd
123213068Spjd	p = malloc(length);
124213068Spjd	if (p == NULL)
125213068Spjd		err(1, "malloc");
126292963Sallanjude	fd = *(int *)cp;
127213068Spjd	o2 = lseek(fd, offset, SEEK_SET);
128213068Spjd	if (o2 != offset)
129213068Spjd		err(1, "lseek");
130213068Spjd	i = read(fd, p, length);
131213068Spjd	if (i != length)
132292963Sallanjude		err(1, "read");
133213068Spjd	if (error != NULL)
134213068Spjd		error = 0;
135213068Spjd	return (p);
136213068Spjd}
137213068Spjd
138292963Sallanjudestatic void
139213068Spjdrandom_bits(void *p, u_int len)
140213068Spjd{
141213068Spjd	static int fdr = -1;
142213068Spjd	int i;
143213068Spjd
144213068Spjd	if (fdr < 0) {
145213068Spjd		fdr = open("/dev/urandom", O_RDONLY);
146292963Sallanjude		if (fdr < 0)
147213068Spjd			err(1, "/dev/urandom");
148213068Spjd	}
149213068Spjd
150213068Spjd	i = read(fdr, p, len);
151213068Spjd	if (i != (int)len)
152213068Spjd		err(1, "read from /dev/urandom");
153213068Spjd}
154213068Spjd
155213068Spjd/* XXX: not nice */
156213068Spjdstatic u_char sha2[SHA512_DIGEST_LENGTH];
157213068Spjd
158292963Sallanjudestatic void
159213068Spjdreset_passphrase(struct g_bde_softc *sc)
160213068Spjd{
161213068Spjd
162292963Sallanjude	memcpy(sc->sha2, sha2, SHA512_DIGEST_LENGTH);
163213068Spjd}
164213068Spjd
165static void
166setup_passphrase(struct g_bde_softc *sc, int sure, const char *input)
167{
168	char buf1[BUFSIZ], buf2[BUFSIZ], *p;
169
170	if (input != NULL) {
171		g_bde_hash_pass(sc, input, strlen(input));
172		memcpy(sha2, sc->sha2, SHA512_DIGEST_LENGTH);
173		return;
174	}
175	for (;;) {
176		p = readpassphrase(
177		    sure ? "Enter new passphrase:" : "Enter passphrase: ",
178		    buf1, sizeof buf1,
179		    RPP_ECHO_OFF | RPP_REQUIRE_TTY);
180		if (p == NULL)
181			err(1, "readpassphrase");
182
183		if (sure) {
184			p = readpassphrase("Reenter new passphrase: ",
185			    buf2, sizeof buf2,
186			    RPP_ECHO_OFF | RPP_REQUIRE_TTY);
187			if (p == NULL)
188				err(1, "readpassphrase");
189
190			if (strcmp(buf1, buf2)) {
191				printf("They didn't match.\n");
192				continue;
193			}
194		}
195		if (strlen(buf1) < 3) {
196			printf("Too short passphrase.\n");
197			continue;
198		}
199		break;
200	}
201	g_bde_hash_pass(sc, buf1, strlen(buf1));
202	memcpy(sha2, sc->sha2, SHA512_DIGEST_LENGTH);
203}
204
205static void
206encrypt_sector(void *d, int len, int klen, void *key)
207{
208	keyInstance ki;
209	cipherInstance ci;
210	int error;
211
212	error = rijndael_cipherInit(&ci, MODE_CBC, NULL);
213	if (error <= 0)
214		errx(1, "rijndael_cipherInit=%d", error);
215	error = rijndael_makeKey(&ki, DIR_ENCRYPT, klen, key);
216	if (error <= 0)
217		errx(1, "rijndael_makeKeY=%d", error);
218	error = rijndael_blockEncrypt(&ci, &ki, d, len * 8, d);
219	if (error <= 0)
220		errx(1, "rijndael_blockEncrypt=%d", error);
221}
222
223static void
224cmd_attach(const struct g_bde_softc *sc, const char *dest, const char *lfile)
225{
226	int ffd;
227	u_char buf[16];
228	struct gctl_req *r;
229	const char *errstr;
230
231	r = gctl_get_handle();
232	gctl_ro_param(r, "verb", -1, "create geom");
233	gctl_ro_param(r, "class", -1, "BDE");
234	gctl_ro_param(r, "provider", -1, dest);
235	gctl_ro_param(r, "pass", SHA512_DIGEST_LENGTH, sc->sha2);
236	if (lfile != NULL) {
237		ffd = open(lfile, O_RDONLY, 0);
238		if (ffd < 0)
239			err(1, "%s", lfile);
240		read(ffd, buf, 16);
241		gctl_ro_param(r, "key", 16, buf);
242		close(ffd);
243	}
244	/* gctl_dump(r, stdout); */
245	errstr = gctl_issue(r);
246	if (errstr != NULL)
247		errx(1, "Attach to %s failed: %s\n", dest, errstr);
248
249	exit (0);
250}
251
252static void
253cmd_detach(const char *dest)
254{
255	struct gctl_req *r;
256	const char *errstr;
257	char buf[BUFSIZ];
258
259	r = gctl_get_handle();
260	gctl_ro_param(r, "verb", -1, "destroy geom");
261	gctl_ro_param(r, "class", -1, "BDE");
262	sprintf(buf, "%s.bde", dest);
263	gctl_ro_param(r, "geom", -1, buf);
264	/* gctl_dump(r, stdout); */
265	errstr = gctl_issue(r);
266	if (errstr != NULL)
267		errx(1, "Detach of %s failed: %s\n", dest, errstr);
268	exit (0);
269}
270
271static void
272cmd_open(struct g_bde_softc *sc, int dfd , const char *l_opt, u_int *nkey)
273{
274	int error;
275	int ffd;
276	u_char keyloc[16];
277	u_int sectorsize;
278	off_t mediasize;
279	struct stat st;
280
281	error = ioctl(dfd, DIOCGSECTORSIZE, &sectorsize);
282	if (error)
283		sectorsize = 512;
284	error = ioctl(dfd, DIOCGMEDIASIZE, &mediasize);
285	if (error) {
286		error = fstat(dfd, &st);
287		if (error == 0 && S_ISREG(st.st_mode))
288			mediasize = st.st_size;
289		else
290			error = ENOENT;
291	}
292	if (error)
293		mediasize = (off_t)-1;
294	if (l_opt != NULL) {
295		ffd = open(l_opt, O_RDONLY, 0);
296		if (ffd < 0)
297			err(1, "%s", l_opt);
298		read(ffd, keyloc, sizeof keyloc);
299		close(ffd);
300	} else {
301		memset(keyloc, 0, sizeof keyloc);
302	}
303
304	error = g_bde_decrypt_lock(sc, sc->sha2, keyloc, mediasize,
305	    sectorsize, nkey);
306	if (error == ENOENT)
307		errx(1, "Lock was destroyed.");
308	if (error == ESRCH)
309		errx(1, "Lock was nuked.");
310	if (error == ENOTDIR)
311		errx(1, "Lock not found");
312	if (error != 0)
313		errx(1, "Error %d decrypting lock", error);
314	if (nkey)
315		printf("Opened with key %u\n", *nkey);
316	return;
317}
318
319static void
320cmd_nuke(struct g_bde_key *gl, int dfd , int key)
321{
322	int i;
323	u_char *sbuf;
324	off_t offset, offset2;
325
326	sbuf = malloc(gl->sectorsize);
327	memset(sbuf, 0, gl->sectorsize);
328	offset = (gl->lsector[key] & ~(gl->sectorsize - 1));
329	offset2 = lseek(dfd, offset, SEEK_SET);
330	if (offset2 != offset)
331		err(1, "lseek");
332	i = write(dfd, sbuf, gl->sectorsize);
333	if (i != (int)gl->sectorsize)
334		err(1, "write");
335	printf("Nuked key %d\n", key);
336}
337
338static void
339cmd_write(struct g_bde_key *gl, struct g_bde_softc *sc, int dfd , int key, const char *l_opt)
340{
341	int i, ffd;
342	uint64_t off[2];
343	u_char keyloc[16];
344	u_char *sbuf, *q;
345	off_t offset, offset2;
346
347	sbuf = malloc(gl->sectorsize);
348	/*
349	 * Find the byte-offset in the lock sector where we will put the lock
350	 * data structure.  We can put it any random place as long as the
351	 * structure fits.
352	 */
353	for(;;) {
354		random_bits(off, sizeof off);
355		off[0] &= (gl->sectorsize - 1);
356		if (off[0] + G_BDE_LOCKSIZE > gl->sectorsize)
357			continue;
358		break;
359	}
360
361	/* Add the sector offset in bytes */
362	off[0] += (gl->lsector[key] & ~(gl->sectorsize - 1));
363	gl->lsector[key] = off[0];
364
365	i = g_bde_keyloc_encrypt(sc->sha2, off[0], off[1], keyloc);
366	if (i)
367		errx(1, "g_bde_keyloc_encrypt()");
368	if (l_opt != NULL) {
369		ffd = open(l_opt, O_WRONLY | O_CREAT | O_TRUNC, 0600);
370		if (ffd < 0)
371			err(1, "%s", l_opt);
372		write(ffd, keyloc, sizeof keyloc);
373		close(ffd);
374	} else if (gl->flags & GBDE_F_SECT0) {
375		offset2 = lseek(dfd, 0, SEEK_SET);
376		if (offset2 != 0)
377			err(1, "lseek");
378		i = read(dfd, sbuf, gl->sectorsize);
379		if (i != (int)gl->sectorsize)
380			err(1, "read");
381		memcpy(sbuf + key * 16, keyloc, sizeof keyloc);
382		offset2 = lseek(dfd, 0, SEEK_SET);
383		if (offset2 != 0)
384			err(1, "lseek");
385		i = write(dfd, sbuf, gl->sectorsize);
386		if (i != (int)gl->sectorsize)
387			err(1, "write");
388	} else {
389		errx(1, "No -L option and no space in sector 0 for lockfile");
390	}
391
392	/* Allocate a sectorbuffer and fill it with random junk */
393	if (sbuf == NULL)
394		err(1, "malloc");
395	random_bits(sbuf, gl->sectorsize);
396
397	/* Fill random bits in the spare field */
398	random_bits(gl->spare, sizeof(gl->spare));
399
400	/* Encode the structure where we want it */
401	q = sbuf + (off[0] % gl->sectorsize);
402	i = g_bde_encode_lock(sc->sha2, gl, q);
403	if (i < 0)
404		errx(1, "programming error encoding lock");
405
406	encrypt_sector(q, G_BDE_LOCKSIZE, 256, sc->sha2 + 16);
407	offset = gl->lsector[key] & ~(gl->sectorsize - 1);
408	offset2 = lseek(dfd, offset, SEEK_SET);
409	if (offset2 != offset)
410		err(1, "lseek");
411	i = write(dfd, sbuf, gl->sectorsize);
412	if (i != (int)gl->sectorsize)
413		err(1, "write");
414	printf("Wrote key %d at %jd\n", key, (intmax_t)offset);
415#if 0
416	printf("s0 = %jd\n", (intmax_t)gl->sector0);
417	printf("sN = %jd\n", (intmax_t)gl->sectorN);
418	printf("l[0] = %jd\n", (intmax_t)gl->lsector[0]);
419	printf("l[1] = %jd\n", (intmax_t)gl->lsector[1]);
420	printf("l[2] = %jd\n", (intmax_t)gl->lsector[2]);
421	printf("l[3] = %jd\n", (intmax_t)gl->lsector[3]);
422	printf("k = %jd\n", (intmax_t)gl->keyoffset);
423	printf("ss = %jd\n", (intmax_t)gl->sectorsize);
424#endif
425}
426
427static void
428cmd_destroy(struct g_bde_key *gl, int nkey)
429{
430	int i;
431
432	bzero(&gl->sector0, sizeof gl->sector0);
433	bzero(&gl->sectorN, sizeof gl->sectorN);
434	bzero(&gl->keyoffset, sizeof gl->keyoffset);
435	bzero(&gl->flags, sizeof gl->flags);
436	bzero(gl->mkey, sizeof gl->mkey);
437	for (i = 0; i < G_BDE_MAXKEYS; i++)
438		if (i != nkey)
439			gl->lsector[i] = ~0;
440}
441
442static int
443sorthelp(const void *a, const void *b)
444{
445	const off_t *oa, *ob;
446
447	oa = a;
448	ob = b;
449	return (*oa > *ob);
450}
451
452static void
453cmd_init(struct g_bde_key *gl, int dfd, const char *f_opt, int i_opt, const char *l_opt)
454{
455	int i;
456	u_char *buf;
457	unsigned sector_size;
458	uint64_t	first_sector;
459	uint64_t	last_sector;
460	uint64_t	total_sectors;
461	off_t	off, off2;
462	unsigned nkeys;
463	const char *p;
464	char *q, cbuf[BUFSIZ];
465	unsigned u, u2;
466	uint64_t o;
467	properties	params;
468
469	bzero(gl, sizeof *gl);
470	if (f_opt != NULL) {
471		i = open(f_opt, O_RDONLY);
472		if (i < 0)
473			err(1, "%s", f_opt);
474		params = properties_read(i);
475		close (i);
476	} else {
477		/* XXX: Polish */
478		q = strdup("/tmp/temp.XXXXXXXXXX");
479		i = mkstemp(q);
480		if (i < 0)
481			err(1, "%s", q);
482		write(i, template, strlen(template));
483		close (i);
484		if (i_opt) {
485			p = getenv("EDITOR");
486			if (p == NULL)
487				p = "vi";
488			if (snprintf(cbuf, sizeof(cbuf), "%s %s\n", p, q) >=
489			    (ssize_t)sizeof(cbuf))
490				errx(1, "EDITOR is too long");
491			system(cbuf);
492		}
493		i = open(q, O_RDONLY);
494		if (i < 0)
495			err(1, "%s", f_opt);
496		params = properties_read(i);
497		close (i);
498		unlink(q);
499	}
500
501	/* <sector_size> */
502	p = property_find(params, "sector_size");
503	i = ioctl(dfd, DIOCGSECTORSIZE, &u);
504	if (p != NULL) {
505		sector_size = strtoul(p, &q, 0);
506		if (!*p || *q)
507			errx(1, "sector_size not a proper number");
508	} else if (i == 0) {
509		sector_size = u;
510	} else {
511		errx(1, "Missing sector_size property");
512	}
513	if (sector_size & (sector_size - 1))
514		errx(1, "sector_size not a power of 2");
515	if (sector_size < 512)
516		errx(1, "sector_size is smaller than 512");
517	buf = malloc(sector_size);
518	if (buf == NULL)
519		err(1, "Failed to malloc sector buffer");
520	gl->sectorsize = sector_size;
521
522	i = ioctl(dfd, DIOCGMEDIASIZE, &off);
523	if (i == 0) {
524		first_sector = 0;
525		total_sectors = off / sector_size;
526		last_sector = total_sectors - 1;
527	} else {
528		first_sector = 0;
529		last_sector = 0;
530		total_sectors = 0;
531	}
532
533	/* <first_sector> */
534	p = property_find(params, "first_sector");
535	if (p != NULL) {
536		first_sector = strtoul(p, &q, 0);
537		if (!*p || *q)
538			errx(1, "first_sector not a proper number");
539	}
540
541	/* <last_sector> */
542	p = property_find(params, "last_sector");
543	if (p != NULL) {
544		last_sector = strtoul(p, &q, 0);
545		if (!*p || *q)
546			errx(1, "last_sector not a proper number");
547		if (last_sector <= first_sector)
548			errx(1, "last_sector not larger than first_sector");
549		total_sectors = last_sector + 1;
550	}
551
552	/* <total_sectors> */
553	p = property_find(params, "total_sectors");
554	if (p != NULL) {
555		total_sectors = strtoul(p, &q, 0);
556		if (!*p || *q)
557			errx(1, "total_sectors not a proper number");
558		if (last_sector == 0)
559			last_sector = first_sector + total_sectors - 1;
560	}
561
562	if (l_opt == NULL && first_sector != 0)
563		errx(1, "No -L new-lockfile argument and first_sector != 0");
564	else if (l_opt == NULL) {
565		first_sector++;
566		total_sectors--;
567		gl->flags |= GBDE_F_SECT0;
568	}
569	gl->sector0 = first_sector * gl->sectorsize;
570
571	if (total_sectors != (last_sector - first_sector) + 1)
572		errx(1, "total_sectors disagree with first_sector and last_sector");
573	if (total_sectors == 0)
574		errx(1, "missing last_sector or total_sectors");
575
576	gl->sectorN = (last_sector + 1) * gl->sectorsize;
577
578	/* Find a random keyoffset */
579	random_bits(&o, sizeof o);
580	o %= (gl->sectorN - gl->sector0);
581	o &= ~(gl->sectorsize - 1);
582	gl->keyoffset = o;
583
584	/* <number_of_keys> */
585	p = property_find(params, "number_of_keys");
586	if (p == NULL)
587		errx(1, "Missing number_of_keys property");
588	nkeys = strtoul(p, &q, 0);
589	if (!*p || *q)
590		errx(1, "number_of_keys not a proper number");
591	if (nkeys < 1 || nkeys > G_BDE_MAXKEYS)
592		errx(1, "number_of_keys out of range");
593	for (u = 0; u < nkeys; u++) {
594		for(;;) {
595			do {
596				random_bits(&o, sizeof o);
597				o %= gl->sectorN;
598				o &= ~(gl->sectorsize - 1);
599			} while(o < gl->sector0);
600			for (u2 = 0; u2 < u; u2++)
601				if (o == gl->lsector[u2])
602					break;
603			if (u2 < u)
604				continue;
605			break;
606		}
607		gl->lsector[u] = o;
608	}
609	for (; u < G_BDE_MAXKEYS; u++) {
610		do
611			random_bits(&o, sizeof o);
612		while (o < gl->sectorN);
613		gl->lsector[u] = o;
614	}
615	qsort(gl->lsector, G_BDE_MAXKEYS, sizeof gl->lsector[0], sorthelp);
616
617	/* Flush sector zero if we use it for lockfile data */
618	if (gl->flags & GBDE_F_SECT0) {
619		off2 = lseek(dfd, 0, SEEK_SET);
620		if (off2 != 0)
621			err(1, "lseek(2) to sector 0");
622		random_bits(buf, sector_size);
623		i = write(dfd, buf, sector_size);
624		if (i != (int)sector_size)
625			err(1, "write sector 0");
626	}
627
628	/* <random_flush> */
629	p = property_find(params, "random_flush");
630	if (p != NULL) {
631		off = first_sector * sector_size;
632		off2 = lseek(dfd, off, SEEK_SET);
633		if (off2 != off)
634			err(1, "lseek(2) to first_sector");
635		off2 = last_sector * sector_size;
636		while (off <= off2) {
637			random_bits(buf, sector_size);
638			i = write(dfd, buf, sector_size);
639			if (i != (int)sector_size)
640				err(1, "write to $device_name");
641			off += sector_size;
642		}
643	}
644
645	random_bits(gl->mkey, sizeof gl->mkey);
646	random_bits(gl->salt, sizeof gl->salt);
647
648	return;
649}
650
651static enum action {
652	ACT_HUH,
653	ACT_ATTACH, ACT_DETACH,
654	ACT_INIT, ACT_SETKEY, ACT_DESTROY, ACT_NUKE
655} action;
656
657int
658main(int argc, char **argv)
659{
660	const char *opts;
661	const char *l_opt, *L_opt;
662	const char *p_opt, *P_opt;
663	const char *f_opt;
664	char *dest;
665	int i_opt, n_opt, ch, dfd, doopen;
666	u_int nkey;
667	int i;
668	char *q, buf[BUFSIZ];
669	struct g_bde_key *gl;
670	struct g_bde_softc sc;
671
672	if (argc < 3)
673		usage("Too few arguments\n");
674
675       if ((i = kldfind(GBDEMOD)) < 0) {
676               /* need to load the gbde module */
677               if (kldload(GBDEMOD) < 0 || kldfind(GBDEMOD) < 0) {
678                       usage(GBDEMOD ": Kernel module not available");
679               }
680       }
681	doopen = 0;
682	if (!strcmp(argv[1], "attach")) {
683		action = ACT_ATTACH;
684		opts = "l:p:";
685	} else if (!strcmp(argv[1], "detach")) {
686		action = ACT_DETACH;
687		opts = "";
688	} else if (!strcmp(argv[1], "init")) {
689		action = ACT_INIT;
690		doopen = 1;
691		opts = "f:iL:P:";
692	} else if (!strcmp(argv[1], "setkey")) {
693		action = ACT_SETKEY;
694		doopen = 1;
695		opts = "n:l:L:p:P:";
696	} else if (!strcmp(argv[1], "destroy")) {
697		action = ACT_DESTROY;
698		doopen = 1;
699		opts = "l:p:";
700	} else if (!strcmp(argv[1], "nuke")) {
701		action = ACT_NUKE;
702		doopen = 1;
703		opts = "l:p:n:";
704	} else {
705		usage("Unknown sub command\n");
706	}
707	argc--;
708	argv++;
709
710	dest = strdup(argv[1]);
711	argc--;
712	argv++;
713
714	p_opt = NULL;
715	P_opt = NULL;
716	l_opt = NULL;
717	L_opt = NULL;
718	f_opt = NULL;
719	n_opt = 0;
720	i_opt = 0;
721
722	while((ch = getopt(argc, argv, opts)) != -1)
723		switch (ch) {
724		case 'f':
725			f_opt = optarg;
726			break;
727		case 'i':
728			i_opt = !i_opt;
729		case 'l':
730			l_opt = optarg;
731			break;
732		case 'L':
733			L_opt = optarg;
734			break;
735		case 'p':
736			p_opt = optarg;
737			break;
738		case 'P':
739			P_opt = optarg;
740			break;
741		case 'n':
742			n_opt = strtoul(optarg, &q, 0);
743			if (!*optarg || *q)
744				usage("-n argument not numeric\n");
745			if (n_opt < -1 || n_opt > G_BDE_MAXKEYS)
746				usage("-n argument out of range\n"); break;
747		default:
748			usage("Invalid option\n");
749		}
750
751	if (doopen) {
752		dfd = open(dest, O_RDWR | O_CREAT, 0644);
753		if (dfd < 0) {
754			if (snprintf(buf, sizeof(buf), "%s%s",
755			    _PATH_DEV, dest) >= (ssize_t)sizeof(buf))
756				errno = ENAMETOOLONG;
757			else
758				dfd = open(buf, O_RDWR | O_CREAT, 0644);
759		}
760		if (dfd < 0)
761			err(1, "%s", dest);
762	} else {
763		if (!memcmp(dest, _PATH_DEV, strlen(_PATH_DEV)))
764			strcpy(dest, dest + strlen(_PATH_DEV));
765		if (strchr(dest, '/'))
766			usage("\"dest\" argument must be geom-name\n");
767	}
768
769	memset(&sc, 0, sizeof sc);
770	sc.consumer = (void *)&dfd;
771	gl = &sc.key;
772	switch(action) {
773	case ACT_ATTACH:
774		setup_passphrase(&sc, 0, p_opt);
775		cmd_attach(&sc, dest, l_opt);
776		break;
777	case ACT_DETACH:
778		cmd_detach(dest);
779		break;
780	case ACT_INIT:
781		cmd_init(gl, dfd, f_opt, i_opt, L_opt);
782		setup_passphrase(&sc, 1, P_opt);
783		cmd_write(gl, &sc, dfd, 0, L_opt);
784		break;
785	case ACT_SETKEY:
786		setup_passphrase(&sc, 0, p_opt);
787		cmd_open(&sc, dfd, l_opt, &nkey);
788		if (n_opt == 0)
789			n_opt = nkey + 1;
790		setup_passphrase(&sc, 1, P_opt);
791		cmd_write(gl, &sc, dfd, n_opt - 1, L_opt);
792		break;
793	case ACT_DESTROY:
794		setup_passphrase(&sc, 0, p_opt);
795		cmd_open(&sc, dfd, l_opt, &nkey);
796		cmd_destroy(gl, nkey);
797		reset_passphrase(&sc);
798		cmd_write(gl, &sc, dfd, nkey, l_opt);
799		break;
800	case ACT_NUKE:
801		setup_passphrase(&sc, 0, p_opt);
802		cmd_open(&sc, dfd, l_opt, &nkey);
803		if (n_opt == 0)
804			n_opt = nkey + 1;
805		if (n_opt == -1) {
806			for(i = 0; i < G_BDE_MAXKEYS; i++)
807				cmd_nuke(gl, dfd, i);
808		} else {
809				cmd_nuke(gl, dfd, n_opt - 1);
810		}
811		break;
812	default:
813		usage("Internal error\n");
814	}
815
816	return(0);
817}
818