geom_eli.c revision 167229
1/*-
2 * Copyright (c) 2004-2006 Pawel Jakub Dawidek <pjd@FreeBSD.org>
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 *
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
15 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
18 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24 * SUCH DAMAGE.
25 */
26
27#include <sys/cdefs.h>
28__FBSDID("$FreeBSD: head/sbin/geom/class/eli/geom_eli.c 167229 2007-03-05 12:41:44Z pjd $");
29
30#include <stdio.h>
31#include <stdint.h>
32#include <stdlib.h>
33#include <unistd.h>
34#include <fcntl.h>
35#include <readpassphrase.h>
36#include <string.h>
37#include <strings.h>
38#include <libgeom.h>
39#include <paths.h>
40#include <errno.h>
41#include <assert.h>
42
43#include <sys/param.h>
44#include <sys/mman.h>
45#include <sys/resource.h>
46#include <opencrypto/cryptodev.h>
47#include <geom/eli/g_eli.h>
48#include <geom/eli/pkcs5v2.h>
49
50#include "core/geom.h"
51#include "misc/subr.h"
52
53
54uint32_t lib_version = G_LIB_VERSION;
55uint32_t version = G_ELI_VERSION;
56
57static char aalgo[] = "none";
58static char ealgo[] = "aes";
59static intmax_t keylen = 0;
60static intmax_t keyno = -1;
61static intmax_t iterations = -1;
62static intmax_t sectorsize = 0;
63static char keyfile[] = "", newkeyfile[] = "";
64
65static void eli_main(struct gctl_req *req, unsigned flags);
66static void eli_init(struct gctl_req *req);
67static void eli_attach(struct gctl_req *req);
68static void eli_configure(struct gctl_req *req);
69static void eli_setkey(struct gctl_req *req);
70static void eli_delkey(struct gctl_req *req);
71static void eli_kill(struct gctl_req *req);
72static void eli_backup(struct gctl_req *req);
73static void eli_restore(struct gctl_req *req);
74static void eli_clear(struct gctl_req *req);
75static void eli_dump(struct gctl_req *req);
76
77/*
78 * Available commands:
79 *
80 * init [-bhPv] [-a aalgo] [-e ealgo] [-i iterations] [-l keylen] [-K newkeyfile] prov
81 * label - alias for 'init'
82 * attach [-dprv] [-k keyfile] prov
83 * detach [-fl] prov ...
84 * stop - alias for 'detach'
85 * onetime [-d] [-a aalgo] [-e ealgo] [-l keylen] prov ...
86 * configure [-bB] prov ...
87 * setkey [-pPv] [-n keyno] [-k keyfile] [-K newkeyfile] prov
88 * delkey [-afv] [-n keyno] prov
89 * kill [-av] [prov ...]
90 * backup [-v] prov file
91 * restore [-v] file prov
92 * clear [-v] prov ...
93 * dump [-v] prov ...
94 */
95struct g_command class_commands[] = {
96	{ "init", G_FLAG_VERBOSE, eli_main,
97	    {
98		{ 'a', "aalgo", aalgo, G_TYPE_STRING },
99		{ 'b', "boot", NULL, G_TYPE_BOOL },
100		{ 'e', "ealgo", ealgo, G_TYPE_STRING },
101		{ 'i', "iterations", &iterations, G_TYPE_NUMBER },
102		{ 'K', "newkeyfile", newkeyfile, G_TYPE_STRING },
103		{ 'l', "keylen", &keylen, G_TYPE_NUMBER },
104		{ 'P', "nonewpassphrase", NULL, G_TYPE_BOOL },
105		{ 's', "sectorsize", &sectorsize, G_TYPE_NUMBER },
106		G_OPT_SENTINEL
107	    },
108	    "[-bPv] [-a aalgo] [-e ealgo] [-i iterations] [-l keylen] [-K newkeyfile] [-s sectorsize] prov"
109	},
110	{ "label", G_FLAG_VERBOSE, eli_main,
111	    {
112		{ 'a', "aalgo", aalgo, G_TYPE_STRING },
113		{ 'b', "boot", NULL, G_TYPE_BOOL },
114		{ 'e', "ealgo", ealgo, G_TYPE_STRING },
115		{ 'i', "iterations", &iterations, G_TYPE_NUMBER },
116		{ 'K', "newkeyfile", newkeyfile, G_TYPE_STRING },
117		{ 'l', "keylen", &keylen, G_TYPE_NUMBER },
118		{ 'P', "nonewpassphrase", NULL, G_TYPE_BOOL },
119		{ 's', "sectorsize", &sectorsize, G_TYPE_NUMBER },
120		G_OPT_SENTINEL
121	    },
122	    "- an alias for 'init'"
123	},
124	{ "attach", G_FLAG_VERBOSE | G_FLAG_LOADKLD, eli_main,
125	    {
126		{ 'd', "detach", NULL, G_TYPE_BOOL },
127		{ 'k', "keyfile", keyfile, G_TYPE_STRING },
128		{ 'p', "nopassphrase", NULL, G_TYPE_BOOL },
129		{ 'r', "readonly", NULL, G_TYPE_BOOL },
130		G_OPT_SENTINEL
131	    },
132	    "[-dprv] [-k keyfile] prov"
133	},
134	{ "detach", 0, NULL,
135	    {
136		{ 'f', "force", NULL, G_TYPE_BOOL },
137		{ 'l', "last", NULL, G_TYPE_BOOL },
138		G_OPT_SENTINEL
139	    },
140	    "[-fl] prov ..."
141	},
142	{ "stop", 0, NULL,
143	    {
144		{ 'f', "force", NULL, G_TYPE_BOOL },
145		{ 'l', "last", NULL, G_TYPE_BOOL },
146		G_OPT_SENTINEL
147	    },
148	    "- an alias for 'detach'"
149	},
150	{ "onetime", G_FLAG_VERBOSE | G_FLAG_LOADKLD, NULL,
151	    {
152		{ 'a', "aalgo", aalgo, G_TYPE_STRING },
153		{ 'd', "detach", NULL, G_TYPE_BOOL },
154		{ 'e', "ealgo", ealgo, G_TYPE_STRING },
155		{ 'l', "keylen", &keylen, G_TYPE_NUMBER },
156		{ 's', "sectorsize", &sectorsize, G_TYPE_NUMBER },
157		G_OPT_SENTINEL
158	    },
159	    "[-d] [-a aalgo] [-e ealgo] [-l keylen] [-s sectorsize] prov ..."
160	},
161	{ "configure", G_FLAG_VERBOSE, eli_main,
162	    {
163		{ 'b', "boot", NULL, G_TYPE_BOOL },
164		{ 'B', "noboot", NULL, G_TYPE_BOOL },
165		G_OPT_SENTINEL
166	    },
167	    "[-bB] prov ..."
168	},
169	{ "setkey", G_FLAG_VERBOSE, eli_main,
170	    {
171		{ 'i', "iterations", &iterations, G_TYPE_NUMBER },
172		{ 'k', "keyfile", keyfile, G_TYPE_STRING },
173		{ 'K', "newkeyfile", newkeyfile, G_TYPE_STRING },
174		{ 'n', "keyno", &keyno, G_TYPE_NUMBER },
175		{ 'p', "nopassphrase", NULL, G_TYPE_BOOL },
176		{ 'P', "nonewpassphrase", NULL, G_TYPE_BOOL },
177		G_OPT_SENTINEL
178	    },
179	    "[-pPv] [-n keyno] [-i iterations] [-k keyfile] [-K newkeyfile] prov"
180	},
181	{ "delkey", G_FLAG_VERBOSE, eli_main,
182	    {
183		{ 'a', "all", NULL, G_TYPE_BOOL },
184		{ 'f', "force", NULL, G_TYPE_BOOL },
185		{ 'n', "keyno", &keyno, G_TYPE_NUMBER },
186		G_OPT_SENTINEL
187	    },
188	    "[-afv] [-n keyno] prov"
189	},
190	{ "kill", G_FLAG_VERBOSE, eli_main,
191	    {
192		{ 'a', "all", NULL, G_TYPE_BOOL },
193		G_OPT_SENTINEL
194	    },
195	    "[-av] [prov ...]"
196	},
197	{ "backup", G_FLAG_VERBOSE, eli_main, G_NULL_OPTS,
198	    "[-v] prov file"
199	},
200	{ "restore", G_FLAG_VERBOSE, eli_main, G_NULL_OPTS,
201	    "[-v] file prov"
202	},
203	{ "clear", G_FLAG_VERBOSE, eli_main, G_NULL_OPTS,
204	    "[-v] prov ..."
205	},
206	{ "dump", G_FLAG_VERBOSE, eli_main, G_NULL_OPTS,
207	    "[-v] prov ..."
208	},
209	G_CMD_SENTINEL
210};
211
212static int verbose = 0;
213
214static int
215eli_protect(struct gctl_req *req)
216{
217	struct rlimit rl;
218
219	/* Disable core dumps. */
220	rl.rlim_cur = 0;
221	rl.rlim_max = 0;
222	if (setrlimit(RLIMIT_CORE, &rl) == -1) {
223		gctl_error(req, "Cannot disable core dumps: %s.",
224		    strerror(errno));
225		return (-1);
226	}
227	/* Disable swapping. */
228	if (mlockall(MCL_FUTURE) == -1) {
229		gctl_error(req, "Cannot lock memory: %s.", strerror(errno));
230		return (-1);
231	}
232	return (0);
233}
234
235static void
236eli_main(struct gctl_req *req, unsigned flags)
237{
238	const char *name;
239
240	if (eli_protect(req) == -1)
241		return;
242
243	if ((flags & G_FLAG_VERBOSE) != 0)
244		verbose = 1;
245
246	name = gctl_get_ascii(req, "verb");
247	if (name == NULL) {
248		gctl_error(req, "No '%s' argument.", "verb");
249		return;
250	}
251	if (strcmp(name, "init") == 0 || strcmp(name, "label") == 0)
252		eli_init(req);
253	else if (strcmp(name, "attach") == 0)
254		eli_attach(req);
255	else if (strcmp(name, "configure") == 0)
256		eli_configure(req);
257	else if (strcmp(name, "setkey") == 0)
258		eli_setkey(req);
259	else if (strcmp(name, "delkey") == 0)
260		eli_delkey(req);
261	else if (strcmp(name, "kill") == 0)
262		eli_kill(req);
263	else if (strcmp(name, "backup") == 0)
264		eli_backup(req);
265	else if (strcmp(name, "restore") == 0)
266		eli_restore(req);
267	else if (strcmp(name, "dump") == 0)
268		eli_dump(req);
269	else if (strcmp(name, "clear") == 0)
270		eli_clear(req);
271	else
272		gctl_error(req, "Unknown command: %s.", name);
273}
274
275static void
276arc4rand(unsigned char *buf, size_t size)
277{
278	uint32_t *buf4;
279	size_t size4;
280	unsigned i;
281
282	buf4 = (uint32_t *)buf;
283	size4 = size / 4;
284
285	for (i = 0; i < size4; i++)
286		buf4[i] = arc4random();
287	for (i *= 4; i < size; i++)
288		buf[i] = arc4random() % 0xff;
289}
290
291static int
292eli_is_attached(const char *prov)
293{
294	char name[MAXPATHLEN];
295	unsigned secsize;
296
297	/*
298	 * Not the best way to do it, but the easiest.
299	 * We try to open provider and check if it is a GEOM provider
300	 * by asking about its sectorsize.
301	 */
302	snprintf(name, sizeof(name), "%s%s", prov, G_ELI_SUFFIX);
303	secsize = g_get_sectorsize(name);
304	if (secsize > 0)
305		return (1);
306	return (0);
307}
308
309static unsigned char *
310eli_genkey(struct gctl_req *req, struct g_eli_metadata *md, unsigned char *key,
311    int new)
312{
313	struct hmac_ctx ctx;
314	const char *str;
315	int error, nopassphrase;
316
317	nopassphrase =
318	    gctl_get_int(req, new ? "nonewpassphrase" : "nopassphrase");
319
320	g_eli_crypto_hmac_init(&ctx, NULL, 0);
321
322	str = gctl_get_ascii(req, new ? "newkeyfile" : "keyfile");
323	if (str[0] == '\0' && nopassphrase) {
324		gctl_error(req, "No key components given.");
325		return (NULL);
326	} else if (str[0] != '\0') {
327		char buf[MAXPHYS];
328		ssize_t done;
329		int fd;
330
331		if (strcmp(str, "-") == 0)
332			fd = STDIN_FILENO;
333		else {
334			fd = open(str, O_RDONLY);
335			if (fd == -1) {
336				gctl_error(req, "Cannot open keyfile %s: %s.",
337				    str, strerror(errno));
338				return (NULL);
339			}
340		}
341		while ((done = read(fd, buf, sizeof(buf))) > 0)
342			g_eli_crypto_hmac_update(&ctx, buf, done);
343		error = errno;
344		if (strcmp(str, "-") != 0)
345			close(fd);
346		bzero(buf, sizeof(buf));
347		if (done == -1) {
348			gctl_error(req, "Cannot read keyfile %s: %s.", str,
349			    strerror(error));
350			return (NULL);
351		}
352	}
353
354	if (!nopassphrase) {
355		char buf1[BUFSIZ], buf2[BUFSIZ], *p;
356
357		if (!new && md->md_iterations == -1) {
358			gctl_error(req, "Missing -p flag.");
359			return (NULL);
360		}
361		for (;;) {
362			p = readpassphrase(
363			    new ? "Enter new passphrase:" : "Enter passphrase:",
364			    buf1, sizeof(buf1), RPP_ECHO_OFF | RPP_REQUIRE_TTY);
365			if (p == NULL) {
366				bzero(buf1, sizeof(buf1));
367				gctl_error(req, "Cannot read passphrase: %s.",
368				    strerror(errno));
369				return (NULL);
370			}
371
372			if (new) {
373				p = readpassphrase("Reenter new passphrase: ",
374				    buf2, sizeof(buf2),
375				    RPP_ECHO_OFF | RPP_REQUIRE_TTY);
376				if (p == NULL) {
377					bzero(buf1, sizeof(buf1));
378					gctl_error(req,
379					    "Cannot read passphrase: %s.",
380					    strerror(errno));
381					return (NULL);
382				}
383
384				if (strcmp(buf1, buf2) != 0) {
385					bzero(buf2, sizeof(buf2));
386					fprintf(stderr, "They didn't match.\n");
387					continue;
388				}
389				bzero(buf2, sizeof(buf2));
390			}
391			break;
392		}
393		/*
394		 * Field md_iterations equal to -1 means "choose some sane
395		 * value for me".
396		 */
397		if (md->md_iterations == -1) {
398			assert(new);
399			if (verbose)
400				printf("Calculating number of iterations...\n");
401			md->md_iterations = pkcs5v2_calculate(2000000);
402			assert(md->md_iterations > 0);
403			if (verbose) {
404				printf("Done, using %d iterations.\n",
405				    md->md_iterations);
406			}
407		}
408		/*
409		 * If md_iterations is equal to 0, user don't want PKCS#5v2.
410		 */
411		if (md->md_iterations == 0) {
412			g_eli_crypto_hmac_update(&ctx, md->md_salt,
413			    sizeof(md->md_salt));
414			g_eli_crypto_hmac_update(&ctx, buf1, strlen(buf1));
415		} else /* if (md->md_iterations > 0) */ {
416			unsigned char dkey[G_ELI_USERKEYLEN];
417
418			pkcs5v2_genkey(dkey, sizeof(dkey), md->md_salt,
419			    sizeof(md->md_salt), buf1, md->md_iterations);
420			g_eli_crypto_hmac_update(&ctx, dkey, sizeof(dkey));
421			bzero(dkey, sizeof(dkey));
422		}
423		bzero(buf1, sizeof(buf1));
424	}
425	g_eli_crypto_hmac_final(&ctx, key, 0);
426	return (key);
427}
428
429static int
430eli_metadata_read(struct gctl_req *req, const char *prov,
431    struct g_eli_metadata *md)
432{
433	unsigned char sector[sizeof(struct g_eli_metadata)];
434	int error;
435
436	if (g_get_sectorsize(prov) == 0) {
437		int fd;
438
439		/* This is a file probably. */
440		fd = open(prov, O_RDONLY);
441		if (fd == -1) {
442			gctl_error(req, "Cannot open %s: %s.", prov,
443			    strerror(errno));
444			return (-1);
445		}
446		if (read(fd, sector, sizeof(sector)) != sizeof(sector)) {
447			gctl_error(req, "Cannot read metadata from %s: %s.",
448			    prov, strerror(errno));
449			close(fd);
450			return (-1);
451		}
452		close(fd);
453	} else {
454		/* This is a GEOM provider. */
455		error = g_metadata_read(prov, sector, sizeof(sector),
456		    G_ELI_MAGIC);
457		if (error != 0) {
458			gctl_error(req, "Cannot read metadata from %s: %s.",
459			    prov, strerror(error));
460			return (-1);
461		}
462	}
463	if (eli_metadata_decode(sector, md) != 0) {
464		gctl_error(req, "MD5 hash mismatch for %s.", prov);
465		return (-1);
466	}
467	return (0);
468}
469
470static int
471eli_metadata_store(struct gctl_req *req, const char *prov,
472    struct g_eli_metadata *md)
473{
474	unsigned char sector[sizeof(struct g_eli_metadata)];
475	int error;
476
477	eli_metadata_encode(md, sector);
478	if (g_get_sectorsize(prov) == 0) {
479		int fd;
480
481		/* This is a file probably. */
482		fd = open(prov, O_WRONLY | O_TRUNC);
483		if (fd == -1) {
484			gctl_error(req, "Cannot open %s: %s.", prov,
485			    strerror(errno));
486			bzero(sector, sizeof(sector));
487			return (-1);
488		}
489		if (write(fd, sector, sizeof(sector)) != sizeof(sector)) {
490			gctl_error(req, "Cannot write metadata to %s: %s.",
491			    prov, strerror(errno));
492			bzero(sector, sizeof(sector));
493			close(fd);
494			return (-1);
495		}
496		close(fd);
497	} else {
498		/* This is a GEOM provider. */
499		error = g_metadata_store(prov, sector, sizeof(sector));
500		if (error != 0) {
501			gctl_error(req, "Cannot write metadata to %s: %s.",
502			    prov, strerror(errno));
503			bzero(sector, sizeof(sector));
504			return (-1);
505		}
506	}
507	bzero(sector, sizeof(sector));
508	return (0);
509}
510
511static void
512eli_init(struct gctl_req *req)
513{
514	struct g_eli_metadata md;
515	unsigned char sector[sizeof(struct g_eli_metadata)];
516	unsigned char key[G_ELI_USERKEYLEN];
517	const char *str, *prov;
518	unsigned secsize;
519	off_t mediasize;
520	intmax_t val;
521	int error, nargs;
522
523	nargs = gctl_get_int(req, "nargs");
524	if (nargs != 1) {
525		gctl_error(req, "Invalid number of arguments.");
526		return;
527	}
528	prov = gctl_get_ascii(req, "arg0");
529	mediasize = g_get_mediasize(prov);
530	secsize = g_get_sectorsize(prov);
531	if (mediasize == 0 || secsize == 0) {
532		gctl_error(req, "Cannot get informations about %s: %s.", prov,
533		    strerror(errno));
534		return;
535	}
536
537	bzero(&md, sizeof(md));
538	strlcpy(md.md_magic, G_ELI_MAGIC, sizeof(md.md_magic));
539	md.md_version = G_ELI_VERSION;
540	md.md_flags = 0;
541	if (gctl_get_int(req, "boot"))
542		md.md_flags |= G_ELI_FLAG_BOOT;
543	md.md_ealgo = CRYPTO_ALGORITHM_MIN - 1;
544	str = gctl_get_ascii(req, "aalgo");
545	if (strcmp(str, "none") != 0) {
546		md.md_aalgo = g_eli_str2aalgo(str);
547		if (md.md_aalgo >= CRYPTO_ALGORITHM_MIN &&
548		    md.md_aalgo <= CRYPTO_ALGORITHM_MAX) {
549			md.md_flags |= G_ELI_FLAG_AUTH;
550		} else {
551			/*
552			 * For backward compatibility, check if the -a option
553			 * was used to provide encryption algorithm.
554			 */
555			md.md_ealgo = g_eli_str2ealgo(str);
556			if (md.md_ealgo < CRYPTO_ALGORITHM_MIN ||
557			    md.md_ealgo > CRYPTO_ALGORITHM_MAX) {
558				gctl_error(req,
559				    "Invalid authentication algorithm.");
560				return;
561			} else {
562				fprintf(stderr, "warning: The -e option, not "
563				    "the -a option is now used to specify "
564				    "encryption algorithm to use.\n");
565			}
566		}
567	}
568	if (md.md_ealgo < CRYPTO_ALGORITHM_MIN ||
569	    md.md_ealgo > CRYPTO_ALGORITHM_MAX) {
570		str = gctl_get_ascii(req, "ealgo");
571		md.md_ealgo = g_eli_str2ealgo(str);
572		if (md.md_ealgo < CRYPTO_ALGORITHM_MIN ||
573		    md.md_ealgo > CRYPTO_ALGORITHM_MAX) {
574			gctl_error(req, "Invalid encryption algorithm.");
575			return;
576		}
577	}
578	val = gctl_get_intmax(req, "keylen");
579	md.md_keylen = val;
580	md.md_keylen = g_eli_keylen(md.md_ealgo, md.md_keylen);
581	if (md.md_keylen == 0) {
582		gctl_error(req, "Invalid key length.");
583		return;
584	}
585	md.md_provsize = mediasize;
586
587	val = gctl_get_intmax(req, "iterations");
588	if (val != -1) {
589		int nonewpassphrase;
590
591		/*
592		 * Don't allow to set iterations when there will be no
593		 * passphrase.
594		 */
595		nonewpassphrase = gctl_get_int(req, "nonewpassphrase");
596		if (nonewpassphrase) {
597			gctl_error(req,
598			    "Options -i and -P are mutually exclusive.");
599			return;
600		}
601	}
602	md.md_iterations = val;
603
604	val = gctl_get_intmax(req, "sectorsize");
605	if (val == 0)
606		md.md_sectorsize = secsize;
607	else {
608		if (val < 0 || (val % secsize) != 0) {
609			gctl_error(req, "Invalid sector size.");
610			return;
611		}
612		if (val > sysconf(_SC_PAGE_SIZE)) {
613			gctl_error(req, "warning: Using sectorsize bigger than "
614			    "the page size!");
615		}
616		md.md_sectorsize = val;
617	}
618
619	md.md_keys = 0x01;
620	arc4rand(md.md_salt, sizeof(md.md_salt));
621	arc4rand(md.md_mkeys, sizeof(md.md_mkeys));
622
623	/* Generate user key. */
624	if (eli_genkey(req, &md, key, 1) == NULL) {
625		bzero(key, sizeof(key));
626		bzero(&md, sizeof(md));
627		return;
628	}
629
630	/* Encrypt the first and the only Master Key. */
631	error = g_eli_mkey_encrypt(md.md_ealgo, key, md.md_keylen, md.md_mkeys);
632	bzero(key, sizeof(key));
633	if (error != 0) {
634		bzero(&md, sizeof(md));
635		gctl_error(req, "Cannot encrypt Master Key: %s.",
636		    strerror(error));
637		return;
638	}
639
640	eli_metadata_encode(&md, sector);
641	bzero(&md, sizeof(md));
642	error = g_metadata_store(prov, sector, sizeof(sector));
643	bzero(sector, sizeof(sector));
644	if (error != 0) {
645		gctl_error(req, "Cannot store metadata on %s: %s.", prov,
646		    strerror(error));
647		return;
648	}
649	if (verbose)
650		printf("Metadata value stored on %s.\n", prov);
651}
652
653static void
654eli_attach(struct gctl_req *req)
655{
656	struct g_eli_metadata md;
657	unsigned char key[G_ELI_USERKEYLEN];
658	const char *prov;
659	int nargs;
660
661	nargs = gctl_get_int(req, "nargs");
662	if (nargs != 1) {
663		gctl_error(req, "Invalid number of arguments.");
664		return;
665	}
666	prov = gctl_get_ascii(req, "arg0");
667
668	if (eli_metadata_read(req, prov, &md) == -1)
669		return;
670
671	if (eli_genkey(req, &md, key, 0) == NULL) {
672		bzero(key, sizeof(key));
673		return;
674	}
675
676	gctl_ro_param(req, "key", sizeof(key), key);
677	if (gctl_issue(req) == NULL) {
678		if (verbose)
679			printf("Attached to %s.\n", prov);
680	}
681	bzero(key, sizeof(key));
682}
683
684static void
685eli_configure_detached(struct gctl_req *req, const char *prov, int boot)
686{
687	struct g_eli_metadata md;
688
689	if (eli_metadata_read(req, prov, &md) == -1)
690		return;
691
692	if (boot && (md.md_flags & G_ELI_FLAG_BOOT)) {
693		if (verbose)
694			printf("BOOT flag already configured for %s.\n", prov);
695	} else if (!boot && !(md.md_flags & G_ELI_FLAG_BOOT)) {
696		if (verbose)
697			printf("BOOT flag not configured for %s.\n", prov);
698	} else {
699		if (boot)
700			md.md_flags |= G_ELI_FLAG_BOOT;
701		else
702			md.md_flags &= ~G_ELI_FLAG_BOOT;
703		eli_metadata_store(req, prov, &md);
704	}
705	bzero(&md, sizeof(md));
706}
707
708static void
709eli_configure(struct gctl_req *req)
710{
711	const char *prov;
712	int i, nargs, boot, noboot;
713
714	nargs = gctl_get_int(req, "nargs");
715	if (nargs == 0) {
716		gctl_error(req, "Too few arguments.");
717		return;
718	}
719
720	boot = gctl_get_int(req, "boot");
721	noboot = gctl_get_int(req, "noboot");
722
723	if (boot && noboot) {
724		gctl_error(req, "Options -b and -B are mutually exclusive.");
725		return;
726	}
727	if (!boot && !noboot) {
728		gctl_error(req, "No option given.");
729		return;
730	}
731
732	/* First attached providers. */
733	gctl_issue(req);
734	/* Now the rest. */
735	for (i = 0; i < nargs; i++) {
736		prov = gctl_get_ascii(req, "arg%d", i);
737		if (!eli_is_attached(prov))
738			eli_configure_detached(req, prov, boot);
739	}
740}
741
742static void
743eli_setkey_attached(struct gctl_req *req, struct g_eli_metadata *md)
744{
745	unsigned char key[G_ELI_USERKEYLEN];
746	intmax_t val, old = 0;
747	int error;
748
749	val = gctl_get_intmax(req, "iterations");
750	/* Check if iterations number should be changed. */
751	if (val != -1)
752		md->md_iterations = val;
753	else
754		old = md->md_iterations;
755
756	/* Generate key for Master Key encryption. */
757	if (eli_genkey(req, md, key, 1) == NULL) {
758		bzero(key, sizeof(key));
759		return;
760	}
761	/*
762	 * If number of iterations has changed, but wasn't given as a
763	 * command-line argument, update the request.
764	 */
765	if (val == -1 && md->md_iterations != old) {
766		error = gctl_change_param(req, "iterations", sizeof(intmax_t),
767		    &md->md_iterations);
768		assert(error == 0);
769	}
770
771	gctl_ro_param(req, "key", sizeof(key), key);
772	gctl_issue(req);
773	bzero(key, sizeof(key));
774}
775
776static void
777eli_setkey_detached(struct gctl_req *req, const char *prov,
778 struct g_eli_metadata *md)
779{
780	unsigned char key[G_ELI_USERKEYLEN], mkey[G_ELI_DATAIVKEYLEN];
781	unsigned char *mkeydst;
782	intmax_t val;
783	unsigned nkey;
784	int error;
785
786	if (md->md_keys == 0) {
787		gctl_error(req, "No valid keys on %s.", prov);
788		return;
789	}
790
791	/* Generate key for Master Key decryption. */
792	if (eli_genkey(req, md, key, 0) == NULL) {
793		bzero(key, sizeof(key));
794		return;
795	}
796
797	/* Decrypt Master Key. */
798	error = g_eli_mkey_decrypt(md, key, mkey, &nkey);
799	bzero(key, sizeof(key));
800	if (error != 0) {
801		bzero(md, sizeof(*md));
802		if (error == -1)
803			gctl_error(req, "Wrong key for %s.", prov);
804		else /* if (error > 0) */ {
805			gctl_error(req, "Cannot decrypt Master Key: %s.",
806			    strerror(error));
807		}
808		return;
809	}
810	if (verbose)
811		printf("Decrypted Master Key %u.\n", nkey);
812
813	val = gctl_get_intmax(req, "keyno");
814	if (val != -1)
815		nkey = val;
816#if 0
817	else
818		; /* Use the key number which was found during decryption. */
819#endif
820	if (nkey >= G_ELI_MAXMKEYS) {
821		gctl_error(req, "Invalid '%s' argument.", "keyno");
822		return;
823	}
824
825	val = gctl_get_intmax(req, "iterations");
826	/* Check if iterations number should and can be changed. */
827	if (val != -1) {
828		if (bitcount32(md->md_keys) != 1) {
829			gctl_error(req, "To be able to use '-i' option, only "
830			    "one key can be defined.");
831			return;
832		}
833		if (md->md_keys != (1 << nkey)) {
834			gctl_error(req, "Only already defined key can be "
835			    "changed when '-i' option is used.");
836			return;
837		}
838		md->md_iterations = val;
839	}
840
841	mkeydst = md->md_mkeys + nkey * G_ELI_MKEYLEN;
842	md->md_keys |= (1 << nkey);
843
844	bcopy(mkey, mkeydst, sizeof(mkey));
845	bzero(mkey, sizeof(mkey));
846
847	/* Generate key for Master Key encryption. */
848	if (eli_genkey(req, md, key, 1) == NULL) {
849		bzero(key, sizeof(key));
850		bzero(md, sizeof(*md));
851		return;
852	}
853
854	/* Encrypt the Master-Key with the new key. */
855	error = g_eli_mkey_encrypt(md->md_ealgo, key, md->md_keylen, mkeydst);
856	bzero(key, sizeof(key));
857	if (error != 0) {
858		bzero(md, sizeof(*md));
859		gctl_error(req, "Cannot encrypt Master Key: %s.",
860		    strerror(error));
861		return;
862	}
863
864	/* Store metadata with fresh key. */
865	eli_metadata_store(req, prov, md);
866	bzero(md, sizeof(*md));
867}
868
869static void
870eli_setkey(struct gctl_req *req)
871{
872	struct g_eli_metadata md;
873	const char *prov;
874	int nargs;
875
876	nargs = gctl_get_int(req, "nargs");
877	if (nargs != 1) {
878		gctl_error(req, "Invalid number of arguments.");
879		return;
880	}
881	prov = gctl_get_ascii(req, "arg0");
882
883	if (eli_metadata_read(req, prov, &md) == -1)
884		return;
885
886	if (eli_is_attached(prov))
887		eli_setkey_attached(req, &md);
888	else
889		eli_setkey_detached(req, prov, &md);
890}
891
892static void
893eli_delkey_attached(struct gctl_req *req, const char *prov __unused)
894{
895
896	gctl_issue(req);
897}
898
899static void
900eli_delkey_detached(struct gctl_req *req, const char *prov)
901{
902	struct g_eli_metadata md;
903	unsigned char *mkeydst;
904	intmax_t val;
905	unsigned nkey;
906	int all, force;
907
908	if (eli_metadata_read(req, prov, &md) == -1)
909		return;
910
911	all = gctl_get_int(req, "all");
912	if (all)
913		arc4rand(md.md_mkeys, sizeof(md.md_mkeys));
914	else {
915		force = gctl_get_int(req, "force");
916		val = gctl_get_intmax(req, "keyno");
917		if (val == -1) {
918			gctl_error(req, "Key number has to be specified.");
919			return;
920		}
921		nkey = val;
922		if (nkey >= G_ELI_MAXMKEYS) {
923			gctl_error(req, "Invalid '%s' argument.", "keyno");
924			return;
925		}
926		if (!(md.md_keys & (1 << nkey)) && !force) {
927			gctl_error(req, "Master Key %u is not set.", nkey);
928			return;
929		}
930		md.md_keys &= ~(1 << nkey);
931		if (md.md_keys == 0 && !force) {
932			gctl_error(req, "This is the last Master Key. Use '-f' "
933			    "option if you really want to remove it.");
934			return;
935		}
936		mkeydst = md.md_mkeys + nkey * G_ELI_MKEYLEN;
937		arc4rand(mkeydst, G_ELI_MKEYLEN);
938	}
939
940	eli_metadata_store(req, prov, &md);
941	bzero(&md, sizeof(md));
942}
943
944static void
945eli_delkey(struct gctl_req *req)
946{
947	const char *prov;
948	int nargs;
949
950	nargs = gctl_get_int(req, "nargs");
951	if (nargs != 1) {
952		gctl_error(req, "Invalid number of arguments.");
953		return;
954	}
955	prov = gctl_get_ascii(req, "arg0");
956
957	if (eli_is_attached(prov))
958		eli_delkey_attached(req, prov);
959	else
960		eli_delkey_detached(req, prov);
961}
962
963static void
964eli_kill_detached(struct gctl_req *req, const char *prov)
965{
966	struct g_eli_metadata md;
967	int error;
968
969	/*
970	 * NOTE: Maybe we should verify if this is geli provider first,
971	 *       but 'kill' command is quite critical so better don't waste
972	 *       the time.
973	 */
974#if 0
975	error = g_metadata_read(prov, (unsigned char *)&md, sizeof(md),
976	    G_ELI_MAGIC);
977	if (error != 0) {
978		gctl_error(req, "Cannot read metadata from %s: %s.", prov,
979		    strerror(error));
980		return;
981	}
982#endif
983
984	arc4rand((unsigned char *)&md, sizeof(md));
985	error = g_metadata_store(prov, (unsigned char *)&md, sizeof(md));
986	if (error != 0) {
987		gctl_error(req, "Cannot write metadata to %s: %s.", prov,
988		    strerror(error));
989	}
990}
991
992static void
993eli_kill(struct gctl_req *req)
994{
995	const char *prov;
996	int i, nargs, all;
997
998	nargs = gctl_get_int(req, "nargs");
999	all = gctl_get_int(req, "all");
1000	if (!all && nargs == 0) {
1001		gctl_error(req, "Too few arguments.");
1002		return;
1003	}
1004	/*
1005	 * How '-a' option combine with a list of providers:
1006	 * Delete Master Keys from all attached providers:
1007	 * geli kill -a
1008	 * Delete Master Keys from all attached provider and from
1009	 * detached da0 and da1:
1010	 * geli kill -a da0 da1
1011	 * Delete Master Keys from (attached or detached) da0 and da1:
1012	 * geli kill da0 da1
1013	 */
1014
1015	/* First detached provider. */
1016	for (i = 0; i < nargs; i++) {
1017		prov = gctl_get_ascii(req, "arg%d", i);
1018		if (!eli_is_attached(prov))
1019			eli_kill_detached(req, prov);
1020	}
1021	/* Now attached providers. */
1022	gctl_issue(req);
1023}
1024
1025static void
1026eli_backup(struct gctl_req *req)
1027{
1028	struct g_eli_metadata md;
1029	const char *file, *prov;
1030	unsigned secsize;
1031	unsigned char *sector;
1032	off_t mediasize;
1033	int nargs, filefd, provfd;
1034
1035	nargs = gctl_get_int(req, "nargs");
1036	if (nargs != 2) {
1037		gctl_error(req, "Invalid number of arguments.");
1038		return;
1039	}
1040	prov = gctl_get_ascii(req, "arg0");
1041	file = gctl_get_ascii(req, "arg1");
1042
1043	provfd = filefd = -1;
1044	sector = NULL;
1045	secsize = 0;
1046
1047	provfd = open(prov, O_RDONLY);
1048	if (provfd == -1 && errno == ENOENT && prov[0] != '/') {
1049		char devprov[MAXPATHLEN];
1050
1051		snprintf(devprov, sizeof(devprov), "%s%s", _PATH_DEV, prov);
1052		provfd = open(devprov, O_RDONLY);
1053	}
1054	if (provfd == -1) {
1055		gctl_error(req, "Cannot open %s: %s.", prov, strerror(errno));
1056		return;
1057	}
1058	filefd = open(file, O_WRONLY | O_TRUNC | O_CREAT, 0600);
1059	if (filefd == -1) {
1060		gctl_error(req, "Cannot open %s: %s.", file, strerror(errno));
1061		goto out;
1062	}
1063
1064	mediasize = g_get_mediasize(prov);
1065	secsize = g_get_sectorsize(prov);
1066	if (mediasize == 0 || secsize == 0) {
1067		gctl_error(req, "Cannot get informations about %s: %s.", prov,
1068		    strerror(errno));
1069		return;
1070	}
1071
1072	sector = malloc(secsize);
1073	if (sector == NULL) {
1074		gctl_error(req, "Cannot allocate memory.");
1075		return;
1076	}
1077
1078	/* Read metadata from the provider. */
1079	if (pread(provfd, sector, secsize, mediasize - secsize) !=
1080	    (ssize_t)secsize) {
1081		gctl_error(req, "Cannot read metadata: %s.", strerror(errno));
1082		goto out;
1083	}
1084	/* Check if this is geli provider. */
1085	if (eli_metadata_decode(sector, &md) != 0) {
1086		gctl_error(req, "MD5 hash mismatch: not a geli provider?");
1087		goto out;
1088	}
1089	/* Write metadata to the destination file. */
1090	if (write(filefd, sector, secsize) != (ssize_t)secsize) {
1091		gctl_error(req, "Cannot write to %s: %s.", file,
1092		    strerror(errno));
1093		goto out;
1094	}
1095out:
1096	if (provfd > 0)
1097		close(provfd);
1098	if (filefd > 0)
1099		close(filefd);
1100	if (sector != NULL) {
1101		bzero(sector, secsize);
1102		free(sector);
1103	}
1104}
1105
1106static void
1107eli_restore(struct gctl_req *req)
1108{
1109	struct g_eli_metadata md;
1110	const char *file, *prov;
1111	unsigned char *sector;
1112	unsigned secsize;
1113	off_t mediasize;
1114	int nargs, filefd, provfd;
1115
1116	nargs = gctl_get_int(req, "nargs");
1117	if (nargs != 2) {
1118		gctl_error(req, "Invalid number of arguments.");
1119		return;
1120	}
1121	file = gctl_get_ascii(req, "arg0");
1122	prov = gctl_get_ascii(req, "arg1");
1123
1124	provfd = filefd = -1;
1125	sector = NULL;
1126	secsize = 0;
1127
1128	filefd = open(file, O_RDONLY);
1129	if (filefd == -1) {
1130		gctl_error(req, "Cannot open %s: %s.", file, strerror(errno));
1131		goto out;
1132	}
1133	provfd = open(prov, O_WRONLY);
1134	if (provfd == -1 && errno == ENOENT && prov[0] != '/') {
1135		char devprov[MAXPATHLEN];
1136
1137		snprintf(devprov, sizeof(devprov), "%s%s", _PATH_DEV, prov);
1138		provfd = open(devprov, O_WRONLY);
1139	}
1140	if (provfd == -1) {
1141		gctl_error(req, "Cannot open %s: %s.", prov, strerror(errno));
1142		return;
1143	}
1144
1145	mediasize = g_get_mediasize(prov);
1146	secsize = g_get_sectorsize(prov);
1147	if (mediasize == 0 || secsize == 0) {
1148		gctl_error(req, "Cannot get informations about %s: %s.", prov,
1149		    strerror(errno));
1150		return;
1151	}
1152
1153	sector = malloc(secsize);
1154	if (sector == NULL) {
1155		gctl_error(req, "Cannot allocate memory.");
1156		return;
1157	}
1158
1159	/* Read metadata from the backup file. */
1160	if (read(filefd, sector, secsize) != (ssize_t)secsize) {
1161		gctl_error(req, "Cannot read from %s: %s.", file,
1162		    strerror(errno));
1163		goto out;
1164	}
1165	/* Check if this file contains geli metadata. */
1166	if (eli_metadata_decode(sector, &md) != 0) {
1167		gctl_error(req, "MD5 hash mismatch: not a geli backup file?");
1168		goto out;
1169	}
1170	/* Write metadata from the provider. */
1171	if (pwrite(provfd, sector, secsize, mediasize - secsize) !=
1172	    (ssize_t)secsize) {
1173		gctl_error(req, "Cannot write metadata: %s.", strerror(errno));
1174		goto out;
1175	}
1176out:
1177	if (provfd > 0)
1178		close(provfd);
1179	if (filefd > 0)
1180		close(filefd);
1181	if (sector != NULL) {
1182		bzero(sector, secsize);
1183		free(sector);
1184	}
1185}
1186
1187static void
1188eli_clear(struct gctl_req *req)
1189{
1190	const char *name;
1191	int error, i, nargs;
1192
1193	nargs = gctl_get_int(req, "nargs");
1194	if (nargs < 1) {
1195		gctl_error(req, "Too few arguments.");
1196		return;
1197	}
1198
1199	for (i = 0; i < nargs; i++) {
1200		name = gctl_get_ascii(req, "arg%d", i);
1201		error = g_metadata_clear(name, G_ELI_MAGIC);
1202		if (error != 0) {
1203			fprintf(stderr, "Cannot clear metadata on %s: %s.\n",
1204			    name, strerror(error));
1205			gctl_error(req, "Not fully done.");
1206			continue;
1207		}
1208		if (verbose)
1209			printf("Metadata cleared on %s.\n", name);
1210	}
1211}
1212
1213static void
1214eli_dump(struct gctl_req *req)
1215{
1216	struct g_eli_metadata md, tmpmd;
1217	const char *name;
1218	int error, i, nargs;
1219
1220	nargs = gctl_get_int(req, "nargs");
1221	if (nargs < 1) {
1222		gctl_error(req, "Too few arguments.");
1223		return;
1224	}
1225
1226	for (i = 0; i < nargs; i++) {
1227		name = gctl_get_ascii(req, "arg%d", i);
1228		error = g_metadata_read(name, (unsigned char *)&tmpmd,
1229		    sizeof(tmpmd), G_ELI_MAGIC);
1230		if (error != 0) {
1231			fprintf(stderr, "Cannot read metadata from %s: %s.\n",
1232			    name, strerror(error));
1233			gctl_error(req, "Not fully done.");
1234			continue;
1235		}
1236		if (eli_metadata_decode((unsigned char *)&tmpmd, &md) != 0) {
1237			fprintf(stderr, "MD5 hash mismatch for %s, skipping.\n",
1238			    name);
1239			gctl_error(req, "Not fully done.");
1240			continue;
1241		}
1242		printf("Metadata on %s:\n", name);
1243		eli_metadata_dump(&md);
1244		printf("\n");
1245	}
1246}
1247