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: stable/10/sbin/gbde/gbde.c 314327 2017-02-27 08:27:38Z avg $
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 	/* gctl_dump(r, stdout); */
304 	errstr = gctl_issue(r);
305 	if (errstr != NULL)
306 		errx(1, "Attach to %s failed: %s", dest, errstr);
307 
308 	exit (0);
309 }
310 
311 static void
cmd_detach(const char * dest)312 cmd_detach(const char *dest)
313 {
314 	struct gctl_req *r;
315 	const char *errstr;
316 	char buf[BUFSIZ];
317 
318 	r = gctl_get_handle();
319 	gctl_ro_param(r, "verb", -1, "destroy geom");
320 	gctl_ro_param(r, "class", -1, "BDE");
321 	sprintf(buf, "%s.bde", dest);
322 	gctl_ro_param(r, "geom", -1, buf);
323 	/* gctl_dump(r, stdout); */
324 	errstr = gctl_issue(r);
325 	if (errstr != NULL)
326 		errx(1, "Detach of %s failed: %s", dest, errstr);
327 	exit (0);
328 }
329 
330 static void
cmd_open(struct g_bde_softc * sc,int dfd,const char * l_opt,u_int * nkey)331 cmd_open(struct g_bde_softc *sc, int dfd , const char *l_opt, u_int *nkey)
332 {
333 	int error;
334 	int ffd;
335 	u_char keyloc[16];
336 	u_int sectorsize;
337 	off_t mediasize;
338 	struct stat st;
339 
340 	error = ioctl(dfd, DIOCGSECTORSIZE, &sectorsize);
341 	if (error)
342 		sectorsize = 512;
343 	error = ioctl(dfd, DIOCGMEDIASIZE, &mediasize);
344 	if (error) {
345 		error = fstat(dfd, &st);
346 		if (error == 0 && S_ISREG(st.st_mode))
347 			mediasize = st.st_size;
348 		else
349 			error = ENOENT;
350 	}
351 	if (error)
352 		mediasize = (off_t)-1;
353 	if (l_opt != NULL) {
354 		ffd = open(l_opt, O_RDONLY, 0);
355 		if (ffd < 0)
356 			err(1, "%s", l_opt);
357 		read(ffd, keyloc, sizeof keyloc);
358 		close(ffd);
359 	} else {
360 		memset(keyloc, 0, sizeof keyloc);
361 	}
362 
363 	error = g_bde_decrypt_lock(sc, sc->sha2, keyloc, mediasize,
364 	    sectorsize, nkey);
365 	if (error == ENOENT)
366 		errx(1, "Lock was destroyed.");
367 	if (error == ESRCH)
368 		errx(1, "Lock was nuked.");
369 	if (error == ENOTDIR)
370 		errx(1, "Lock not found");
371 	if (error != 0)
372 		errx(1, "Error %d decrypting lock", error);
373 	if (nkey)
374 		printf("Opened with key %u\n", *nkey);
375 	return;
376 }
377 
378 static void
cmd_nuke(struct g_bde_key * gl,int dfd,int key)379 cmd_nuke(struct g_bde_key *gl, int dfd , int key)
380 {
381 	int i;
382 	u_char *sbuf;
383 	off_t offset, offset2;
384 
385 	sbuf = malloc(gl->sectorsize);
386 	memset(sbuf, 0, gl->sectorsize);
387 	offset = (gl->lsector[key] & ~(gl->sectorsize - 1));
388 	offset2 = lseek(dfd, offset, SEEK_SET);
389 	if (offset2 != offset)
390 		err(1, "lseek");
391 	i = write(dfd, sbuf, gl->sectorsize);
392 	free(sbuf);
393 	if (i != (int)gl->sectorsize)
394 		err(1, "write");
395 	printf("Nuked key %d\n", key);
396 }
397 
398 static void
cmd_write(struct g_bde_key * gl,struct g_bde_softc * sc,int dfd,int key,const char * l_opt)399 cmd_write(struct g_bde_key *gl, struct g_bde_softc *sc, int dfd , int key, const char *l_opt)
400 {
401 	int i, ffd;
402 	uint64_t off[2];
403 	u_char keyloc[16];
404 	u_char *sbuf, *q;
405 	off_t offset, offset2;
406 
407 	sbuf = malloc(gl->sectorsize);
408 	/*
409 	 * Find the byte-offset in the lock sector where we will put the lock
410 	 * data structure.  We can put it any random place as long as the
411 	 * structure fits.
412 	 */
413 	for(;;) {
414 		random_bits(off, sizeof off);
415 		off[0] &= (gl->sectorsize - 1);
416 		if (off[0] + G_BDE_LOCKSIZE > gl->sectorsize)
417 			continue;
418 		break;
419 	}
420 
421 	/* Add the sector offset in bytes */
422 	off[0] += (gl->lsector[key] & ~(gl->sectorsize - 1));
423 	gl->lsector[key] = off[0];
424 
425 	i = g_bde_keyloc_encrypt(sc->sha2, off[0], off[1], keyloc);
426 	if (i)
427 		errx(1, "g_bde_keyloc_encrypt()");
428 	if (l_opt != NULL) {
429 		ffd = open(l_opt, O_WRONLY | O_CREAT | O_TRUNC, 0600);
430 		if (ffd < 0)
431 			err(1, "%s", l_opt);
432 		write(ffd, keyloc, sizeof keyloc);
433 		close(ffd);
434 	} else if (gl->flags & GBDE_F_SECT0) {
435 		offset2 = lseek(dfd, 0, SEEK_SET);
436 		if (offset2 != 0)
437 			err(1, "lseek");
438 		i = read(dfd, sbuf, gl->sectorsize);
439 		if (i != (int)gl->sectorsize)
440 			err(1, "read");
441 		memcpy(sbuf + key * 16, keyloc, sizeof keyloc);
442 		offset2 = lseek(dfd, 0, SEEK_SET);
443 		if (offset2 != 0)
444 			err(1, "lseek");
445 		i = write(dfd, sbuf, gl->sectorsize);
446 		if (i != (int)gl->sectorsize)
447 			err(1, "write");
448 	} else {
449 		errx(1, "No -L option and no space in sector 0 for lockfile");
450 	}
451 
452 	/* Allocate a sectorbuffer and fill it with random junk */
453 	if (sbuf == NULL)
454 		err(1, "malloc");
455 	random_bits(sbuf, gl->sectorsize);
456 
457 	/* Fill random bits in the spare field */
458 	random_bits(gl->spare, sizeof(gl->spare));
459 
460 	/* Encode the structure where we want it */
461 	q = sbuf + (off[0] % gl->sectorsize);
462 	i = g_bde_encode_lock(sc->sha2, gl, q);
463 	if (i < 0)
464 		errx(1, "programming error encoding lock");
465 
466 	encrypt_sector(q, G_BDE_LOCKSIZE, 256, sc->sha2 + 16);
467 	offset = gl->lsector[key] & ~(gl->sectorsize - 1);
468 	offset2 = lseek(dfd, offset, SEEK_SET);
469 	if (offset2 != offset)
470 		err(1, "lseek");
471 	i = write(dfd, sbuf, gl->sectorsize);
472 	if (i != (int)gl->sectorsize)
473 		err(1, "write");
474 	free(sbuf);
475 #if 0
476 	printf("Wrote key %d at %jd\n", key, (intmax_t)offset);
477 	printf("s0 = %jd\n", (intmax_t)gl->sector0);
478 	printf("sN = %jd\n", (intmax_t)gl->sectorN);
479 	printf("l[0] = %jd\n", (intmax_t)gl->lsector[0]);
480 	printf("l[1] = %jd\n", (intmax_t)gl->lsector[1]);
481 	printf("l[2] = %jd\n", (intmax_t)gl->lsector[2]);
482 	printf("l[3] = %jd\n", (intmax_t)gl->lsector[3]);
483 	printf("k = %jd\n", (intmax_t)gl->keyoffset);
484 	printf("ss = %jd\n", (intmax_t)gl->sectorsize);
485 #endif
486 }
487 
488 static void
cmd_destroy(struct g_bde_key * gl,int nkey)489 cmd_destroy(struct g_bde_key *gl, int nkey)
490 {
491 	int i;
492 
493 	bzero(&gl->sector0, sizeof gl->sector0);
494 	bzero(&gl->sectorN, sizeof gl->sectorN);
495 	bzero(&gl->keyoffset, sizeof gl->keyoffset);
496 	bzero(&gl->flags, sizeof gl->flags);
497 	bzero(gl->mkey, sizeof gl->mkey);
498 	for (i = 0; i < G_BDE_MAXKEYS; i++)
499 		if (i != nkey)
500 			gl->lsector[i] = ~0;
501 }
502 
503 static int
sorthelp(const void * a,const void * b)504 sorthelp(const void *a, const void *b)
505 {
506 	const uint64_t *oa, *ob;
507 
508 	oa = a;
509 	ob = b;
510 	if (*oa > *ob)
511 		return 1;
512 	if (*oa < *ob)
513 		return -1;
514 	return 0;
515 }
516 
517 static void
cmd_init(struct g_bde_key * gl,int dfd,const char * f_opt,int i_opt,const char * l_opt)518 cmd_init(struct g_bde_key *gl, int dfd, const char *f_opt, int i_opt, const char *l_opt)
519 {
520 	int i;
521 	u_char *buf;
522 	unsigned sector_size;
523 	uint64_t	first_sector;
524 	uint64_t	last_sector;
525 	uint64_t	total_sectors;
526 	off_t	off, off2;
527 	unsigned nkeys;
528 	const char *p;
529 	char *q, cbuf[BUFSIZ];
530 	unsigned u, u2;
531 	uint64_t o;
532 	properties	params;
533 
534 	bzero(gl, sizeof *gl);
535 	if (f_opt != NULL) {
536 		i = open(f_opt, O_RDONLY);
537 		if (i < 0)
538 			err(1, "%s", f_opt);
539 		params = properties_read(i);
540 		close (i);
541 	} else if (i_opt) {
542 		/* XXX: Polish */
543 		asprintf(&q, "%stemp.XXXXXXXXXX", _PATH_TMP);
544 		if (q == NULL)
545 			err(1, "asprintf");
546 		i = mkstemp(q);
547 		if (i < 0)
548 			err(1, "%s", q);
549 		write(i, template, strlen(template));
550 		close (i);
551 		p = getenv("EDITOR");
552 		if (p == NULL)
553 			p = "vi";
554 		if (snprintf(cbuf, sizeof(cbuf), "%s %s\n", p, q) >=
555 		    (ssize_t)sizeof(cbuf)) {
556 			unlink(q);
557 			errx(1, "EDITOR is too long");
558 		}
559 		system(cbuf);
560 		i = open(q, O_RDONLY);
561 		if (i < 0)
562 			err(1, "%s", f_opt);
563 		params = properties_read(i);
564 		close (i);
565 		unlink(q);
566 		free(q);
567 	} else {
568 		/* XXX: Hack */
569 		i = open(_PATH_DEVNULL, O_RDONLY);
570 		if (i < 0)
571 			err(1, "%s", _PATH_DEVNULL);
572 		params = properties_read(i);
573 		close (i);
574 	}
575 
576 	/* <sector_size> */
577 	p = property_find(params, "sector_size");
578 	i = ioctl(dfd, DIOCGSECTORSIZE, &u);
579 	if (p != NULL) {
580 		sector_size = strtoul(p, &q, 0);
581 		if (!*p || *q)
582 			errx(1, "sector_size not a proper number");
583 	} else if (i == 0) {
584 		sector_size = u;
585 	} else {
586 		errx(1, "Missing sector_size property");
587 	}
588 	if (sector_size & (sector_size - 1))
589 		errx(1, "sector_size not a power of 2");
590 	if (sector_size < 512)
591 		errx(1, "sector_size is smaller than 512");
592 	buf = malloc(sector_size);
593 	if (buf == NULL)
594 		err(1, "Failed to malloc sector buffer");
595 	gl->sectorsize = sector_size;
596 
597 	i = ioctl(dfd, DIOCGMEDIASIZE, &off);
598 	if (i == 0) {
599 		first_sector = 0;
600 		total_sectors = off / sector_size;
601 		last_sector = total_sectors - 1;
602 	} else {
603 		first_sector = 0;
604 		last_sector = 0;
605 		total_sectors = 0;
606 	}
607 
608 	/* <first_sector> */
609 	p = property_find(params, "first_sector");
610 	if (p != NULL) {
611 		first_sector = strtoul(p, &q, 0);
612 		if (!*p || *q)
613 			errx(1, "first_sector not a proper number");
614 	}
615 
616 	/* <last_sector> */
617 	p = property_find(params, "last_sector");
618 	if (p != NULL) {
619 		last_sector = strtoul(p, &q, 0);
620 		if (!*p || *q)
621 			errx(1, "last_sector not a proper number");
622 		if (last_sector <= first_sector)
623 			errx(1, "last_sector not larger than first_sector");
624 		total_sectors = last_sector + 1;
625 	}
626 
627 	/* <total_sectors> */
628 	p = property_find(params, "total_sectors");
629 	if (p != NULL) {
630 		total_sectors = strtoul(p, &q, 0);
631 		if (!*p || *q)
632 			errx(1, "total_sectors not a proper number");
633 		if (last_sector == 0)
634 			last_sector = first_sector + total_sectors - 1;
635 	}
636 
637 	if (l_opt == NULL && first_sector != 0)
638 		errx(1, "No -L new-lockfile argument and first_sector != 0");
639 	else if (l_opt == NULL) {
640 		first_sector++;
641 		total_sectors--;
642 		gl->flags |= GBDE_F_SECT0;
643 	}
644 	gl->sector0 = first_sector * gl->sectorsize;
645 
646 	if (total_sectors != (last_sector - first_sector) + 1)
647 		errx(1, "total_sectors disagree with first_sector and last_sector");
648 	if (total_sectors == 0)
649 		errx(1, "missing last_sector or total_sectors");
650 
651 	gl->sectorN = (last_sector + 1) * gl->sectorsize;
652 
653 	/* Find a random keyoffset */
654 	random_bits(&o, sizeof o);
655 	o %= (gl->sectorN - gl->sector0);
656 	o &= ~(gl->sectorsize - 1);
657 	gl->keyoffset = o;
658 
659 	/* <number_of_keys> */
660 	p = property_find(params, "number_of_keys");
661 	if (p != NULL) {
662 		nkeys = strtoul(p, &q, 0);
663 		if (!*p || *q)
664 			errx(1, "number_of_keys not a proper number");
665 		if (nkeys < 1 || nkeys > G_BDE_MAXKEYS)
666 			errx(1, "number_of_keys out of range");
667 	} else {
668 		nkeys = 4;
669 	}
670 	for (u = 0; u < nkeys; u++) {
671 		for(;;) {
672 			do {
673 				random_bits(&o, sizeof o);
674 				o %= gl->sectorN;
675 				o &= ~(gl->sectorsize - 1);
676 			} while(o < gl->sector0);
677 			for (u2 = 0; u2 < u; u2++)
678 				if (o == gl->lsector[u2])
679 					break;
680 			if (u2 < u)
681 				continue;
682 			break;
683 		}
684 		gl->lsector[u] = o;
685 	}
686 	for (; u < G_BDE_MAXKEYS; u++) {
687 		do
688 			random_bits(&o, sizeof o);
689 		while (o < gl->sectorN);
690 		gl->lsector[u] = o;
691 	}
692 	qsort(gl->lsector, G_BDE_MAXKEYS, sizeof gl->lsector[0], sorthelp);
693 
694 	/* Flush sector zero if we use it for lockfile data */
695 	if (gl->flags & GBDE_F_SECT0) {
696 		off2 = lseek(dfd, 0, SEEK_SET);
697 		if (off2 != 0)
698 			err(1, "lseek(2) to sector 0");
699 		random_bits(buf, sector_size);
700 		i = write(dfd, buf, sector_size);
701 		if (i != (int)sector_size)
702 			err(1, "write sector 0");
703 	}
704 
705 	/* <random_flush> */
706 	p = property_find(params, "random_flush");
707 	if (p != NULL) {
708 		off = first_sector * sector_size;
709 		off2 = lseek(dfd, off, SEEK_SET);
710 		if (off2 != off)
711 			err(1, "lseek(2) to first_sector");
712 		off2 = last_sector * sector_size;
713 		while (off <= off2) {
714 			random_bits(buf, sector_size);
715 			i = write(dfd, buf, sector_size);
716 			if (i != (int)sector_size)
717 				err(1, "write to $device_name");
718 			off += sector_size;
719 		}
720 	}
721 
722 	random_bits(gl->mkey, sizeof gl->mkey);
723 	random_bits(gl->salt, sizeof gl->salt);
724 
725 	return;
726 }
727 
728 static enum action {
729 	ACT_HUH,
730 	ACT_ATTACH, ACT_DETACH,
731 	ACT_INIT, ACT_SETKEY, ACT_DESTROY, ACT_NUKE
732 } action;
733 
734 int
main(int argc,char ** argv)735 main(int argc, char **argv)
736 {
737 	const char *opts;
738 	const char *k_opt, *K_opt;
739 	const char *l_opt, *L_opt;
740 	const char *p_opt, *P_opt;
741 	const char *f_opt;
742 	char *dest;
743 	int i_opt, n_opt, ch, dfd, doopen;
744 	u_int nkey;
745 	int i;
746 	char *q, buf[BUFSIZ];
747 	struct g_bde_key *gl;
748 	struct g_bde_softc sc;
749 
750 	if (argc < 3)
751 		usage();
752 
753 	if (modfind("g_bde") < 0) {
754 		/* need to load the gbde module */
755 		if (kldload(GBDEMOD) < 0 || modfind("g_bde") < 0)
756 			err(1, GBDEMOD ": Kernel module not available");
757 	}
758 	doopen = 0;
759 	if (!strcmp(argv[1], "attach")) {
760 		action = ACT_ATTACH;
761 		opts = "k:l:p:";
762 	} else if (!strcmp(argv[1], "detach")) {
763 		action = ACT_DETACH;
764 		opts = "";
765 	} else if (!strcmp(argv[1], "init")) {
766 		action = ACT_INIT;
767 		doopen = 1;
768 		opts = "f:iK:L:P:";
769 	} else if (!strcmp(argv[1], "setkey")) {
770 		action = ACT_SETKEY;
771 		doopen = 1;
772 		opts = "k:K:l:L:n:p:P:";
773 	} else if (!strcmp(argv[1], "destroy")) {
774 		action = ACT_DESTROY;
775 		doopen = 1;
776 		opts = "k:l:p:";
777 	} else if (!strcmp(argv[1], "nuke")) {
778 		action = ACT_NUKE;
779 		doopen = 1;
780 		opts = "k:l:n:p:";
781 	} else {
782 		usage();
783 	}
784 	argc--;
785 	argv++;
786 
787 	dest = strdup(argv[1]);
788 	argc--;
789 	argv++;
790 
791 	p_opt = NULL;
792 	P_opt = NULL;
793 	k_opt = NULL;
794 	K_opt = NULL;
795 	l_opt = NULL;
796 	L_opt = NULL;
797 	f_opt = NULL;
798 	n_opt = 0;
799 	i_opt = 0;
800 
801 	while((ch = getopt(argc, argv, opts)) != -1)
802 		switch (ch) {
803 		case 'f':
804 			f_opt = optarg;
805 			break;
806 		case 'i':
807 			i_opt = !i_opt;
808 			break;
809 		case 'k':
810 			k_opt = optarg;
811 			break;
812 		case 'K':
813 			K_opt = optarg;
814 			break;
815 		case 'l':
816 			l_opt = optarg;
817 			break;
818 		case 'L':
819 			L_opt = optarg;
820 			break;
821 		case 'n':
822 			n_opt = strtoul(optarg, &q, 0);
823 			if (!*optarg || *q)
824 				errx(1, "-n argument not numeric");
825 			if (n_opt < -1 || n_opt > G_BDE_MAXKEYS)
826 				errx(1, "-n argument out of range");
827 			break;
828 		case 'p':
829 			p_opt = optarg;
830 			break;
831 		case 'P':
832 			P_opt = optarg;
833 			break;
834 		default:
835 			usage();
836 		}
837 
838 	if (doopen) {
839 		dfd = open(dest, O_RDWR);
840 		if (dfd < 0 && dest[0] != '/') {
841 			if (snprintf(buf, sizeof(buf), "%s%s",
842 			    _PATH_DEV, dest) >= (ssize_t)sizeof(buf))
843 				errno = ENAMETOOLONG;
844 			else
845 				dfd = open(buf, O_RDWR);
846 		}
847 		if (dfd < 0)
848 			err(1, "%s", dest);
849 	} else {
850 		if (!memcmp(dest, _PATH_DEV, strlen(_PATH_DEV)))
851 			strcpy(dest, dest + strlen(_PATH_DEV));
852 	}
853 
854 	memset(&sc, 0, sizeof sc);
855 	sc.consumer = (void *)&dfd;
856 	gl = &sc.key;
857 	switch(action) {
858 	case ACT_ATTACH:
859 		setup_passphrase(&sc, 0, p_opt, k_opt);
860 		cmd_attach(&sc, dest, l_opt);
861 		break;
862 	case ACT_DETACH:
863 		cmd_detach(dest);
864 		break;
865 	case ACT_INIT:
866 		cmd_init(gl, dfd, f_opt, i_opt, L_opt);
867 		setup_passphrase(&sc, 1, P_opt, K_opt);
868 		cmd_write(gl, &sc, dfd, 0, L_opt);
869 		break;
870 	case ACT_SETKEY:
871 		setup_passphrase(&sc, 0, p_opt, k_opt);
872 		cmd_open(&sc, dfd, l_opt, &nkey);
873 		if (n_opt == 0)
874 			n_opt = nkey + 1;
875 		setup_passphrase(&sc, 1, P_opt, K_opt);
876 		cmd_write(gl, &sc, dfd, n_opt - 1, L_opt);
877 		break;
878 	case ACT_DESTROY:
879 		setup_passphrase(&sc, 0, p_opt, k_opt);
880 		cmd_open(&sc, dfd, l_opt, &nkey);
881 		cmd_destroy(gl, nkey);
882 		reset_passphrase(&sc);
883 		cmd_write(gl, &sc, dfd, nkey, l_opt);
884 		break;
885 	case ACT_NUKE:
886 		setup_passphrase(&sc, 0, p_opt, k_opt);
887 		cmd_open(&sc, dfd, l_opt, &nkey);
888 		if (n_opt == 0)
889 			n_opt = nkey + 1;
890 		if (n_opt == -1) {
891 			for(i = 0; i < G_BDE_MAXKEYS; i++)
892 				cmd_nuke(gl, dfd, i);
893 		} else {
894 				cmd_nuke(gl, dfd, n_opt - 1);
895 		}
896 		break;
897 	default:
898 		errx(1, "internal error");
899 	}
900 
901 	return(0);
902 }
903