xref: /NextBSD/sbin/gbde/gbde.c (revision 4557fabb34e865d7f40be64b39c9e34fa41dbb60)
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-api-fst.h>
87 #include <crypto/sha2/sha512.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
usage(void)133 usage(void)
134 {
135 
136 	(void)fprintf(stderr,
137 "usage: gbde attach destination [-k keyfile] [-l lockfile] [-p pass-phrase]\n"
138 "       gbde detach destination\n"
139 "       gbde init destination [-i] [-f filename] [-K new-keyfile]\n"
140 "            [-L new-lockfile] [-P new-pass-phrase]\n"
141 "       gbde setkey destination [-n key]\n"
142 "            [-k keyfile] [-l lockfile] [-p pass-phrase]\n"
143 "            [-K new-keyfile] [-L new-lockfile] [-P new-pass-phrase]\n"
144 "       gbde nuke destination [-n key]\n"
145 "            [-k keyfile] [-l lockfile] [-p pass-phrase]\n"
146 "       gbde destroy destination [-k keyfile] [-l lockfile] [-p pass-phrase]\n");
147 	exit(1);
148 }
149 
150 void *
g_read_data(struct g_consumer * cp,off_t offset,off_t length,int * error)151 g_read_data(struct g_consumer *cp, off_t offset, off_t length, int *error)
152 {
153 	void *p;
154 	int fd, i;
155 	off_t o2;
156 
157 	p = malloc(length);
158 	if (p == NULL)
159 		err(1, "malloc");
160 	fd = *(int *)cp;
161 	o2 = lseek(fd, offset, SEEK_SET);
162 	if (o2 != offset)
163 		err(1, "lseek");
164 	i = read(fd, p, length);
165 	if (i != length)
166 		err(1, "read");
167 	if (error != NULL)
168 		error = 0;
169 	return (p);
170 }
171 
172 static void
random_bits(void * p,u_int len)173 random_bits(void *p, u_int len)
174 {
175 	static int fdr = -1;
176 	int i;
177 
178 	if (fdr < 0) {
179 		fdr = open("/dev/urandom", O_RDONLY);
180 		if (fdr < 0)
181 			err(1, "/dev/urandom");
182 	}
183 
184 	i = read(fdr, p, len);
185 	if (i != (int)len)
186 		err(1, "read from /dev/urandom");
187 }
188 
189 /* XXX: not nice */
190 static u_char sha2[SHA512_DIGEST_LENGTH];
191 
192 static void
reset_passphrase(struct g_bde_softc * sc)193 reset_passphrase(struct g_bde_softc *sc)
194 {
195 
196 	memcpy(sc->sha2, sha2, SHA512_DIGEST_LENGTH);
197 }
198 
199 static void
setup_passphrase(struct g_bde_softc * sc,int sure,const char * input,const char * keyfile)200 setup_passphrase(struct g_bde_softc *sc, int sure, const char *input,
201     const char *keyfile)
202 {
203 	char buf1[BUFSIZ + SHA512_DIGEST_LENGTH];
204 	char buf2[BUFSIZ + SHA512_DIGEST_LENGTH];
205 	char *p;
206 	int kfd, klen, bpos = 0;
207 
208 	if (keyfile != NULL) {
209 		/* Read up to BUFSIZ bytes from keyfile */
210 		kfd = open(keyfile, O_RDONLY, 0);
211 		if (kfd < 0)
212 			err(1, "%s", keyfile);
213 		klen = read(kfd, buf1, BUFSIZ);
214 		if (klen == -1)
215 			err(1, "%s", keyfile);
216 		close(kfd);
217 
218 		/* Prepend the passphrase with the hash of the key read */
219 		g_bde_hash_pass(sc, buf1, klen);
220 		memcpy(buf1, sc->sha2, SHA512_DIGEST_LENGTH);
221 		memcpy(buf2, sc->sha2, SHA512_DIGEST_LENGTH);
222 		bpos = SHA512_DIGEST_LENGTH;
223 	}
224 
225 	if (input != NULL) {
226 		if (strlen(input) >= BUFSIZ)
227 			errx(1, "Passphrase too long");
228 		strcpy(buf1 + bpos, input);
229 
230 		g_bde_hash_pass(sc, buf1, strlen(buf1 + bpos) + bpos);
231 		memcpy(sha2, sc->sha2, SHA512_DIGEST_LENGTH);
232 		return;
233 	}
234 	for (;;) {
235 		p = readpassphrase(
236 		    sure ? "Enter new passphrase:" : "Enter passphrase: ",
237 		    buf1 + bpos, sizeof buf1 - bpos,
238 		    RPP_ECHO_OFF | RPP_REQUIRE_TTY);
239 		if (p == NULL)
240 			err(1, "readpassphrase");
241 
242 		if (sure) {
243 			p = readpassphrase("Reenter new passphrase: ",
244 			    buf2 + bpos, sizeof buf2 - bpos,
245 			    RPP_ECHO_OFF | RPP_REQUIRE_TTY);
246 			if (p == NULL)
247 				err(1, "readpassphrase");
248 
249 			if (strcmp(buf1 + bpos, buf2 + bpos)) {
250 				printf("They didn't match.\n");
251 				continue;
252 			}
253 		}
254 		if (strlen(buf1 + bpos) < 3) {
255 			printf("Too short passphrase.\n");
256 			continue;
257 		}
258 		break;
259 	}
260 	g_bde_hash_pass(sc, buf1, strlen(buf1 + bpos) + bpos);
261 	memcpy(sha2, sc->sha2, SHA512_DIGEST_LENGTH);
262 }
263 
264 static void
encrypt_sector(void * d,int len,int klen,void * key)265 encrypt_sector(void *d, int len, int klen, void *key)
266 {
267 	keyInstance ki;
268 	cipherInstance ci;
269 	int error;
270 
271 	error = rijndael_cipherInit(&ci, MODE_CBC, NULL);
272 	if (error <= 0)
273 		errx(1, "rijndael_cipherInit=%d", error);
274 	error = rijndael_makeKey(&ki, DIR_ENCRYPT, klen, key);
275 	if (error <= 0)
276 		errx(1, "rijndael_makeKeY=%d", error);
277 	error = rijndael_blockEncrypt(&ci, &ki, d, len * 8, d);
278 	if (error <= 0)
279 		errx(1, "rijndael_blockEncrypt=%d", error);
280 }
281 
282 static void
cmd_attach(const struct g_bde_softc * sc,const char * dest,const char * lfile)283 cmd_attach(const struct g_bde_softc *sc, const char *dest, const char *lfile)
284 {
285 	int ffd;
286 	u_char buf[16];
287 	struct gctl_req *r;
288 	const char *errstr;
289 
290 	r = gctl_get_handle();
291 	gctl_ro_param(r, "verb", -1, "create geom");
292 	gctl_ro_param(r, "class", -1, "BDE");
293 	gctl_ro_param(r, "provider", -1, dest);
294 	gctl_ro_param(r, "pass", SHA512_DIGEST_LENGTH, sc->sha2);
295 	if (lfile != NULL) {
296 		ffd = open(lfile, O_RDONLY, 0);
297 		if (ffd < 0)
298 			err(1, "%s", lfile);
299 		read(ffd, buf, 16);
300 		gctl_ro_param(r, "key", 16, buf);
301 		close(ffd);
302 	}
303 	errstr = gctl_issue(r);
304 	if (errstr != NULL)
305 		errx(1, "Attach to %s failed: %s", dest, errstr);
306 
307 	exit (0);
308 }
309 
310 static void
cmd_detach(const char * dest)311 cmd_detach(const char *dest)
312 {
313 	struct gctl_req *r;
314 	const char *errstr;
315 	char buf[BUFSIZ];
316 
317 	r = gctl_get_handle();
318 	gctl_ro_param(r, "verb", -1, "destroy geom");
319 	gctl_ro_param(r, "class", -1, "BDE");
320 	sprintf(buf, "%s.bde", dest);
321 	gctl_ro_param(r, "geom", -1, buf);
322 	/* gctl_dump(r, stdout); */
323 	errstr = gctl_issue(r);
324 	if (errstr != NULL)
325 		errx(1, "Detach of %s failed: %s", dest, errstr);
326 	exit (0);
327 }
328 
329 static void
cmd_open(struct g_bde_softc * sc,int dfd,const char * l_opt,u_int * nkey)330 cmd_open(struct g_bde_softc *sc, int dfd , const char *l_opt, u_int *nkey)
331 {
332 	int error;
333 	int ffd;
334 	u_char keyloc[16];
335 	u_int sectorsize;
336 	off_t mediasize;
337 	struct stat st;
338 
339 	error = ioctl(dfd, DIOCGSECTORSIZE, &sectorsize);
340 	if (error)
341 		sectorsize = 512;
342 	error = ioctl(dfd, DIOCGMEDIASIZE, &mediasize);
343 	if (error) {
344 		error = fstat(dfd, &st);
345 		if (error == 0 && S_ISREG(st.st_mode))
346 			mediasize = st.st_size;
347 		else
348 			error = ENOENT;
349 	}
350 	if (error)
351 		mediasize = (off_t)-1;
352 	if (l_opt != NULL) {
353 		ffd = open(l_opt, O_RDONLY, 0);
354 		if (ffd < 0)
355 			err(1, "%s", l_opt);
356 		read(ffd, keyloc, sizeof keyloc);
357 		close(ffd);
358 	} else {
359 		memset(keyloc, 0, sizeof keyloc);
360 	}
361 
362 	error = g_bde_decrypt_lock(sc, sc->sha2, keyloc, mediasize,
363 	    sectorsize, nkey);
364 	if (error == ENOENT)
365 		errx(1, "Lock was destroyed.");
366 	if (error == ESRCH)
367 		errx(1, "Lock was nuked.");
368 	if (error == ENOTDIR)
369 		errx(1, "Lock not found");
370 	if (error != 0)
371 		errx(1, "Error %d decrypting lock", error);
372 	if (nkey)
373 		printf("Opened with key %u\n", 1 + *nkey);
374 	return;
375 }
376 
377 static void
cmd_nuke(struct g_bde_key * gl,int dfd,int key)378 cmd_nuke(struct g_bde_key *gl, int dfd , int key)
379 {
380 	int i;
381 	u_char *sbuf;
382 	off_t offset, offset2;
383 
384 	sbuf = malloc(gl->sectorsize);
385 	memset(sbuf, 0, gl->sectorsize);
386 	offset = (gl->lsector[key] & ~(gl->sectorsize - 1));
387 	offset2 = lseek(dfd, offset, SEEK_SET);
388 	if (offset2 != offset)
389 		err(1, "lseek");
390 	i = write(dfd, sbuf, gl->sectorsize);
391 	free(sbuf);
392 	if (i != (int)gl->sectorsize)
393 		err(1, "write");
394 	printf("Nuked key %d\n", 1 + key);
395 }
396 
397 static void
cmd_write(struct g_bde_key * gl,struct g_bde_softc * sc,int dfd,int key,const char * l_opt)398 cmd_write(struct g_bde_key *gl, struct g_bde_softc *sc, int dfd , int key, const char *l_opt)
399 {
400 	int i, ffd;
401 	uint64_t off[2];
402 	u_char keyloc[16];
403 	u_char *sbuf, *q;
404 	off_t offset, offset2;
405 
406 	sbuf = malloc(gl->sectorsize);
407 	/*
408 	 * Find the byte-offset in the lock sector where we will put the lock
409 	 * data structure.  We can put it any random place as long as the
410 	 * structure fits.
411 	 */
412 	for(;;) {
413 		random_bits(off, sizeof off);
414 		off[0] &= (gl->sectorsize - 1);
415 		if (off[0] + G_BDE_LOCKSIZE > gl->sectorsize)
416 			continue;
417 		break;
418 	}
419 
420 	/* Add the sector offset in bytes */
421 	off[0] += (gl->lsector[key] & ~(gl->sectorsize - 1));
422 	gl->lsector[key] = off[0];
423 
424 	i = g_bde_keyloc_encrypt(sc->sha2, off[0], off[1], keyloc);
425 	if (i)
426 		errx(1, "g_bde_keyloc_encrypt()");
427 	if (l_opt != NULL) {
428 		ffd = open(l_opt, O_WRONLY | O_CREAT | O_TRUNC, 0600);
429 		if (ffd < 0)
430 			err(1, "%s", l_opt);
431 		write(ffd, keyloc, sizeof keyloc);
432 		close(ffd);
433 	} else if (gl->flags & GBDE_F_SECT0) {
434 		offset2 = lseek(dfd, 0, SEEK_SET);
435 		if (offset2 != 0)
436 			err(1, "lseek");
437 		i = read(dfd, sbuf, gl->sectorsize);
438 		if (i != (int)gl->sectorsize)
439 			err(1, "read");
440 		memcpy(sbuf + key * 16, keyloc, sizeof keyloc);
441 		offset2 = lseek(dfd, 0, SEEK_SET);
442 		if (offset2 != 0)
443 			err(1, "lseek");
444 		i = write(dfd, sbuf, gl->sectorsize);
445 		if (i != (int)gl->sectorsize)
446 			err(1, "write");
447 	} else {
448 		errx(1, "No -L option and no space in sector 0 for lockfile");
449 	}
450 
451 	/* Allocate a sectorbuffer and fill it with random junk */
452 	if (sbuf == NULL)
453 		err(1, "malloc");
454 	random_bits(sbuf, gl->sectorsize);
455 
456 	/* Fill random bits in the spare field */
457 	random_bits(gl->spare, sizeof(gl->spare));
458 
459 	/* Encode the structure where we want it */
460 	q = sbuf + (off[0] % gl->sectorsize);
461 	i = g_bde_encode_lock(sc->sha2, gl, q);
462 	if (i < 0)
463 		errx(1, "programming error encoding lock");
464 
465 	encrypt_sector(q, G_BDE_LOCKSIZE, 256, sc->sha2 + 16);
466 	offset = gl->lsector[key] & ~(gl->sectorsize - 1);
467 	offset2 = lseek(dfd, offset, SEEK_SET);
468 	if (offset2 != offset)
469 		err(1, "lseek");
470 	i = write(dfd, sbuf, gl->sectorsize);
471 	if (i != (int)gl->sectorsize)
472 		err(1, "write");
473 	free(sbuf);
474 #if 0
475 	printf("Wrote key %d at %jd\n", key, (intmax_t)offset);
476 	printf("s0 = %jd\n", (intmax_t)gl->sector0);
477 	printf("sN = %jd\n", (intmax_t)gl->sectorN);
478 	printf("l[0] = %jd\n", (intmax_t)gl->lsector[0]);
479 	printf("l[1] = %jd\n", (intmax_t)gl->lsector[1]);
480 	printf("l[2] = %jd\n", (intmax_t)gl->lsector[2]);
481 	printf("l[3] = %jd\n", (intmax_t)gl->lsector[3]);
482 	printf("k = %jd\n", (intmax_t)gl->keyoffset);
483 	printf("ss = %jd\n", (intmax_t)gl->sectorsize);
484 #endif
485 }
486 
487 static void
cmd_destroy(struct g_bde_key * gl,int nkey)488 cmd_destroy(struct g_bde_key *gl, int nkey)
489 {
490 	int i;
491 
492 	bzero(&gl->sector0, sizeof gl->sector0);
493 	bzero(&gl->sectorN, sizeof gl->sectorN);
494 	bzero(&gl->keyoffset, sizeof gl->keyoffset);
495 	gl->flags &= GBDE_F_SECT0;
496 	bzero(gl->mkey, sizeof gl->mkey);
497 	for (i = 0; i < G_BDE_MAXKEYS; i++)
498 		if (i != nkey)
499 			gl->lsector[i] = ~0;
500 }
501 
502 static int
sorthelp(const void * a,const void * b)503 sorthelp(const void *a, const void *b)
504 {
505 	const uint64_t *oa, *ob;
506 
507 	oa = a;
508 	ob = b;
509 	if (*oa > *ob)
510 		return 1;
511 	if (*oa < *ob)
512 		return -1;
513 	return 0;
514 }
515 
516 static void
cmd_init(struct g_bde_key * gl,int dfd,const char * f_opt,int i_opt,const char * l_opt)517 cmd_init(struct g_bde_key *gl, int dfd, const char *f_opt, int i_opt, const char *l_opt)
518 {
519 	int i;
520 	u_char *buf;
521 	unsigned sector_size;
522 	uint64_t	first_sector;
523 	uint64_t	last_sector;
524 	uint64_t	total_sectors;
525 	off_t	off, off2;
526 	unsigned nkeys;
527 	const char *p;
528 	char *q, cbuf[BUFSIZ];
529 	unsigned u, u2;
530 	uint64_t o;
531 	properties	params;
532 
533 	bzero(gl, sizeof *gl);
534 	if (f_opt != NULL) {
535 		i = open(f_opt, O_RDONLY);
536 		if (i < 0)
537 			err(1, "%s", f_opt);
538 		params = properties_read(i);
539 		close (i);
540 	} else if (i_opt) {
541 		/* XXX: Polish */
542 		asprintf(&q, "%stemp.XXXXXXXXXX", _PATH_TMP);
543 		if (q == NULL)
544 			err(1, "asprintf");
545 		i = mkstemp(q);
546 		if (i < 0)
547 			err(1, "%s", q);
548 		write(i, template, strlen(template));
549 		close (i);
550 		p = getenv("EDITOR");
551 		if (p == NULL)
552 			p = "vi";
553 		if (snprintf(cbuf, sizeof(cbuf), "%s %s\n", p, q) >=
554 		    (ssize_t)sizeof(cbuf)) {
555 			unlink(q);
556 			errx(1, "EDITOR is too long");
557 		}
558 		system(cbuf);
559 		i = open(q, O_RDONLY);
560 		if (i < 0)
561 			err(1, "%s", f_opt);
562 		params = properties_read(i);
563 		close (i);
564 		unlink(q);
565 		free(q);
566 	} else {
567 		/* XXX: Hack */
568 		i = open(_PATH_DEVNULL, O_RDONLY);
569 		if (i < 0)
570 			err(1, "%s", _PATH_DEVNULL);
571 		params = properties_read(i);
572 		close (i);
573 	}
574 
575 	/* <sector_size> */
576 	p = property_find(params, "sector_size");
577 	i = ioctl(dfd, DIOCGSECTORSIZE, &u);
578 	if (p != NULL) {
579 		sector_size = strtoul(p, &q, 0);
580 		if (!*p || *q)
581 			errx(1, "sector_size not a proper number");
582 	} else if (i == 0) {
583 		sector_size = u;
584 	} else {
585 		errx(1, "Missing sector_size property");
586 	}
587 	if (sector_size & (sector_size - 1))
588 		errx(1, "sector_size not a power of 2");
589 	if (sector_size < 512)
590 		errx(1, "sector_size is smaller than 512");
591 	buf = malloc(sector_size);
592 	if (buf == NULL)
593 		err(1, "Failed to malloc sector buffer");
594 	gl->sectorsize = sector_size;
595 
596 	i = ioctl(dfd, DIOCGMEDIASIZE, &off);
597 	if (i == 0) {
598 		first_sector = 0;
599 		total_sectors = off / sector_size;
600 		last_sector = total_sectors - 1;
601 	} else {
602 		first_sector = 0;
603 		last_sector = 0;
604 		total_sectors = 0;
605 	}
606 
607 	/* <first_sector> */
608 	p = property_find(params, "first_sector");
609 	if (p != NULL) {
610 		first_sector = strtoul(p, &q, 0);
611 		if (!*p || *q)
612 			errx(1, "first_sector not a proper number");
613 	}
614 
615 	/* <last_sector> */
616 	p = property_find(params, "last_sector");
617 	if (p != NULL) {
618 		last_sector = strtoul(p, &q, 0);
619 		if (!*p || *q)
620 			errx(1, "last_sector not a proper number");
621 		if (last_sector <= first_sector)
622 			errx(1, "last_sector not larger than first_sector");
623 		total_sectors = last_sector + 1;
624 	}
625 
626 	/* <total_sectors> */
627 	p = property_find(params, "total_sectors");
628 	if (p != NULL) {
629 		total_sectors = strtoul(p, &q, 0);
630 		if (!*p || *q)
631 			errx(1, "total_sectors not a proper number");
632 		if (last_sector == 0)
633 			last_sector = first_sector + total_sectors - 1;
634 	}
635 
636 	if (l_opt == NULL && first_sector != 0)
637 		errx(1, "No -L new-lockfile argument and first_sector != 0");
638 	else if (l_opt == NULL) {
639 		first_sector++;
640 		total_sectors--;
641 		gl->flags |= GBDE_F_SECT0;
642 	}
643 	gl->sector0 = first_sector * gl->sectorsize;
644 
645 	if (total_sectors != (last_sector - first_sector) + 1)
646 		errx(1, "total_sectors disagree with first_sector and last_sector");
647 	if (total_sectors == 0)
648 		errx(1, "missing last_sector or total_sectors");
649 
650 	gl->sectorN = (last_sector + 1) * gl->sectorsize;
651 
652 	/* Find a random keyoffset */
653 	random_bits(&o, sizeof o);
654 	o %= (gl->sectorN - gl->sector0);
655 	o &= ~(gl->sectorsize - 1);
656 	gl->keyoffset = o;
657 
658 	/* <number_of_keys> */
659 	p = property_find(params, "number_of_keys");
660 	if (p != NULL) {
661 		nkeys = strtoul(p, &q, 0);
662 		if (!*p || *q)
663 			errx(1, "number_of_keys not a proper number");
664 		if (nkeys < 1 || nkeys > G_BDE_MAXKEYS)
665 			errx(1, "number_of_keys out of range");
666 	} else {
667 		nkeys = 4;
668 	}
669 	for (u = 0; u < nkeys; u++) {
670 		for(;;) {
671 			do {
672 				random_bits(&o, sizeof o);
673 				o %= gl->sectorN;
674 				o &= ~(gl->sectorsize - 1);
675 			} while(o < gl->sector0);
676 			for (u2 = 0; u2 < u; u2++)
677 				if (o == gl->lsector[u2])
678 					break;
679 			if (u2 < u)
680 				continue;
681 			break;
682 		}
683 		gl->lsector[u] = o;
684 	}
685 	for (; u < G_BDE_MAXKEYS; u++) {
686 		do
687 			random_bits(&o, sizeof o);
688 		while (o < gl->sectorN);
689 		gl->lsector[u] = o;
690 	}
691 	qsort(gl->lsector, G_BDE_MAXKEYS, sizeof gl->lsector[0], sorthelp);
692 
693 	/* Flush sector zero if we use it for lockfile data */
694 	if (gl->flags & GBDE_F_SECT0) {
695 		off2 = lseek(dfd, 0, SEEK_SET);
696 		if (off2 != 0)
697 			err(1, "lseek(2) to sector 0");
698 		random_bits(buf, sector_size);
699 		i = write(dfd, buf, sector_size);
700 		if (i != (int)sector_size)
701 			err(1, "write sector 0");
702 	}
703 
704 	/* <random_flush> */
705 	p = property_find(params, "random_flush");
706 	if (p != NULL) {
707 		off = first_sector * sector_size;
708 		off2 = lseek(dfd, off, SEEK_SET);
709 		if (off2 != off)
710 			err(1, "lseek(2) to first_sector");
711 		off2 = last_sector * sector_size;
712 		while (off <= off2) {
713 			random_bits(buf, sector_size);
714 			i = write(dfd, buf, sector_size);
715 			if (i != (int)sector_size)
716 				err(1, "write to $device_name");
717 			off += sector_size;
718 		}
719 	}
720 
721 	random_bits(gl->mkey, sizeof gl->mkey);
722 	random_bits(gl->salt, sizeof gl->salt);
723 
724 	return;
725 }
726 
727 static enum action {
728 	ACT_HUH,
729 	ACT_ATTACH, ACT_DETACH,
730 	ACT_INIT, ACT_SETKEY, ACT_DESTROY, ACT_NUKE
731 } action;
732 
733 int
main(int argc,char ** argv)734 main(int argc, char **argv)
735 {
736 	const char *opts;
737 	const char *k_opt, *K_opt;
738 	const char *l_opt, *L_opt;
739 	const char *p_opt, *P_opt;
740 	const char *f_opt;
741 	char *dest;
742 	int i_opt, n_opt, ch, dfd, doopen;
743 	u_int nkey;
744 	int i;
745 	char *q, buf[BUFSIZ];
746 	struct g_bde_key *gl;
747 	struct g_bde_softc sc;
748 
749 	if (argc < 3)
750 		usage();
751 
752 	if (modfind("g_bde") < 0) {
753 		/* need to load the gbde module */
754 		if (kldload(GBDEMOD) < 0 || modfind("g_bde") < 0)
755 			err(1, GBDEMOD ": Kernel module not available");
756 	}
757 	doopen = 0;
758 	if (!strcmp(argv[1], "attach")) {
759 		action = ACT_ATTACH;
760 		opts = "k:l:p:";
761 	} else if (!strcmp(argv[1], "detach")) {
762 		action = ACT_DETACH;
763 		opts = "";
764 	} else if (!strcmp(argv[1], "init")) {
765 		action = ACT_INIT;
766 		doopen = 1;
767 		opts = "f:iK:L:P:";
768 	} else if (!strcmp(argv[1], "setkey")) {
769 		action = ACT_SETKEY;
770 		doopen = 1;
771 		opts = "k:K:l:L:n:p:P:";
772 	} else if (!strcmp(argv[1], "destroy")) {
773 		action = ACT_DESTROY;
774 		doopen = 1;
775 		opts = "k:l:p:";
776 	} else if (!strcmp(argv[1], "nuke")) {
777 		action = ACT_NUKE;
778 		doopen = 1;
779 		opts = "k:l:n:p:";
780 	} else {
781 		usage();
782 	}
783 	argc--;
784 	argv++;
785 
786 	dest = strdup(argv[1]);
787 	argc--;
788 	argv++;
789 
790 	p_opt = NULL;
791 	P_opt = NULL;
792 	k_opt = NULL;
793 	K_opt = NULL;
794 	l_opt = NULL;
795 	L_opt = NULL;
796 	f_opt = NULL;
797 	n_opt = 0;
798 	i_opt = 0;
799 
800 	while((ch = getopt(argc, argv, opts)) != -1)
801 		switch (ch) {
802 		case 'f':
803 			f_opt = optarg;
804 			break;
805 		case 'i':
806 			i_opt = !i_opt;
807 			break;
808 		case 'k':
809 			k_opt = optarg;
810 			break;
811 		case 'K':
812 			K_opt = optarg;
813 			break;
814 		case 'l':
815 			l_opt = optarg;
816 			break;
817 		case 'L':
818 			L_opt = optarg;
819 			break;
820 		case 'n':
821 			n_opt = strtoul(optarg, &q, 0);
822 			if (!*optarg || *q)
823 				errx(1, "-n argument not numeric");
824 			if (n_opt < -1 || n_opt > G_BDE_MAXKEYS)
825 				errx(1, "-n argument out of range");
826 			break;
827 		case 'p':
828 			p_opt = optarg;
829 			break;
830 		case 'P':
831 			P_opt = optarg;
832 			break;
833 		default:
834 			usage();
835 		}
836 
837 	if (doopen) {
838 		dfd = open(dest, O_RDWR);
839 		if (dfd < 0 && dest[0] != '/') {
840 			if (snprintf(buf, sizeof(buf), "%s%s",
841 			    _PATH_DEV, dest) >= (ssize_t)sizeof(buf))
842 				errno = ENAMETOOLONG;
843 			else
844 				dfd = open(buf, O_RDWR);
845 		}
846 		if (dfd < 0)
847 			err(1, "%s", dest);
848 	} else {
849 		if (!memcmp(dest, _PATH_DEV, strlen(_PATH_DEV)))
850 			strcpy(dest, dest + strlen(_PATH_DEV));
851 	}
852 
853 	memset(&sc, 0, sizeof sc);
854 	sc.consumer = (void *)&dfd;
855 	gl = &sc.key;
856 	switch(action) {
857 	case ACT_ATTACH:
858 		setup_passphrase(&sc, 0, p_opt, k_opt);
859 		cmd_attach(&sc, dest, l_opt);
860 		break;
861 	case ACT_DETACH:
862 		cmd_detach(dest);
863 		break;
864 	case ACT_INIT:
865 		cmd_init(gl, dfd, f_opt, i_opt, L_opt);
866 		setup_passphrase(&sc, 1, P_opt, K_opt);
867 		cmd_write(gl, &sc, dfd, 0, L_opt);
868 		break;
869 	case ACT_SETKEY:
870 		setup_passphrase(&sc, 0, p_opt, k_opt);
871 		cmd_open(&sc, dfd, l_opt, &nkey);
872 		if (n_opt == 0)
873 			n_opt = nkey + 1;
874 		setup_passphrase(&sc, 1, P_opt, K_opt);
875 		cmd_write(gl, &sc, dfd, n_opt - 1, L_opt);
876 		break;
877 	case ACT_DESTROY:
878 		setup_passphrase(&sc, 0, p_opt, k_opt);
879 		cmd_open(&sc, dfd, l_opt, &nkey);
880 		cmd_destroy(gl, nkey);
881 		reset_passphrase(&sc);
882 		cmd_write(gl, &sc, dfd, nkey, l_opt);
883 		break;
884 	case ACT_NUKE:
885 		setup_passphrase(&sc, 0, p_opt, k_opt);
886 		cmd_open(&sc, dfd, l_opt, &nkey);
887 		if (n_opt == 0)
888 			n_opt = nkey + 1;
889 		if (n_opt == -1) {
890 			for(i = 0; i < G_BDE_MAXKEYS; i++)
891 				cmd_nuke(gl, dfd, i);
892 		} else {
893 				cmd_nuke(gl, dfd, n_opt - 1);
894 		}
895 		break;
896 	default:
897 		errx(1, "internal error");
898 	}
899 
900 	return(0);
901 }
902