1/*-
2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3 *
4 * Copyright (c) 2004-2019 Pawel Jakub Dawidek <pawel@dawidek.net>
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 *    notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 *    notice, this list of conditions and the following disclaimer in the
14 *    documentation and/or other materials provided with the distribution.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
17 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
20 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * SUCH DAMAGE.
27 */
28
29#include <sys/cdefs.h>
30__FBSDID("$FreeBSD$");
31
32#include <sys/param.h>
33#include <sys/mman.h>
34#include <sys/sysctl.h>
35#include <sys/resource.h>
36#include <opencrypto/cryptodev.h>
37
38#include <assert.h>
39#include <err.h>
40#include <errno.h>
41#include <fcntl.h>
42#include <libgeom.h>
43#include <paths.h>
44#include <readpassphrase.h>
45#include <stdbool.h>
46#include <stdint.h>
47#include <stdio.h>
48#include <stdlib.h>
49#include <string.h>
50#include <strings.h>
51#include <unistd.h>
52
53#include <geom/eli/g_eli.h>
54#include <geom/eli/pkcs5v2.h>
55
56#include "core/geom.h"
57#include "misc/subr.h"
58
59
60uint32_t lib_version = G_LIB_VERSION;
61uint32_t version = G_ELI_VERSION;
62
63#define	GELI_BACKUP_DIR	"/var/backups/"
64#define	GELI_ENC_ALGO	"aes"
65#define	BUFSIZE		1024
66
67/*
68 * Passphrase cached when attaching multiple providers, in order to be more
69 * user-friendly if they are using the same passphrase.
70 */
71static char cached_passphrase[BUFSIZE] = "";
72
73static void eli_main(struct gctl_req *req, unsigned flags);
74static void eli_init(struct gctl_req *req);
75static void eli_attach(struct gctl_req *req);
76static void eli_configure(struct gctl_req *req);
77static void eli_setkey(struct gctl_req *req);
78static void eli_delkey(struct gctl_req *req);
79static void eli_resume(struct gctl_req *req);
80static void eli_kill(struct gctl_req *req);
81static void eli_backup(struct gctl_req *req);
82static void eli_restore(struct gctl_req *req);
83static void eli_resize(struct gctl_req *req);
84static void eli_version(struct gctl_req *req);
85static void eli_clear(struct gctl_req *req);
86static void eli_dump(struct gctl_req *req);
87
88static int eli_backup_create(struct gctl_req *req, const char *prov,
89    const char *file);
90
91/*
92 * Available commands:
93 *
94 * init [-bdgPRTv] [-a aalgo] [-B backupfile] [-e ealgo] [-i iterations] [-l keylen] [-J newpassfile] [-K newkeyfile] [-s sectorsize] [-V version] prov ...
95 * label - alias for 'init'
96 * attach [-Cdprv] [-n keyno] [-j passfile] [-k keyfile] prov ...
97 * detach [-fl] prov ...
98 * stop - alias for 'detach'
99 * onetime [-dRT] [-a aalgo] [-e ealgo] [-l keylen] prov
100 * configure [-bBgGrRtT] prov ...
101 * setkey [-pPv] [-n keyno] [-j passfile] [-J newpassfile] [-k keyfile] [-K newkeyfile] prov
102 * delkey [-afv] [-n keyno] prov
103 * suspend [-v] -a | prov ...
104 * resume [-pv] [-j passfile] [-k keyfile] prov
105 * kill [-av] [prov ...]
106 * backup [-v] prov file
107 * restore [-fv] file prov
108 * resize [-v] -s oldsize prov
109 * version [prov ...]
110 * clear [-v] prov ...
111 * dump [-v] prov ...
112 */
113struct g_command class_commands[] = {
114	{ "init", G_FLAG_VERBOSE, eli_main,
115	    {
116		{ 'a', "aalgo", "", G_TYPE_STRING },
117		{ 'b', "boot", NULL, G_TYPE_BOOL },
118		{ 'B', "backupfile", "", G_TYPE_STRING },
119		{ 'd', "displaypass", NULL, G_TYPE_BOOL },
120		{ 'e', "ealgo", "", G_TYPE_STRING },
121		{ 'g', "geliboot", NULL, G_TYPE_BOOL },
122		{ 'i', "iterations", "-1", G_TYPE_NUMBER },
123		{ 'J', "newpassfile", G_VAL_OPTIONAL, G_TYPE_STRING | G_TYPE_MULTI },
124		{ 'K', "newkeyfile", G_VAL_OPTIONAL, G_TYPE_STRING | G_TYPE_MULTI },
125		{ 'l', "keylen", "0", G_TYPE_NUMBER },
126		{ 'P', "nonewpassphrase", NULL, G_TYPE_BOOL },
127		{ 'R', "noautoresize", NULL, G_TYPE_BOOL },
128		{ 's', "sectorsize", "0", G_TYPE_NUMBER },
129		{ 'T', "notrim", NULL, G_TYPE_BOOL },
130		{ 'V', "mdversion", "-1", G_TYPE_NUMBER },
131		G_OPT_SENTINEL
132	    },
133	    "[-bdgPRTv] [-a aalgo] [-B backupfile] [-e ealgo] [-i iterations] [-l keylen] [-J newpassfile] [-K newkeyfile] [-s sectorsize] [-V version] prov ..."
134	},
135	{ "label", G_FLAG_VERBOSE, eli_main,
136	    {
137		{ 'a', "aalgo", "", G_TYPE_STRING },
138		{ 'b', "boot", NULL, G_TYPE_BOOL },
139		{ 'B', "backupfile", "", G_TYPE_STRING },
140		{ 'd', "displaypass", NULL, G_TYPE_BOOL },
141		{ 'e', "ealgo", "", G_TYPE_STRING },
142		{ 'g', "geliboot", NULL, G_TYPE_BOOL },
143		{ 'i', "iterations", "-1", G_TYPE_NUMBER },
144		{ 'J', "newpassfile", G_VAL_OPTIONAL, G_TYPE_STRING | G_TYPE_MULTI },
145		{ 'K', "newkeyfile", G_VAL_OPTIONAL, G_TYPE_STRING | G_TYPE_MULTI },
146		{ 'l', "keylen", "0", G_TYPE_NUMBER },
147		{ 'P', "nonewpassphrase", NULL, G_TYPE_BOOL },
148		{ 'R', "noautoresize", NULL, G_TYPE_BOOL },
149		{ 's', "sectorsize", "0", G_TYPE_NUMBER },
150		{ 'T', "notrim", NULL, G_TYPE_BOOL },
151		{ 'V', "mdversion", "-1", G_TYPE_NUMBER },
152		G_OPT_SENTINEL
153	    },
154	    "- an alias for 'init'"
155	},
156	{ "attach", G_FLAG_VERBOSE | G_FLAG_LOADKLD, eli_main,
157	    {
158		{ 'C', "dryrun", NULL, G_TYPE_BOOL },
159		{ 'd', "detach", NULL, G_TYPE_BOOL },
160		{ 'j', "passfile", G_VAL_OPTIONAL, G_TYPE_STRING | G_TYPE_MULTI },
161		{ 'k', "keyfile", G_VAL_OPTIONAL, G_TYPE_STRING | G_TYPE_MULTI },
162		{ 'n', "keyno", "-1", G_TYPE_NUMBER },
163		{ 'p', "nopassphrase", NULL, G_TYPE_BOOL },
164		{ 'r', "readonly", NULL, G_TYPE_BOOL },
165		G_OPT_SENTINEL
166	    },
167	    "[-Cdprv] [-n keyno] [-j passfile] [-k keyfile] prov ..."
168	},
169	{ "detach", 0, NULL,
170	    {
171		{ 'f', "force", NULL, G_TYPE_BOOL },
172		{ 'l', "last", NULL, G_TYPE_BOOL },
173		G_OPT_SENTINEL
174	    },
175	    "[-fl] prov ..."
176	},
177	{ "stop", 0, NULL,
178	    {
179		{ 'f', "force", NULL, G_TYPE_BOOL },
180		{ 'l', "last", NULL, G_TYPE_BOOL },
181		G_OPT_SENTINEL
182	    },
183	    "- an alias for 'detach'"
184	},
185	{ "onetime", G_FLAG_VERBOSE | G_FLAG_LOADKLD, NULL,
186	    {
187		{ 'a', "aalgo", "", G_TYPE_STRING },
188		{ 'd', "detach", NULL, G_TYPE_BOOL },
189		{ 'e', "ealgo", GELI_ENC_ALGO, G_TYPE_STRING },
190		{ 'l', "keylen", "0", G_TYPE_NUMBER },
191		{ 'R', "noautoresize", NULL, G_TYPE_BOOL },
192		{ 's', "sectorsize", "0", G_TYPE_NUMBER },
193		{ 'T', "notrim", NULL, G_TYPE_BOOL },
194		G_OPT_SENTINEL
195	    },
196	    "[-dRT] [-a aalgo] [-e ealgo] [-l keylen] [-s sectorsize] prov"
197	},
198	{ "configure", G_FLAG_VERBOSE, eli_main,
199	    {
200		{ 'b', "boot", NULL, G_TYPE_BOOL },
201		{ 'B', "noboot", NULL, G_TYPE_BOOL },
202		{ 'd', "displaypass", NULL, G_TYPE_BOOL },
203		{ 'D', "nodisplaypass", NULL, G_TYPE_BOOL },
204		{ 'g', "geliboot", NULL, G_TYPE_BOOL },
205		{ 'G', "nogeliboot", NULL, G_TYPE_BOOL },
206		{ 'r', "autoresize", NULL, G_TYPE_BOOL },
207		{ 'R', "noautoresize", NULL, G_TYPE_BOOL },
208		{ 't', "trim", NULL, G_TYPE_BOOL },
209		{ 'T', "notrim", NULL, G_TYPE_BOOL },
210		G_OPT_SENTINEL
211	    },
212	    "[-bBdDgGrRtT] prov ..."
213	},
214	{ "setkey", G_FLAG_VERBOSE, eli_main,
215	    {
216		{ 'i', "iterations", "-1", G_TYPE_NUMBER },
217		{ 'j', "passfile", G_VAL_OPTIONAL, G_TYPE_STRING | G_TYPE_MULTI },
218		{ 'J', "newpassfile", G_VAL_OPTIONAL, G_TYPE_STRING | G_TYPE_MULTI },
219		{ 'k', "keyfile", G_VAL_OPTIONAL, G_TYPE_STRING | G_TYPE_MULTI },
220		{ 'K', "newkeyfile", G_VAL_OPTIONAL, G_TYPE_STRING | G_TYPE_MULTI },
221		{ 'n', "keyno", "-1", G_TYPE_NUMBER },
222		{ 'p', "nopassphrase", NULL, G_TYPE_BOOL },
223		{ 'P', "nonewpassphrase", NULL, G_TYPE_BOOL },
224		G_OPT_SENTINEL
225	    },
226	    "[-pPv] [-n keyno] [-i iterations] [-j passfile] [-J newpassfile] [-k keyfile] [-K newkeyfile] prov"
227	},
228	{ "delkey", G_FLAG_VERBOSE, eli_main,
229	    {
230		{ 'a', "all", NULL, G_TYPE_BOOL },
231		{ 'f', "force", NULL, G_TYPE_BOOL },
232		{ 'n', "keyno", "-1", G_TYPE_NUMBER },
233		G_OPT_SENTINEL
234	    },
235	    "[-afv] [-n keyno] prov"
236	},
237	{ "suspend", G_FLAG_VERBOSE, NULL,
238	    {
239		{ 'a', "all", NULL, G_TYPE_BOOL },
240		G_OPT_SENTINEL
241	    },
242	    "[-v] -a | prov ..."
243	},
244	{ "resume", G_FLAG_VERBOSE, eli_main,
245	    {
246		{ 'j', "passfile", G_VAL_OPTIONAL, G_TYPE_STRING | G_TYPE_MULTI },
247		{ 'k', "keyfile", G_VAL_OPTIONAL, G_TYPE_STRING | G_TYPE_MULTI },
248		{ 'p', "nopassphrase", NULL, G_TYPE_BOOL },
249		G_OPT_SENTINEL
250	    },
251	    "[-pv] [-j passfile] [-k keyfile] prov"
252	},
253	{ "kill", G_FLAG_VERBOSE, eli_main,
254	    {
255		{ 'a', "all", NULL, G_TYPE_BOOL },
256		G_OPT_SENTINEL
257	    },
258	    "[-av] [prov ...]"
259	},
260	{ "backup", G_FLAG_VERBOSE, eli_main, G_NULL_OPTS,
261	    "[-v] prov file"
262	},
263	{ "restore", G_FLAG_VERBOSE, eli_main,
264	    {
265		{ 'f', "force", NULL, G_TYPE_BOOL },
266		G_OPT_SENTINEL
267	    },
268	    "[-fv] file prov"
269	},
270	{ "resize", G_FLAG_VERBOSE, eli_main,
271	    {
272		{ 's', "oldsize", NULL, G_TYPE_NUMBER },
273		G_OPT_SENTINEL
274	    },
275	    "[-v] -s oldsize prov"
276	},
277	{ "version", G_FLAG_LOADKLD, eli_main, G_NULL_OPTS,
278	    "[prov ...]"
279	},
280	{ "clear", G_FLAG_VERBOSE, eli_main, G_NULL_OPTS,
281	    "[-v] prov ..."
282	},
283	{ "dump", G_FLAG_VERBOSE, eli_main, G_NULL_OPTS,
284	    "[-v] prov ..."
285	},
286	G_CMD_SENTINEL
287};
288
289static int verbose = 0;
290
291static int
292eli_protect(struct gctl_req *req)
293{
294	struct rlimit rl;
295
296	/* Disable core dumps. */
297	rl.rlim_cur = 0;
298	rl.rlim_max = 0;
299	if (setrlimit(RLIMIT_CORE, &rl) == -1) {
300		gctl_error(req, "Cannot disable core dumps: %s.",
301		    strerror(errno));
302		return (-1);
303	}
304	/* Disable swapping. */
305	if (mlockall(MCL_FUTURE) == -1) {
306		gctl_error(req, "Cannot lock memory: %s.", strerror(errno));
307		return (-1);
308	}
309	return (0);
310}
311
312static void
313eli_main(struct gctl_req *req, unsigned int flags)
314{
315	const char *name;
316
317	if (eli_protect(req) == -1)
318		return;
319
320	if ((flags & G_FLAG_VERBOSE) != 0)
321		verbose = 1;
322
323	name = gctl_get_ascii(req, "verb");
324	if (name == NULL) {
325		gctl_error(req, "No '%s' argument.", "verb");
326		return;
327	}
328	if (strcmp(name, "init") == 0 || strcmp(name, "label") == 0)
329		eli_init(req);
330	else if (strcmp(name, "attach") == 0)
331		eli_attach(req);
332	else if (strcmp(name, "configure") == 0)
333		eli_configure(req);
334	else if (strcmp(name, "setkey") == 0)
335		eli_setkey(req);
336	else if (strcmp(name, "delkey") == 0)
337		eli_delkey(req);
338	else if (strcmp(name, "resume") == 0)
339		eli_resume(req);
340	else if (strcmp(name, "kill") == 0)
341		eli_kill(req);
342	else if (strcmp(name, "backup") == 0)
343		eli_backup(req);
344	else if (strcmp(name, "restore") == 0)
345		eli_restore(req);
346	else if (strcmp(name, "resize") == 0)
347		eli_resize(req);
348	else if (strcmp(name, "version") == 0)
349		eli_version(req);
350	else if (strcmp(name, "dump") == 0)
351		eli_dump(req);
352	else if (strcmp(name, "clear") == 0)
353		eli_clear(req);
354	else
355		gctl_error(req, "Unknown command: %s.", name);
356}
357
358static bool
359eli_is_attached(const char *prov)
360{
361	char name[MAXPATHLEN];
362
363	/*
364	 * Not the best way to do it, but the easiest.
365	 * We try to open provider and check if it is a GEOM provider
366	 * by asking about its sectorsize.
367	 */
368	snprintf(name, sizeof(name), "%s%s", prov, G_ELI_SUFFIX);
369	return (g_get_sectorsize(name) > 0);
370}
371
372static int
373eli_genkey_files(struct gctl_req *req, bool new, const char *type,
374    struct hmac_ctx *ctxp, char *passbuf, size_t passbufsize)
375{
376	char *p, buf[BUFSIZE], argname[16];
377	const char *file;
378	int error, fd, i;
379	ssize_t done;
380
381	assert((strcmp(type, "keyfile") == 0 && ctxp != NULL &&
382	    passbuf == NULL && passbufsize == 0) ||
383	    (strcmp(type, "passfile") == 0 && ctxp == NULL &&
384	    passbuf != NULL && passbufsize > 0));
385	assert(strcmp(type, "keyfile") == 0 || passbuf[0] == '\0');
386
387	for (i = 0; ; i++) {
388		snprintf(argname, sizeof(argname), "%s%s%d",
389		    new ? "new" : "", type, i);
390
391		/* No more {key,pass}files? */
392		if (!gctl_has_param(req, argname))
393			return (i);
394
395		file = gctl_get_ascii(req, "%s", argname);
396		assert(file != NULL);
397
398		if (strcmp(file, "-") == 0)
399			fd = STDIN_FILENO;
400		else {
401			fd = open(file, O_RDONLY);
402			if (fd == -1) {
403				gctl_error(req, "Cannot open %s %s: %s.",
404				    type, file, strerror(errno));
405				return (-1);
406			}
407		}
408		if (strcmp(type, "keyfile") == 0) {
409			while ((done = read(fd, buf, sizeof(buf))) > 0)
410				g_eli_crypto_hmac_update(ctxp, buf, done);
411		} else /* if (strcmp(type, "passfile") == 0) */ {
412			assert(strcmp(type, "passfile") == 0);
413
414			while ((done = read(fd, buf, sizeof(buf) - 1)) > 0) {
415				buf[done] = '\0';
416				p = strchr(buf, '\n');
417				if (p != NULL) {
418					*p = '\0';
419					done = p - buf;
420				}
421				if (strlcat(passbuf, buf, passbufsize) >=
422				    passbufsize) {
423					gctl_error(req,
424					    "Passphrase in %s too long.", file);
425					explicit_bzero(buf, sizeof(buf));
426					return (-1);
427				}
428				if (p != NULL)
429					break;
430			}
431		}
432		error = errno;
433		if (strcmp(file, "-") != 0)
434			close(fd);
435		explicit_bzero(buf, sizeof(buf));
436		if (done == -1) {
437			gctl_error(req, "Cannot read %s %s: %s.",
438			    type, file, strerror(error));
439			return (-1);
440		}
441	}
442	/* NOTREACHED */
443}
444
445static int
446eli_genkey_passphrase_prompt(struct gctl_req *req, bool new, char *passbuf,
447    size_t passbufsize)
448{
449	char *p;
450
451	for (;;) {
452		p = readpassphrase(
453		    new ? "Enter new passphrase: " : "Enter passphrase: ",
454		    passbuf, passbufsize, RPP_ECHO_OFF | RPP_REQUIRE_TTY);
455		if (p == NULL) {
456			explicit_bzero(passbuf, passbufsize);
457			gctl_error(req, "Cannot read passphrase: %s.",
458			    strerror(errno));
459			return (-1);
460		}
461
462		if (new) {
463			char tmpbuf[BUFSIZE];
464
465			p = readpassphrase("Reenter new passphrase: ",
466			    tmpbuf, sizeof(tmpbuf),
467			    RPP_ECHO_OFF | RPP_REQUIRE_TTY);
468			if (p == NULL) {
469				explicit_bzero(passbuf, passbufsize);
470				gctl_error(req,
471				    "Cannot read passphrase: %s.",
472				    strerror(errno));
473				return (-1);
474			}
475
476			if (strcmp(passbuf, tmpbuf) != 0) {
477				explicit_bzero(passbuf, passbufsize);
478				fprintf(stderr, "They didn't match.\n");
479				continue;
480			}
481			explicit_bzero(tmpbuf, sizeof(tmpbuf));
482		}
483		return (0);
484	}
485	/* NOTREACHED */
486}
487
488static int
489eli_genkey_passphrase(struct gctl_req *req, struct g_eli_metadata *md, bool new,
490    struct hmac_ctx *ctxp)
491{
492	char passbuf[BUFSIZE];
493	bool nopassphrase;
494	int nfiles;
495
496	/*
497	 * Return error if the 'do not use passphrase' flag was given but a
498	 * passfile was provided.
499	 */
500	nopassphrase =
501	    gctl_get_int(req, new ? "nonewpassphrase" : "nopassphrase");
502	if (nopassphrase) {
503		if (gctl_has_param(req, new ? "newpassfile0" : "passfile0")) {
504			gctl_error(req,
505			    "Options -%c and -%c are mutually exclusive.",
506			    new ? 'J' : 'j', new ? 'P' : 'p');
507			return (-1);
508		}
509		return (0);
510	}
511
512	/*
513	 * Return error if using a provider which does not require a passphrase
514	 * but the 'do not use passphrase' flag was not given.
515	 */
516	if (!new && md->md_iterations == -1) {
517		gctl_error(req, "Missing -p flag.");
518		return (-1);
519	}
520	passbuf[0] = '\0';
521
522	/* Use cached passphrase if defined. */
523	if (strlen(cached_passphrase) > 0) {
524		strlcpy(passbuf, cached_passphrase, sizeof(passbuf));
525	} else {
526		nfiles = eli_genkey_files(req, new, "passfile", NULL, passbuf,
527		    sizeof(passbuf));
528		if (nfiles == -1) {
529			return (-1);
530		} else if (nfiles == 0) {
531			if (eli_genkey_passphrase_prompt(req, new, passbuf,
532			    sizeof(passbuf)) == -1) {
533				return (-1);
534			}
535		}
536		/* Cache the passphrase for other providers. */
537		strlcpy(cached_passphrase, passbuf, sizeof(cached_passphrase));
538	}
539	/*
540	 * Field md_iterations equal to -1 means "choose some sane
541	 * value for me".
542	 */
543	if (md->md_iterations == -1) {
544		assert(new);
545		if (verbose)
546			printf("Calculating number of iterations...\n");
547		md->md_iterations = pkcs5v2_calculate(2000000);
548		assert(md->md_iterations > 0);
549		if (verbose) {
550			printf("Done, using %d iterations.\n",
551			    md->md_iterations);
552		}
553	}
554	/*
555	 * If md_iterations is equal to 0, user doesn't want PKCS#5v2.
556	 */
557	if (md->md_iterations == 0) {
558		g_eli_crypto_hmac_update(ctxp, md->md_salt,
559		    sizeof(md->md_salt));
560		g_eli_crypto_hmac_update(ctxp, passbuf, strlen(passbuf));
561	} else /* if (md->md_iterations > 0) */ {
562		unsigned char dkey[G_ELI_USERKEYLEN];
563
564		pkcs5v2_genkey(dkey, sizeof(dkey), md->md_salt,
565		    sizeof(md->md_salt), passbuf, md->md_iterations);
566		g_eli_crypto_hmac_update(ctxp, dkey, sizeof(dkey));
567		explicit_bzero(dkey, sizeof(dkey));
568	}
569	explicit_bzero(passbuf, sizeof(passbuf));
570
571	return (0);
572}
573
574static unsigned char *
575eli_genkey(struct gctl_req *req, struct g_eli_metadata *md, unsigned char *key,
576    bool new)
577{
578	struct hmac_ctx ctx;
579	bool nopassphrase;
580	int nfiles;
581
582	nopassphrase =
583	    gctl_get_int(req, new ? "nonewpassphrase" : "nopassphrase");
584
585	g_eli_crypto_hmac_init(&ctx, NULL, 0);
586
587	nfiles = eli_genkey_files(req, new, "keyfile", &ctx, NULL, 0);
588	if (nfiles == -1)
589		return (NULL);
590	else if (nfiles == 0 && nopassphrase) {
591		gctl_error(req, "No key components given.");
592		return (NULL);
593	}
594
595	if (eli_genkey_passphrase(req, md, new, &ctx) == -1)
596		return (NULL);
597
598	g_eli_crypto_hmac_final(&ctx, key, 0);
599
600	return (key);
601}
602
603static int
604eli_metadata_read(struct gctl_req *req, const char *prov,
605    struct g_eli_metadata *md)
606{
607	unsigned char sector[sizeof(struct g_eli_metadata)];
608	int error;
609
610	if (g_get_sectorsize(prov) == 0) {
611		int fd;
612
613		/* This is a file probably. */
614		fd = open(prov, O_RDONLY);
615		if (fd == -1) {
616			gctl_error(req, "Cannot open %s: %s.", prov,
617			    strerror(errno));
618			return (-1);
619		}
620		if (read(fd, sector, sizeof(sector)) != sizeof(sector)) {
621			gctl_error(req, "Cannot read metadata from %s: %s.",
622			    prov, strerror(errno));
623			close(fd);
624			return (-1);
625		}
626		close(fd);
627	} else {
628		/* This is a GEOM provider. */
629		error = g_metadata_read(prov, sector, sizeof(sector),
630		    G_ELI_MAGIC);
631		if (error != 0) {
632			gctl_error(req, "Cannot read metadata from %s: %s.",
633			    prov, strerror(error));
634			return (-1);
635		}
636	}
637	error = eli_metadata_decode(sector, md);
638	switch (error) {
639	case 0:
640		break;
641	case EOPNOTSUPP:
642		gctl_error(req,
643		    "Provider's %s metadata version %u is too new.\n"
644		    "geli: The highest supported version is %u.",
645		    prov, (unsigned int)md->md_version, G_ELI_VERSION);
646		return (-1);
647	case EINVAL:
648		gctl_error(req, "Inconsistent provider's %s metadata.", prov);
649		return (-1);
650	default:
651		gctl_error(req,
652		    "Unexpected error while decoding provider's %s metadata: %s.",
653		    prov, strerror(error));
654		return (-1);
655	}
656	return (0);
657}
658
659static int
660eli_metadata_store(struct gctl_req *req, const char *prov,
661    struct g_eli_metadata *md)
662{
663	unsigned char sector[sizeof(struct g_eli_metadata)];
664	int error;
665
666	eli_metadata_encode(md, sector);
667	if (g_get_sectorsize(prov) == 0) {
668		int fd;
669
670		/* This is a file probably. */
671		fd = open(prov, O_WRONLY | O_TRUNC);
672		if (fd == -1) {
673			gctl_error(req, "Cannot open %s: %s.", prov,
674			    strerror(errno));
675			explicit_bzero(sector, sizeof(sector));
676			return (-1);
677		}
678		if (write(fd, sector, sizeof(sector)) != sizeof(sector)) {
679			gctl_error(req, "Cannot write metadata to %s: %s.",
680			    prov, strerror(errno));
681			explicit_bzero(sector, sizeof(sector));
682			close(fd);
683			return (-1);
684		}
685		close(fd);
686	} else {
687		/* This is a GEOM provider. */
688		error = g_metadata_store(prov, sector, sizeof(sector));
689		if (error != 0) {
690			gctl_error(req, "Cannot write metadata to %s: %s.",
691			    prov, strerror(errno));
692			explicit_bzero(sector, sizeof(sector));
693			return (-1);
694		}
695	}
696	explicit_bzero(sector, sizeof(sector));
697	return (0);
698}
699
700static void
701eli_init(struct gctl_req *req)
702{
703	struct g_eli_metadata md;
704	struct gctl_req *r;
705	unsigned char sector[sizeof(struct g_eli_metadata)] __aligned(4);
706	unsigned char key[G_ELI_USERKEYLEN];
707	char backfile[MAXPATHLEN];
708	const char *str, *prov;
709	unsigned int secsize, eli_version;
710	off_t mediasize;
711	intmax_t val;
712	int error, i, nargs, nparams, param;
713	const int one = 1;
714
715	nargs = gctl_get_int(req, "nargs");
716	if (nargs <= 0) {
717		gctl_error(req, "Too few arguments.");
718		return;
719	}
720
721	/* Start generating metadata for provider(s) being initialized. */
722	explicit_bzero(&md, sizeof(md));
723	strlcpy(md.md_magic, G_ELI_MAGIC, sizeof(md.md_magic));
724	val = gctl_get_intmax(req, "mdversion");
725	if (val == -1) {
726		eli_version = G_ELI_VERSION;
727	} else if (val < 0 || val > G_ELI_VERSION) {
728		gctl_error(req,
729		    "Invalid version specified should be between %u and %u.",
730		    G_ELI_VERSION_00, G_ELI_VERSION);
731		return;
732	} else {
733		eli_version = val;
734	}
735	md.md_version = eli_version;
736	md.md_flags = G_ELI_FLAG_AUTORESIZE;
737	if (gctl_get_int(req, "boot"))
738		md.md_flags |= G_ELI_FLAG_BOOT;
739	if (gctl_get_int(req, "geliboot"))
740		md.md_flags |= G_ELI_FLAG_GELIBOOT;
741	if (gctl_get_int(req, "displaypass"))
742		md.md_flags |= G_ELI_FLAG_GELIDISPLAYPASS;
743	if (gctl_get_int(req, "notrim"))
744		md.md_flags |= G_ELI_FLAG_NODELETE;
745	if (gctl_get_int(req, "noautoresize"))
746		md.md_flags &= ~G_ELI_FLAG_AUTORESIZE;
747	md.md_ealgo = CRYPTO_ALGORITHM_MIN - 1;
748	str = gctl_get_ascii(req, "aalgo");
749	if (*str != '\0') {
750		if (eli_version < G_ELI_VERSION_01) {
751			gctl_error(req,
752			    "Data authentication is supported starting from version %u.",
753			    G_ELI_VERSION_01);
754			return;
755		}
756		md.md_aalgo = g_eli_str2aalgo(str);
757		if (md.md_aalgo >= CRYPTO_ALGORITHM_MIN &&
758		    md.md_aalgo <= CRYPTO_ALGORITHM_MAX) {
759			md.md_flags |= G_ELI_FLAG_AUTH;
760		} else {
761			/*
762			 * For backward compatibility, check if the -a option
763			 * was used to provide encryption algorithm.
764			 */
765			md.md_ealgo = g_eli_str2ealgo(str);
766			if (md.md_ealgo < CRYPTO_ALGORITHM_MIN ||
767			    md.md_ealgo > CRYPTO_ALGORITHM_MAX) {
768				gctl_error(req,
769				    "Invalid authentication algorithm.");
770				return;
771			} else {
772				fprintf(stderr, "warning: The -e option, not "
773				    "the -a option is now used to specify "
774				    "encryption algorithm to use.\n");
775			}
776		}
777	}
778	if (md.md_ealgo < CRYPTO_ALGORITHM_MIN ||
779	    md.md_ealgo > CRYPTO_ALGORITHM_MAX) {
780		str = gctl_get_ascii(req, "ealgo");
781		if (*str == '\0') {
782			if (eli_version < G_ELI_VERSION_05)
783				str = "aes-cbc";
784			else
785				str = GELI_ENC_ALGO;
786		}
787		md.md_ealgo = g_eli_str2ealgo(str);
788		if (md.md_ealgo < CRYPTO_ALGORITHM_MIN ||
789		    md.md_ealgo > CRYPTO_ALGORITHM_MAX) {
790			gctl_error(req, "Invalid encryption algorithm.");
791			return;
792		}
793		if (md.md_ealgo == CRYPTO_CAMELLIA_CBC &&
794		    eli_version < G_ELI_VERSION_04) {
795			gctl_error(req,
796			    "Camellia-CBC algorithm is supported starting from version %u.",
797			    G_ELI_VERSION_04);
798			return;
799		}
800		if (md.md_ealgo == CRYPTO_AES_XTS &&
801		    eli_version < G_ELI_VERSION_05) {
802			gctl_error(req,
803			    "AES-XTS algorithm is supported starting from version %u.",
804			    G_ELI_VERSION_05);
805			return;
806		}
807	}
808	val = gctl_get_intmax(req, "keylen");
809	md.md_keylen = val;
810	md.md_keylen = g_eli_keylen(md.md_ealgo, md.md_keylen);
811	if (md.md_keylen == 0) {
812		gctl_error(req, "Invalid key length.");
813		return;
814	}
815
816	val = gctl_get_intmax(req, "iterations");
817	if (val != -1) {
818		int nonewpassphrase;
819
820		/*
821		 * Don't allow to set iterations when there will be no
822		 * passphrase.
823		 */
824		nonewpassphrase = gctl_get_int(req, "nonewpassphrase");
825		if (nonewpassphrase) {
826			gctl_error(req,
827			    "Options -i and -P are mutually exclusive.");
828			return;
829		}
830	}
831	md.md_iterations = val;
832
833	val = gctl_get_intmax(req, "sectorsize");
834	if (val > sysconf(_SC_PAGE_SIZE)) {
835		fprintf(stderr,
836		    "warning: Using sectorsize bigger than the page size!\n");
837	}
838
839	md.md_keys = 0x01;
840
841	/*
842	 * Determine number of parameters in the parent geom request before the
843	 * nargs parameter and list of providers.
844	 */
845	nparams = req->narg - nargs - 1;
846
847	/* Create new child request for each provider and issue to kernel */
848	for (i = 0; i < nargs; i++) {
849		r = gctl_get_handle();
850
851		/* Copy each parameter from the parent request to the child */
852		for (param = 0; param < nparams; param++) {
853			gctl_ro_param(r, req->arg[param].name,
854			    req->arg[param].len, req->arg[param].value);
855		}
856
857		/* Add a single provider to the parameter list of the child */
858		gctl_ro_param(r, "nargs", sizeof(one), &one);
859		prov = gctl_get_ascii(req, "arg%d", i);
860		gctl_ro_param(r, "arg0", -1, prov);
861
862		mediasize = g_get_mediasize(prov);
863		secsize = g_get_sectorsize(prov);
864		if (mediasize == 0 || secsize == 0) {
865			gctl_error(r, "Cannot get information about %s: %s.",
866			    prov, strerror(errno));
867			goto out;
868		}
869
870		md.md_provsize = mediasize;
871
872		val = gctl_get_intmax(r, "sectorsize");
873		if (val == 0) {
874			md.md_sectorsize = secsize;
875		} else {
876			if (val < 0 || (val % secsize) != 0 || !powerof2(val)) {
877				gctl_error(r, "Invalid sector size.");
878				goto out;
879			}
880			md.md_sectorsize = val;
881		}
882
883		/* Use different salt and Master Key for each provider. */
884		arc4random_buf(md.md_salt, sizeof(md.md_salt));
885		arc4random_buf(md.md_mkeys, sizeof(md.md_mkeys));
886
887		/* Generate user key. */
888		if (eli_genkey(r, &md, key, true) == NULL) {
889			/*
890			 * Error generating key - details added to geom request
891			 * by eli_genkey().
892			 */
893			goto out;
894		}
895
896		/* Encrypt the first and the only Master Key. */
897		error = g_eli_mkey_encrypt(md.md_ealgo, key, md.md_keylen,
898		    md.md_mkeys);
899		if (error != 0) {
900			gctl_error(r, "Cannot encrypt Master Key: %s.",
901			    strerror(error));
902			goto out;
903		}
904
905		/* Convert metadata to on-disk format. */
906		eli_metadata_encode(&md, sector);
907
908		/* Store metadata to disk. */
909		error = g_metadata_store(prov, sector, sizeof(sector));
910		if (error != 0) {
911			gctl_error(r, "Cannot store metadata on %s: %s.", prov,
912			    strerror(error));
913			goto out;
914		}
915		if (verbose)
916			printf("Metadata value stored on %s.\n", prov);
917
918		/* Backup metadata to a file. */
919		const char *p = prov;
920		unsigned int j;
921
922		/*
923		 * Check if provider string includes the devfs mountpoint
924		 * (typically /dev/).
925		 */
926		if (strncmp(p, _PATH_DEV, sizeof(_PATH_DEV) - 1) == 0) {
927			/* Skip forward to the device filename only. */
928			p += sizeof(_PATH_DEV) - 1;
929		}
930
931		str = gctl_get_ascii(r, "backupfile");
932		if (str[0] != '\0') {
933			/* Backupfile given by the user, just copy it. */
934			strlcpy(backfile, str, sizeof(backfile));
935
936			/* If multiple providers have been initialized in one
937			 * command, and the backup filename has been specified
938			 * as anything other than "none", make the backup
939			 * filename unique for each provider. */
940			if (nargs > 1 && strcmp(backfile, "none") != 0) {
941				/*
942				 * Replace first occurrence of "PROV" with
943				 * provider name.
944				 */
945				str = strnstr(backfile, "PROV",
946				    sizeof(backfile));
947				if (str != NULL) {
948					char suffix[MAXPATHLEN];
949					j = str - backfile;
950					strlcpy(suffix, &backfile[j+4],
951					    sizeof(suffix));
952					backfile[j] = '\0';
953					strlcat(backfile, p, sizeof(backfile));
954					strlcat(backfile, suffix,
955					    sizeof(backfile));
956				} else {
957					/*
958					 * "PROV" not found in backfile, append
959					 * provider name.
960					 */
961					strlcat(backfile, "-",
962					    sizeof(backfile));
963					strlcat(backfile, p, sizeof(backfile));
964				}
965			}
966		} else {
967			/* Generate filename automatically. */
968			snprintf(backfile, sizeof(backfile), "%s%s.eli",
969			    GELI_BACKUP_DIR, p);
970			/* Replace all / with _. */
971			for (j = strlen(GELI_BACKUP_DIR); backfile[j] != '\0';
972			    j++) {
973				if (backfile[j] == '/')
974					backfile[j] = '_';
975			}
976		}
977		if (strcmp(backfile, "none") != 0 &&
978		    eli_backup_create(r, prov, backfile) == 0) {
979			printf("\nMetadata backup for provider %s can be found "
980			    "in %s\n", prov, backfile);
981			printf("and can be restored with the following "
982			    "command:\n");
983			printf("\n\t# geli restore %s %s\n\n", backfile, prov);
984		}
985
986out:
987		/*
988		 * Print error for this request, and set parent request error
989		 * message.
990		 */
991		if (r->error != NULL && r->error[0] != '\0') {
992			warnx("%s", r->error);
993			gctl_error(req, "There was an error with at least one "
994			    "provider.");
995		}
996
997		gctl_free(r);
998
999		/*
1000		 * Erase sensitive and provider specific data from memory.
1001		 */
1002		explicit_bzero(key, sizeof(key));
1003		explicit_bzero(sector, sizeof(sector));
1004		explicit_bzero(&md.md_provsize, sizeof(md.md_provsize));
1005		explicit_bzero(&md.md_sectorsize, sizeof(md.md_sectorsize));
1006		explicit_bzero(&md.md_salt, sizeof(md.md_salt));
1007		explicit_bzero(&md.md_mkeys, sizeof(md.md_mkeys));
1008	}
1009
1010	/* Clear the cached metadata, including keys. */
1011	explicit_bzero(&md, sizeof(md));
1012}
1013
1014static void
1015eli_attach(struct gctl_req *req)
1016{
1017	struct g_eli_metadata md;
1018	struct gctl_req *r;
1019	const char *prov;
1020	off_t mediasize;
1021	int i, nargs, nparams, param;
1022	const int one = 1;
1023
1024	nargs = gctl_get_int(req, "nargs");
1025	if (nargs <= 0) {
1026		gctl_error(req, "Too few arguments.");
1027		return;
1028	}
1029
1030	unsigned char key[G_ELI_USERKEYLEN];
1031
1032	/*
1033	 * Determine number of parameters in the parent geom request before the
1034	 * nargs parameter and list of providers.
1035	 */
1036	nparams = req->narg - nargs - 1;
1037
1038	/* Create new child request for each provider and issue to kernel */
1039	for (i = 0; i < nargs; i++) {
1040		r = gctl_get_handle();
1041
1042		/* Copy each parameter from the parent request to the child */
1043		for (param = 0; param < nparams; param++) {
1044			gctl_ro_param(r, req->arg[param].name,
1045			    req->arg[param].len, req->arg[param].value);
1046		}
1047
1048		/* Add a single provider to the parameter list of the child */
1049		gctl_ro_param(r, "nargs", sizeof(one), &one);
1050		prov = gctl_get_ascii(req, "arg%d", i);
1051		gctl_ro_param(r, "arg0", -1, prov);
1052
1053		if (eli_metadata_read(r, prov, &md) == -1) {
1054			/*
1055			 * Error reading metadata - details added to geom
1056			 * request by eli_metadata_read().
1057			 */
1058			goto out;
1059		}
1060
1061		mediasize = g_get_mediasize(prov);
1062		if (md.md_provsize != (uint64_t)mediasize) {
1063			gctl_error(r, "Provider size mismatch.");
1064			goto out;
1065		}
1066
1067		if (eli_genkey(r, &md, key, false) == NULL) {
1068			/*
1069			 * Error generating key - details added to geom request
1070			 * by eli_genkey().
1071			 */
1072			goto out;
1073		}
1074
1075		gctl_ro_param(r, "key", sizeof(key), key);
1076
1077		if (gctl_issue(r) == NULL) {
1078			if (verbose)
1079				printf("Attached to %s.\n", prov);
1080		}
1081
1082out:
1083		/*
1084		 * Print error for this request, and set parent request error
1085		 * message.
1086		 */
1087		if (r->error != NULL && r->error[0] != '\0') {
1088			warnx("%s", r->error);
1089			gctl_error(req, "There was an error with at least one "
1090			    "provider.");
1091		}
1092
1093		gctl_free(r);
1094
1095		/* Clear sensitive data from memory. */
1096		explicit_bzero(key, sizeof(key));
1097	}
1098
1099	/* Clear sensitive data from memory. */
1100	explicit_bzero(cached_passphrase, sizeof(cached_passphrase));
1101}
1102
1103static void
1104eli_configure_detached(struct gctl_req *req, const char *prov, int boot,
1105    int geliboot, int displaypass, int trim, int autoresize)
1106{
1107	struct g_eli_metadata md;
1108	bool changed = 0;
1109
1110	if (eli_metadata_read(req, prov, &md) == -1)
1111		return;
1112
1113	if (boot == 1 && (md.md_flags & G_ELI_FLAG_BOOT)) {
1114		if (verbose)
1115			printf("BOOT flag already configured for %s.\n", prov);
1116	} else if (boot == 0 && !(md.md_flags & G_ELI_FLAG_BOOT)) {
1117		if (verbose)
1118			printf("BOOT flag not configured for %s.\n", prov);
1119	} else if (boot >= 0) {
1120		if (boot)
1121			md.md_flags |= G_ELI_FLAG_BOOT;
1122		else
1123			md.md_flags &= ~G_ELI_FLAG_BOOT;
1124		changed = 1;
1125	}
1126
1127	if (geliboot == 1 && (md.md_flags & G_ELI_FLAG_GELIBOOT)) {
1128		if (verbose)
1129			printf("GELIBOOT flag already configured for %s.\n", prov);
1130	} else if (geliboot == 0 && !(md.md_flags & G_ELI_FLAG_GELIBOOT)) {
1131		if (verbose)
1132			printf("GELIBOOT flag not configured for %s.\n", prov);
1133	} else if (geliboot >= 0) {
1134		if (geliboot)
1135			md.md_flags |= G_ELI_FLAG_GELIBOOT;
1136		else
1137			md.md_flags &= ~G_ELI_FLAG_GELIBOOT;
1138		changed = 1;
1139	}
1140
1141	if (displaypass == 1 && (md.md_flags & G_ELI_FLAG_GELIDISPLAYPASS)) {
1142		if (verbose)
1143			printf("GELIDISPLAYPASS flag already configured for %s.\n", prov);
1144	} else if (displaypass == 0 &&
1145	    !(md.md_flags & G_ELI_FLAG_GELIDISPLAYPASS)) {
1146		if (verbose)
1147			printf("GELIDISPLAYPASS flag not configured for %s.\n", prov);
1148	} else if (displaypass >= 0) {
1149		if (displaypass)
1150			md.md_flags |= G_ELI_FLAG_GELIDISPLAYPASS;
1151		else
1152			md.md_flags &= ~G_ELI_FLAG_GELIDISPLAYPASS;
1153		changed = 1;
1154	}
1155
1156	if (trim == 0 && (md.md_flags & G_ELI_FLAG_NODELETE)) {
1157		if (verbose)
1158			printf("TRIM disable flag already configured for %s.\n", prov);
1159	} else if (trim == 1 && !(md.md_flags & G_ELI_FLAG_NODELETE)) {
1160		if (verbose)
1161			printf("TRIM disable flag not configured for %s.\n", prov);
1162	} else if (trim >= 0) {
1163		if (trim)
1164			md.md_flags &= ~G_ELI_FLAG_NODELETE;
1165		else
1166			md.md_flags |= G_ELI_FLAG_NODELETE;
1167		changed = 1;
1168	}
1169
1170	if (autoresize == 1 && (md.md_flags & G_ELI_FLAG_AUTORESIZE)) {
1171		if (verbose)
1172			printf("AUTORESIZE flag already configured for %s.\n", prov);
1173	} else if (autoresize == 0 && !(md.md_flags & G_ELI_FLAG_AUTORESIZE)) {
1174		if (verbose)
1175			printf("AUTORESIZE flag not configured for %s.\n", prov);
1176	} else if (autoresize >= 0) {
1177		if (autoresize)
1178			md.md_flags |= G_ELI_FLAG_AUTORESIZE;
1179		else
1180			md.md_flags &= ~G_ELI_FLAG_AUTORESIZE;
1181		changed = 1;
1182	}
1183
1184	if (changed)
1185		eli_metadata_store(req, prov, &md);
1186	explicit_bzero(&md, sizeof(md));
1187}
1188
1189static void
1190eli_configure(struct gctl_req *req)
1191{
1192	const char *prov;
1193	bool boot, noboot, geliboot, nogeliboot, displaypass, nodisplaypass;
1194	bool autoresize, noautoresize, trim, notrim;
1195	int doboot, dogeliboot, dodisplaypass, dotrim, doautoresize;
1196	int i, nargs;
1197
1198	nargs = gctl_get_int(req, "nargs");
1199	if (nargs == 0) {
1200		gctl_error(req, "Too few arguments.");
1201		return;
1202	}
1203
1204	boot = gctl_get_int(req, "boot");
1205	noboot = gctl_get_int(req, "noboot");
1206	geliboot = gctl_get_int(req, "geliboot");
1207	nogeliboot = gctl_get_int(req, "nogeliboot");
1208	displaypass = gctl_get_int(req, "displaypass");
1209	nodisplaypass = gctl_get_int(req, "nodisplaypass");
1210	trim = gctl_get_int(req, "trim");
1211	notrim = gctl_get_int(req, "notrim");
1212	autoresize = gctl_get_int(req, "autoresize");
1213	noautoresize = gctl_get_int(req, "noautoresize");
1214
1215	doboot = -1;
1216	if (boot && noboot) {
1217		gctl_error(req, "Options -b and -B are mutually exclusive.");
1218		return;
1219	}
1220	if (boot)
1221		doboot = 1;
1222	else if (noboot)
1223		doboot = 0;
1224
1225	dogeliboot = -1;
1226	if (geliboot && nogeliboot) {
1227		gctl_error(req, "Options -g and -G are mutually exclusive.");
1228		return;
1229	}
1230	if (geliboot)
1231		dogeliboot = 1;
1232	else if (nogeliboot)
1233		dogeliboot = 0;
1234
1235	dodisplaypass = -1;
1236	if (displaypass && nodisplaypass) {
1237		gctl_error(req, "Options -d and -D are mutually exclusive.");
1238		return;
1239	}
1240	if (displaypass)
1241		dodisplaypass = 1;
1242	else if (nodisplaypass)
1243		dodisplaypass = 0;
1244
1245	dotrim = -1;
1246	if (trim && notrim) {
1247		gctl_error(req, "Options -t and -T are mutually exclusive.");
1248		return;
1249	}
1250	if (trim)
1251		dotrim = 1;
1252	else if (notrim)
1253		dotrim = 0;
1254
1255	doautoresize = -1;
1256	if (autoresize && noautoresize) {
1257		gctl_error(req, "Options -r and -R are mutually exclusive.");
1258		return;
1259	}
1260	if (autoresize)
1261		doautoresize = 1;
1262	else if (noautoresize)
1263		doautoresize = 0;
1264
1265	if (doboot == -1 && dogeliboot == -1 && dodisplaypass == -1 &&
1266	    dotrim == -1 && doautoresize == -1) {
1267		gctl_error(req, "No option given.");
1268		return;
1269	}
1270
1271	/* First attached providers. */
1272	gctl_issue(req);
1273	/* Now the rest. */
1274	for (i = 0; i < nargs; i++) {
1275		prov = gctl_get_ascii(req, "arg%d", i);
1276		if (!eli_is_attached(prov)) {
1277			eli_configure_detached(req, prov, doboot, dogeliboot,
1278			    dodisplaypass, dotrim, doautoresize);
1279		}
1280	}
1281}
1282
1283static void
1284eli_setkey_attached(struct gctl_req *req, struct g_eli_metadata *md)
1285{
1286	unsigned char key[G_ELI_USERKEYLEN];
1287	intmax_t val, old = 0;
1288	int error;
1289
1290	val = gctl_get_intmax(req, "iterations");
1291	/* Check if iterations number should be changed. */
1292	if (val != -1)
1293		md->md_iterations = val;
1294	else
1295		old = md->md_iterations;
1296
1297	/* Generate key for Master Key encryption. */
1298	if (eli_genkey(req, md, key, true) == NULL) {
1299		explicit_bzero(key, sizeof(key));
1300		return;
1301	}
1302	/*
1303	 * If number of iterations has changed, but wasn't given as a
1304	 * command-line argument, update the request.
1305	 */
1306	if (val == -1 && md->md_iterations != old) {
1307		error = gctl_change_param(req, "iterations", sizeof(intmax_t),
1308		    &md->md_iterations);
1309		assert(error == 0);
1310	}
1311
1312	gctl_ro_param(req, "key", sizeof(key), key);
1313	gctl_issue(req);
1314	explicit_bzero(key, sizeof(key));
1315}
1316
1317static void
1318eli_setkey_detached(struct gctl_req *req, const char *prov,
1319 struct g_eli_metadata *md)
1320{
1321	unsigned char key[G_ELI_USERKEYLEN], mkey[G_ELI_DATAIVKEYLEN];
1322	unsigned char *mkeydst;
1323	unsigned int nkey;
1324	intmax_t val;
1325	int error;
1326
1327	if (md->md_keys == 0) {
1328		gctl_error(req, "No valid keys on %s.", prov);
1329		return;
1330	}
1331
1332	/* Generate key for Master Key decryption. */
1333	if (eli_genkey(req, md, key, false) == NULL) {
1334		explicit_bzero(key, sizeof(key));
1335		return;
1336	}
1337
1338	/* Decrypt Master Key. */
1339	error = g_eli_mkey_decrypt_any(md, key, mkey, &nkey);
1340	explicit_bzero(key, sizeof(key));
1341	if (error != 0) {
1342		explicit_bzero(md, sizeof(*md));
1343		if (error == -1)
1344			gctl_error(req, "Wrong key for %s.", prov);
1345		else /* if (error > 0) */ {
1346			gctl_error(req, "Cannot decrypt Master Key: %s.",
1347			    strerror(error));
1348		}
1349		return;
1350	}
1351	if (verbose)
1352		printf("Decrypted Master Key %u.\n", nkey);
1353
1354	val = gctl_get_intmax(req, "keyno");
1355	if (val != -1)
1356		nkey = val;
1357#if 0
1358	else
1359		; /* Use the key number which was found during decryption. */
1360#endif
1361	if (nkey >= G_ELI_MAXMKEYS) {
1362		gctl_error(req, "Invalid '%s' argument.", "keyno");
1363		return;
1364	}
1365
1366	val = gctl_get_intmax(req, "iterations");
1367	/* Check if iterations number should and can be changed. */
1368	if (val != -1 && md->md_iterations == -1) {
1369		md->md_iterations = val;
1370	} else if (val != -1 && val != md->md_iterations) {
1371		if (bitcount32(md->md_keys) != 1) {
1372			gctl_error(req, "To be able to use '-i' option, only "
1373			    "one key can be defined.");
1374			return;
1375		}
1376		if (md->md_keys != (1 << nkey)) {
1377			gctl_error(req, "Only already defined key can be "
1378			    "changed when '-i' option is used.");
1379			return;
1380		}
1381		md->md_iterations = val;
1382	}
1383
1384	mkeydst = md->md_mkeys + nkey * G_ELI_MKEYLEN;
1385	md->md_keys |= (1 << nkey);
1386
1387	bcopy(mkey, mkeydst, sizeof(mkey));
1388	explicit_bzero(mkey, sizeof(mkey));
1389
1390	/* Generate key for Master Key encryption. */
1391	if (eli_genkey(req, md, key, true) == NULL) {
1392		explicit_bzero(key, sizeof(key));
1393		explicit_bzero(md, sizeof(*md));
1394		return;
1395	}
1396
1397	/* Encrypt the Master-Key with the new key. */
1398	error = g_eli_mkey_encrypt(md->md_ealgo, key, md->md_keylen, mkeydst);
1399	explicit_bzero(key, sizeof(key));
1400	if (error != 0) {
1401		explicit_bzero(md, sizeof(*md));
1402		gctl_error(req, "Cannot encrypt Master Key: %s.",
1403		    strerror(error));
1404		return;
1405	}
1406
1407	/* Store metadata with fresh key. */
1408	eli_metadata_store(req, prov, md);
1409	explicit_bzero(md, sizeof(*md));
1410}
1411
1412static void
1413eli_setkey(struct gctl_req *req)
1414{
1415	struct g_eli_metadata md;
1416	const char *prov;
1417	int nargs;
1418
1419	nargs = gctl_get_int(req, "nargs");
1420	if (nargs != 1) {
1421		gctl_error(req, "Invalid number of arguments.");
1422		return;
1423	}
1424	prov = gctl_get_ascii(req, "arg0");
1425
1426	if (eli_metadata_read(req, prov, &md) == -1)
1427		return;
1428
1429	if (eli_is_attached(prov))
1430		eli_setkey_attached(req, &md);
1431	else
1432		eli_setkey_detached(req, prov, &md);
1433
1434	if (req->error == NULL || req->error[0] == '\0') {
1435		printf("Note, that the master key encrypted with old keys "
1436		    "and/or passphrase may still exists in a metadata backup "
1437		    "file.\n");
1438	}
1439}
1440
1441static void
1442eli_delkey_attached(struct gctl_req *req, const char *prov __unused)
1443{
1444
1445	gctl_issue(req);
1446}
1447
1448static void
1449eli_delkey_detached(struct gctl_req *req, const char *prov)
1450{
1451	struct g_eli_metadata md;
1452	unsigned char *mkeydst;
1453	unsigned int nkey;
1454	intmax_t val;
1455	bool all, force;
1456
1457	if (eli_metadata_read(req, prov, &md) == -1)
1458		return;
1459
1460	all = gctl_get_int(req, "all");
1461	if (all)
1462		arc4random_buf(md.md_mkeys, sizeof(md.md_mkeys));
1463	else {
1464		force = gctl_get_int(req, "force");
1465		val = gctl_get_intmax(req, "keyno");
1466		if (val == -1) {
1467			gctl_error(req, "Key number has to be specified.");
1468			return;
1469		}
1470		nkey = val;
1471		if (nkey >= G_ELI_MAXMKEYS) {
1472			gctl_error(req, "Invalid '%s' argument.", "keyno");
1473			return;
1474		}
1475		if (!(md.md_keys & (1 << nkey)) && !force) {
1476			gctl_error(req, "Master Key %u is not set.", nkey);
1477			return;
1478		}
1479		md.md_keys &= ~(1 << nkey);
1480		if (md.md_keys == 0 && !force) {
1481			gctl_error(req, "This is the last Master Key. Use '-f' "
1482			    "option if you really want to remove it.");
1483			return;
1484		}
1485		mkeydst = md.md_mkeys + nkey * G_ELI_MKEYLEN;
1486		arc4random_buf(mkeydst, G_ELI_MKEYLEN);
1487	}
1488
1489	eli_metadata_store(req, prov, &md);
1490	explicit_bzero(&md, sizeof(md));
1491}
1492
1493static void
1494eli_delkey(struct gctl_req *req)
1495{
1496	const char *prov;
1497	int nargs;
1498
1499	nargs = gctl_get_int(req, "nargs");
1500	if (nargs != 1) {
1501		gctl_error(req, "Invalid number of arguments.");
1502		return;
1503	}
1504	prov = gctl_get_ascii(req, "arg0");
1505
1506	if (eli_is_attached(prov))
1507		eli_delkey_attached(req, prov);
1508	else
1509		eli_delkey_detached(req, prov);
1510}
1511
1512static void
1513eli_resume(struct gctl_req *req)
1514{
1515	struct g_eli_metadata md;
1516	unsigned char key[G_ELI_USERKEYLEN];
1517	const char *prov;
1518	off_t mediasize;
1519	int nargs;
1520
1521	nargs = gctl_get_int(req, "nargs");
1522	if (nargs != 1) {
1523		gctl_error(req, "Invalid number of arguments.");
1524		return;
1525	}
1526	prov = gctl_get_ascii(req, "arg0");
1527
1528	if (eli_metadata_read(req, prov, &md) == -1)
1529		return;
1530
1531	mediasize = g_get_mediasize(prov);
1532	if (md.md_provsize != (uint64_t)mediasize) {
1533		gctl_error(req, "Provider size mismatch.");
1534		return;
1535	}
1536
1537	if (eli_genkey(req, &md, key, false) == NULL) {
1538		explicit_bzero(key, sizeof(key));
1539		return;
1540	}
1541
1542	gctl_ro_param(req, "key", sizeof(key), key);
1543	if (gctl_issue(req) == NULL) {
1544		if (verbose)
1545			printf("Resumed %s.\n", prov);
1546	}
1547	explicit_bzero(key, sizeof(key));
1548}
1549
1550static int
1551eli_trash_metadata(struct gctl_req *req, const char *prov, int fd, off_t offset)
1552{
1553	unsigned int overwrites;
1554	unsigned char *sector;
1555	ssize_t size;
1556	int error;
1557
1558	size = sizeof(overwrites);
1559	if (sysctlbyname("kern.geom.eli.overwrites", &overwrites, &size,
1560	    NULL, 0) == -1 || overwrites == 0) {
1561		overwrites = G_ELI_OVERWRITES;
1562	}
1563
1564	size = g_sectorsize(fd);
1565	if (size <= 0) {
1566		gctl_error(req, "Cannot obtain provider sector size %s: %s.",
1567		    prov, strerror(errno));
1568		return (-1);
1569	}
1570	sector = malloc(size);
1571	if (sector == NULL) {
1572		gctl_error(req, "Cannot allocate %zd bytes of memory.", size);
1573		return (-1);
1574	}
1575
1576	error = 0;
1577	do {
1578		arc4random_buf(sector, size);
1579		if (pwrite(fd, sector, size, offset) != size) {
1580			if (error == 0)
1581				error = errno;
1582		}
1583		(void)g_flush(fd);
1584	} while (--overwrites > 0);
1585	free(sector);
1586	if (error != 0) {
1587		gctl_error(req, "Cannot trash metadata on provider %s: %s.",
1588		    prov, strerror(error));
1589		return (-1);
1590	}
1591	return (0);
1592}
1593
1594static void
1595eli_kill_detached(struct gctl_req *req, const char *prov)
1596{
1597	off_t offset;
1598	int fd;
1599
1600	/*
1601	 * NOTE: Maybe we should verify if this is geli provider first,
1602	 *       but 'kill' command is quite critical so better don't waste
1603	 *       the time.
1604	 */
1605#if 0
1606	error = g_metadata_read(prov, (unsigned char *)&md, sizeof(md),
1607	    G_ELI_MAGIC);
1608	if (error != 0) {
1609		gctl_error(req, "Cannot read metadata from %s: %s.", prov,
1610		    strerror(error));
1611		return;
1612	}
1613#endif
1614
1615	fd = g_open(prov, 1);
1616	if (fd == -1) {
1617		gctl_error(req, "Cannot open provider %s: %s.", prov,
1618		    strerror(errno));
1619		return;
1620	}
1621	offset = g_mediasize(fd) - g_sectorsize(fd);
1622	if (offset <= 0) {
1623		gctl_error(req,
1624		    "Cannot obtain media size or sector size for provider %s: %s.",
1625		    prov, strerror(errno));
1626		(void)g_close(fd);
1627		return;
1628	}
1629	(void)eli_trash_metadata(req, prov, fd, offset);
1630	(void)g_close(fd);
1631}
1632
1633static void
1634eli_kill(struct gctl_req *req)
1635{
1636	const char *prov;
1637	int i, nargs, all;
1638
1639	nargs = gctl_get_int(req, "nargs");
1640	all = gctl_get_int(req, "all");
1641	if (!all && nargs == 0) {
1642		gctl_error(req, "Too few arguments.");
1643		return;
1644	}
1645	/*
1646	 * How '-a' option combine with a list of providers:
1647	 * Delete Master Keys from all attached providers:
1648	 * geli kill -a
1649	 * Delete Master Keys from all attached providers and from
1650	 * detached da0 and da1:
1651	 * geli kill -a da0 da1
1652	 * Delete Master Keys from (attached or detached) da0 and da1:
1653	 * geli kill da0 da1
1654	 */
1655
1656	/* First detached providers. */
1657	for (i = 0; i < nargs; i++) {
1658		prov = gctl_get_ascii(req, "arg%d", i);
1659		if (!eli_is_attached(prov))
1660			eli_kill_detached(req, prov);
1661	}
1662	/* Now attached providers. */
1663	gctl_issue(req);
1664}
1665
1666static int
1667eli_backup_create(struct gctl_req *req, const char *prov, const char *file)
1668{
1669	unsigned char *sector;
1670	ssize_t secsize;
1671	int error, filefd, ret;
1672
1673	ret = -1;
1674	filefd = -1;
1675	sector = NULL;
1676	secsize = 0;
1677
1678	secsize = g_get_sectorsize(prov);
1679	if (secsize == 0) {
1680		gctl_error(req, "Cannot get informations about %s: %s.", prov,
1681		    strerror(errno));
1682		goto out;
1683	}
1684	sector = malloc(secsize);
1685	if (sector == NULL) {
1686		gctl_error(req, "Cannot allocate memory.");
1687		goto out;
1688	}
1689	/* Read metadata from the provider. */
1690	error = g_metadata_read(prov, sector, secsize, G_ELI_MAGIC);
1691	if (error != 0) {
1692		gctl_error(req, "Unable to read metadata from %s: %s.", prov,
1693		    strerror(error));
1694		goto out;
1695	}
1696
1697	filefd = open(file, O_WRONLY | O_TRUNC | O_CREAT, 0600);
1698	if (filefd == -1) {
1699		gctl_error(req, "Unable to open %s: %s.", file,
1700		    strerror(errno));
1701		goto out;
1702	}
1703	/* Write metadata to the destination file. */
1704	if (write(filefd, sector, secsize) != secsize) {
1705		gctl_error(req, "Unable to write to %s: %s.", file,
1706		    strerror(errno));
1707		(void)close(filefd);
1708		(void)unlink(file);
1709		goto out;
1710	}
1711	(void)fsync(filefd);
1712	(void)close(filefd);
1713	/* Success. */
1714	ret = 0;
1715out:
1716	if (sector != NULL) {
1717		explicit_bzero(sector, secsize);
1718		free(sector);
1719	}
1720	return (ret);
1721}
1722
1723static void
1724eli_backup(struct gctl_req *req)
1725{
1726	const char *file, *prov;
1727	int nargs;
1728
1729	nargs = gctl_get_int(req, "nargs");
1730	if (nargs != 2) {
1731		gctl_error(req, "Invalid number of arguments.");
1732		return;
1733	}
1734	prov = gctl_get_ascii(req, "arg0");
1735	file = gctl_get_ascii(req, "arg1");
1736
1737	eli_backup_create(req, prov, file);
1738}
1739
1740static void
1741eli_restore(struct gctl_req *req)
1742{
1743	struct g_eli_metadata md;
1744	const char *file, *prov;
1745	off_t mediasize;
1746	int nargs;
1747
1748	nargs = gctl_get_int(req, "nargs");
1749	if (nargs != 2) {
1750		gctl_error(req, "Invalid number of arguments.");
1751		return;
1752	}
1753	file = gctl_get_ascii(req, "arg0");
1754	prov = gctl_get_ascii(req, "arg1");
1755
1756	/* Read metadata from the backup file. */
1757	if (eli_metadata_read(req, file, &md) == -1)
1758		return;
1759	/* Obtain provider's mediasize. */
1760	mediasize = g_get_mediasize(prov);
1761	if (mediasize == 0) {
1762		gctl_error(req, "Cannot get informations about %s: %s.", prov,
1763		    strerror(errno));
1764		return;
1765	}
1766	/* Check if the provider size has changed since we did the backup. */
1767	if (md.md_provsize != (uint64_t)mediasize) {
1768		if (gctl_get_int(req, "force")) {
1769			md.md_provsize = mediasize;
1770		} else {
1771			gctl_error(req, "Provider size mismatch: "
1772			    "wrong backup file?");
1773			return;
1774		}
1775	}
1776	/* Write metadata to the provider. */
1777	(void)eli_metadata_store(req, prov, &md);
1778}
1779
1780static void
1781eli_resize(struct gctl_req *req)
1782{
1783	struct g_eli_metadata md;
1784	const char *prov;
1785	unsigned char *sector;
1786	ssize_t secsize;
1787	off_t mediasize, oldsize;
1788	int error, nargs, provfd;
1789
1790	nargs = gctl_get_int(req, "nargs");
1791	if (nargs != 1) {
1792		gctl_error(req, "Invalid number of arguments.");
1793		return;
1794	}
1795	prov = gctl_get_ascii(req, "arg0");
1796
1797	provfd = -1;
1798	sector = NULL;
1799	secsize = 0;
1800
1801	provfd = g_open(prov, 1);
1802	if (provfd == -1) {
1803		gctl_error(req, "Cannot open %s: %s.", prov, strerror(errno));
1804		goto out;
1805	}
1806
1807	mediasize = g_mediasize(provfd);
1808	secsize = g_sectorsize(provfd);
1809	if (mediasize == -1 || secsize == -1) {
1810		gctl_error(req, "Cannot get information about %s: %s.", prov,
1811		    strerror(errno));
1812		goto out;
1813	}
1814
1815	sector = malloc(secsize);
1816	if (sector == NULL) {
1817		gctl_error(req, "Cannot allocate memory.");
1818		goto out;
1819	}
1820
1821	oldsize = gctl_get_intmax(req, "oldsize");
1822	if (oldsize < 0 || oldsize > mediasize) {
1823		gctl_error(req, "Invalid oldsize: Out of range.");
1824		goto out;
1825	}
1826	if (oldsize == mediasize) {
1827		gctl_error(req, "Size hasn't changed.");
1828		goto out;
1829	}
1830
1831	/* Read metadata from the 'oldsize' offset. */
1832	if (pread(provfd, sector, secsize, oldsize - secsize) != secsize) {
1833		gctl_error(req, "Cannot read old metadata: %s.",
1834		    strerror(errno));
1835		goto out;
1836	}
1837
1838	/* Check if this sector contains geli metadata. */
1839	error = eli_metadata_decode(sector, &md);
1840	switch (error) {
1841	case 0:
1842		break;
1843	case EOPNOTSUPP:
1844		gctl_error(req,
1845		    "Provider's %s metadata version %u is too new.\n"
1846		    "geli: The highest supported version is %u.",
1847		    prov, (unsigned int)md.md_version, G_ELI_VERSION);
1848		goto out;
1849	case EINVAL:
1850		gctl_error(req, "Inconsistent provider's %s metadata.", prov);
1851		goto out;
1852	default:
1853		gctl_error(req,
1854		    "Unexpected error while decoding provider's %s metadata: %s.",
1855		    prov, strerror(error));
1856		goto out;
1857	}
1858
1859	/*
1860	 * If the old metadata doesn't have a correct provider size, refuse
1861	 * to resize.
1862	 */
1863	if (md.md_provsize != (uint64_t)oldsize) {
1864		gctl_error(req, "Provider size mismatch at oldsize.");
1865		goto out;
1866	}
1867
1868	/*
1869	 * Update the old metadata with the current provider size and write
1870	 * it back to the correct place on the provider.
1871	 */
1872	md.md_provsize = mediasize;
1873	/* Write metadata to the provider. */
1874	(void)eli_metadata_store(req, prov, &md);
1875	/* Now trash the old metadata. */
1876	(void)eli_trash_metadata(req, prov, provfd, oldsize - secsize);
1877out:
1878	if (provfd != -1)
1879		(void)g_close(provfd);
1880	if (sector != NULL) {
1881		explicit_bzero(sector, secsize);
1882		free(sector);
1883	}
1884}
1885
1886static void
1887eli_version(struct gctl_req *req)
1888{
1889	struct g_eli_metadata md;
1890	const char *name;
1891	unsigned int eli_version;
1892	int error, i, nargs;
1893
1894	nargs = gctl_get_int(req, "nargs");
1895
1896	if (nargs == 0) {
1897		unsigned int kernver;
1898		ssize_t size;
1899
1900		size = sizeof(kernver);
1901		if (sysctlbyname("kern.geom.eli.version", &kernver, &size,
1902		    NULL, 0) == -1) {
1903			warn("Unable to obtain GELI kernel version");
1904		} else {
1905			printf("kernel: %u\n", kernver);
1906		}
1907		printf("userland: %u\n", G_ELI_VERSION);
1908		return;
1909	}
1910
1911	for (i = 0; i < nargs; i++) {
1912		name = gctl_get_ascii(req, "arg%d", i);
1913		error = g_metadata_read(name, (unsigned char *)&md,
1914		    sizeof(md), G_ELI_MAGIC);
1915		if (error != 0) {
1916			warn("%s: Unable to read metadata: %s.", name,
1917			    strerror(error));
1918			gctl_error(req, "Not fully done.");
1919			continue;
1920		}
1921		eli_version = le32dec(&md.md_version);
1922		printf("%s: %u\n", name, eli_version);
1923	}
1924}
1925
1926static void
1927eli_clear(struct gctl_req *req)
1928{
1929	const char *name;
1930	int error, i, nargs;
1931
1932	nargs = gctl_get_int(req, "nargs");
1933	if (nargs < 1) {
1934		gctl_error(req, "Too few arguments.");
1935		return;
1936	}
1937
1938	for (i = 0; i < nargs; i++) {
1939		name = gctl_get_ascii(req, "arg%d", i);
1940		error = g_metadata_clear(name, G_ELI_MAGIC);
1941		if (error != 0) {
1942			fprintf(stderr, "Cannot clear metadata on %s: %s.\n",
1943			    name, strerror(error));
1944			gctl_error(req, "Not fully done.");
1945			continue;
1946		}
1947		if (verbose)
1948			printf("Metadata cleared on %s.\n", name);
1949	}
1950}
1951
1952static void
1953eli_dump(struct gctl_req *req)
1954{
1955	struct g_eli_metadata md;
1956	const char *name;
1957	int i, nargs;
1958
1959	nargs = gctl_get_int(req, "nargs");
1960	if (nargs < 1) {
1961		gctl_error(req, "Too few arguments.");
1962		return;
1963	}
1964
1965	for (i = 0; i < nargs; i++) {
1966		name = gctl_get_ascii(req, "arg%d", i);
1967		if (eli_metadata_read(NULL, name, &md) == -1) {
1968			gctl_error(req, "Not fully done.");
1969			continue;
1970		}
1971		printf("Metadata on %s:\n", name);
1972		eli_metadata_dump(&md);
1973		printf("\n");
1974	}
1975}
1976