xref: /freebsd/lib/geom/eli/geom_eli.c (revision 4d3fc8b0570b29fb0d6ee9525f104d52176ff0d4)
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 
60 uint32_t lib_version = G_LIB_VERSION;
61 uint32_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  */
71 static char cached_passphrase[BUFSIZE] = "";
72 
73 static void eli_main(struct gctl_req *req, unsigned flags);
74 static void eli_init(struct gctl_req *req);
75 static void eli_attach(struct gctl_req *req);
76 static void eli_configure(struct gctl_req *req);
77 static void eli_setkey(struct gctl_req *req);
78 static void eli_delkey(struct gctl_req *req);
79 static void eli_resume(struct gctl_req *req);
80 static void eli_kill(struct gctl_req *req);
81 static void eli_backup(struct gctl_req *req);
82 static void eli_restore(struct gctl_req *req);
83 static void eli_resize(struct gctl_req *req);
84 static void eli_version(struct gctl_req *req);
85 static void eli_clear(struct gctl_req *req);
86 static void eli_dump(struct gctl_req *req);
87 
88 static 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  */
113 struct 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 
289 static int verbose = 0;
290 
291 static int
292 eli_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 
312 static void
313 eli_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 
358 static bool
359 eli_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 
372 static int
373 eli_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 
445 static int
446 eli_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 
488 static int
489 eli_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 
574 static bool
575 eli_init_key_hmac_ctx(struct gctl_req *req, struct hmac_ctx *ctx, bool new)
576 {
577 	int nfiles;
578 	bool nopassphrase;
579 
580 	nopassphrase =
581 	    gctl_get_int(req, new ? "nonewpassphrase" : "nopassphrase");
582 
583 	g_eli_crypto_hmac_init(ctx, NULL, 0);
584 	nfiles = eli_genkey_files(req, new, "keyfile", ctx, NULL, 0);
585 	if (nfiles == -1) {
586 		return (false);
587 	} else if (nfiles == 0 && nopassphrase) {
588 		gctl_error(req, "No key components given.");
589 		return (false);
590 	}
591 
592 	return (true);
593 }
594 
595 static unsigned char *
596 eli_genkey(struct gctl_req *req, const struct hmac_ctx *ctxtemplate,
597     struct g_eli_metadata *md, unsigned char *key, bool new)
598 {
599 	struct hmac_ctx ctx;
600 
601 	memcpy(&ctx, ctxtemplate, sizeof(ctx));
602 
603 	if (eli_genkey_passphrase(req, md, new, &ctx) == -1)
604 		return (NULL);
605 
606 	g_eli_crypto_hmac_final(&ctx, key, 0);
607 
608 	return (key);
609 }
610 
611 static unsigned char *
612 eli_genkey_single(struct gctl_req *req, struct g_eli_metadata *md,
613 		  unsigned char *key, bool new)
614 {
615 	struct hmac_ctx ctx;
616 	unsigned char *rkey;
617 
618 	if (!eli_init_key_hmac_ctx(req, &ctx, new)) {
619 		return (NULL);
620 	}
621 	rkey = eli_genkey(req, &ctx, md, key, new);
622 	explicit_bzero(&ctx, sizeof(ctx));
623 
624 	return (rkey);
625 }
626 
627 static int
628 eli_metadata_read(struct gctl_req *req, const char *prov,
629     struct g_eli_metadata *md)
630 {
631 	unsigned char sector[sizeof(struct g_eli_metadata)];
632 	int error;
633 
634 	if (g_get_sectorsize(prov) == 0) {
635 		int fd;
636 
637 		/* This is a file probably. */
638 		fd = open(prov, O_RDONLY);
639 		if (fd == -1) {
640 			gctl_error(req, "Cannot open %s: %s.", prov,
641 			    strerror(errno));
642 			return (-1);
643 		}
644 		if (read(fd, sector, sizeof(sector)) != sizeof(sector)) {
645 			gctl_error(req, "Cannot read metadata from %s: %s.",
646 			    prov, strerror(errno));
647 			close(fd);
648 			return (-1);
649 		}
650 		close(fd);
651 	} else {
652 		/* This is a GEOM provider. */
653 		error = g_metadata_read(prov, sector, sizeof(sector),
654 		    G_ELI_MAGIC);
655 		if (error != 0) {
656 			gctl_error(req, "Cannot read metadata from %s: %s.",
657 			    prov, strerror(error));
658 			return (-1);
659 		}
660 	}
661 	error = eli_metadata_decode(sector, md);
662 	switch (error) {
663 	case 0:
664 		break;
665 	case EOPNOTSUPP:
666 		gctl_error(req,
667 		    "Provider's %s metadata version %u is too new.\n"
668 		    "geli: The highest supported version is %u.",
669 		    prov, (unsigned int)md->md_version, G_ELI_VERSION);
670 		return (-1);
671 	case EINVAL:
672 		gctl_error(req, "Inconsistent provider's %s metadata.", prov);
673 		return (-1);
674 	default:
675 		gctl_error(req,
676 		    "Unexpected error while decoding provider's %s metadata: %s.",
677 		    prov, strerror(error));
678 		return (-1);
679 	}
680 	return (0);
681 }
682 
683 static int
684 eli_metadata_store(struct gctl_req *req, const char *prov,
685     struct g_eli_metadata *md)
686 {
687 	unsigned char sector[sizeof(struct g_eli_metadata)];
688 	int error;
689 
690 	eli_metadata_encode(md, sector);
691 	if (g_get_sectorsize(prov) == 0) {
692 		int fd;
693 
694 		/* This is a file probably. */
695 		fd = open(prov, O_WRONLY | O_TRUNC);
696 		if (fd == -1) {
697 			gctl_error(req, "Cannot open %s: %s.", prov,
698 			    strerror(errno));
699 			explicit_bzero(sector, sizeof(sector));
700 			return (-1);
701 		}
702 		if (write(fd, sector, sizeof(sector)) != sizeof(sector)) {
703 			gctl_error(req, "Cannot write metadata to %s: %s.",
704 			    prov, strerror(errno));
705 			explicit_bzero(sector, sizeof(sector));
706 			close(fd);
707 			return (-1);
708 		}
709 		close(fd);
710 	} else {
711 		/* This is a GEOM provider. */
712 		error = g_metadata_store(prov, sector, sizeof(sector));
713 		if (error != 0) {
714 			gctl_error(req, "Cannot write metadata to %s: %s.",
715 			    prov, strerror(errno));
716 			explicit_bzero(sector, sizeof(sector));
717 			return (-1);
718 		}
719 	}
720 	explicit_bzero(sector, sizeof(sector));
721 	return (0);
722 }
723 
724 static void
725 eli_init(struct gctl_req *req)
726 {
727 	struct g_eli_metadata md;
728 	struct gctl_req *r;
729 	unsigned char sector[sizeof(struct g_eli_metadata)] __aligned(4);
730 	unsigned char key[G_ELI_USERKEYLEN];
731 	char backfile[MAXPATHLEN];
732 	const char *str, *prov;
733 	unsigned int secsize, eli_version;
734 	off_t mediasize;
735 	intmax_t val;
736 	int error, i, nargs, nparams, param;
737 	const int one = 1;
738 	struct hmac_ctx ctxtemplate;
739 
740 	nargs = gctl_get_int(req, "nargs");
741 	if (nargs <= 0) {
742 		gctl_error(req, "Too few arguments.");
743 		return;
744 	}
745 
746 	/* Start generating metadata for provider(s) being initialized. */
747 	explicit_bzero(&md, sizeof(md));
748 	strlcpy(md.md_magic, G_ELI_MAGIC, sizeof(md.md_magic));
749 	val = gctl_get_intmax(req, "mdversion");
750 	if (val == -1) {
751 		eli_version = G_ELI_VERSION;
752 	} else if (val < 0 || val > G_ELI_VERSION) {
753 		gctl_error(req,
754 		    "Invalid version specified should be between %u and %u.",
755 		    G_ELI_VERSION_00, G_ELI_VERSION);
756 		return;
757 	} else {
758 		eli_version = val;
759 	}
760 	md.md_version = eli_version;
761 	md.md_flags = G_ELI_FLAG_AUTORESIZE;
762 	if (gctl_get_int(req, "boot"))
763 		md.md_flags |= G_ELI_FLAG_BOOT;
764 	if (gctl_get_int(req, "geliboot"))
765 		md.md_flags |= G_ELI_FLAG_GELIBOOT;
766 	if (gctl_get_int(req, "displaypass"))
767 		md.md_flags |= G_ELI_FLAG_GELIDISPLAYPASS;
768 	if (gctl_get_int(req, "notrim"))
769 		md.md_flags |= G_ELI_FLAG_NODELETE;
770 	if (gctl_get_int(req, "noautoresize"))
771 		md.md_flags &= ~G_ELI_FLAG_AUTORESIZE;
772 	md.md_ealgo = CRYPTO_ALGORITHM_MIN - 1;
773 	str = gctl_get_ascii(req, "aalgo");
774 	if (*str != '\0') {
775 		if (eli_version < G_ELI_VERSION_01) {
776 			gctl_error(req,
777 			    "Data authentication is supported starting from version %u.",
778 			    G_ELI_VERSION_01);
779 			return;
780 		}
781 		md.md_aalgo = g_eli_str2aalgo(str);
782 		if (md.md_aalgo >= CRYPTO_ALGORITHM_MIN &&
783 		    md.md_aalgo <= CRYPTO_ALGORITHM_MAX) {
784 			md.md_flags |= G_ELI_FLAG_AUTH;
785 		} else {
786 			/*
787 			 * For backward compatibility, check if the -a option
788 			 * was used to provide encryption algorithm.
789 			 */
790 			md.md_ealgo = g_eli_str2ealgo(str);
791 			if (md.md_ealgo < CRYPTO_ALGORITHM_MIN ||
792 			    md.md_ealgo > CRYPTO_ALGORITHM_MAX) {
793 				gctl_error(req,
794 				    "Invalid authentication algorithm.");
795 				return;
796 			} else {
797 				fprintf(stderr, "warning: The -e option, not "
798 				    "the -a option is now used to specify "
799 				    "encryption algorithm to use.\n");
800 			}
801 		}
802 	}
803 	if (md.md_ealgo < CRYPTO_ALGORITHM_MIN ||
804 	    md.md_ealgo > CRYPTO_ALGORITHM_MAX) {
805 		str = gctl_get_ascii(req, "ealgo");
806 		if (*str == '\0') {
807 			if (eli_version < G_ELI_VERSION_05)
808 				str = "aes-cbc";
809 			else
810 				str = GELI_ENC_ALGO;
811 		}
812 		md.md_ealgo = g_eli_str2ealgo(str);
813 		if (md.md_ealgo < CRYPTO_ALGORITHM_MIN ||
814 		    md.md_ealgo > CRYPTO_ALGORITHM_MAX) {
815 			gctl_error(req, "Invalid encryption algorithm.");
816 			return;
817 		}
818 		if (md.md_ealgo == CRYPTO_CAMELLIA_CBC &&
819 		    eli_version < G_ELI_VERSION_04) {
820 			gctl_error(req,
821 			    "Camellia-CBC algorithm is supported starting from version %u.",
822 			    G_ELI_VERSION_04);
823 			return;
824 		}
825 		if (md.md_ealgo == CRYPTO_AES_XTS &&
826 		    eli_version < G_ELI_VERSION_05) {
827 			gctl_error(req,
828 			    "AES-XTS algorithm is supported starting from version %u.",
829 			    G_ELI_VERSION_05);
830 			return;
831 		}
832 	}
833 	val = gctl_get_intmax(req, "keylen");
834 	md.md_keylen = val;
835 	md.md_keylen = g_eli_keylen(md.md_ealgo, md.md_keylen);
836 	if (md.md_keylen == 0) {
837 		gctl_error(req, "Invalid key length.");
838 		return;
839 	}
840 
841 	val = gctl_get_intmax(req, "iterations");
842 	if (val != -1) {
843 		int nonewpassphrase;
844 
845 		/*
846 		 * Don't allow to set iterations when there will be no
847 		 * passphrase.
848 		 */
849 		nonewpassphrase = gctl_get_int(req, "nonewpassphrase");
850 		if (nonewpassphrase) {
851 			gctl_error(req,
852 			    "Options -i and -P are mutually exclusive.");
853 			return;
854 		}
855 	}
856 	md.md_iterations = val;
857 
858 	val = gctl_get_intmax(req, "sectorsize");
859 	if (val > sysconf(_SC_PAGE_SIZE)) {
860 		fprintf(stderr,
861 		    "warning: Using sectorsize bigger than the page size!\n");
862 	}
863 
864 	md.md_keys = 0x01;
865 
866 	/*
867 	 * Determine number of parameters in the parent geom request before the
868 	 * nargs parameter and list of providers.
869 	 */
870 	nparams = req->narg - nargs - 1;
871 
872 	/* Generate HMAC context template. */
873 	if (!eli_init_key_hmac_ctx(req, &ctxtemplate, true))
874 		return;
875 
876 	/* Create new child request for each provider and issue to kernel */
877 	for (i = 0; i < nargs; i++) {
878 		r = gctl_get_handle();
879 
880 		/* Copy each parameter from the parent request to the child */
881 		for (param = 0; param < nparams; param++) {
882 			gctl_ro_param(r, req->arg[param].name,
883 			    req->arg[param].len, req->arg[param].value);
884 		}
885 
886 		/* Add a single provider to the parameter list of the child */
887 		gctl_ro_param(r, "nargs", sizeof(one), &one);
888 		prov = gctl_get_ascii(req, "arg%d", i);
889 		gctl_ro_param(r, "arg0", -1, prov);
890 
891 		mediasize = g_get_mediasize(prov);
892 		secsize = g_get_sectorsize(prov);
893 		if (mediasize == 0 || secsize == 0) {
894 			gctl_error(r, "Cannot get information about %s: %s.",
895 			    prov, strerror(errno));
896 			goto out;
897 		}
898 
899 		md.md_provsize = mediasize;
900 
901 		val = gctl_get_intmax(r, "sectorsize");
902 		if (val == 0) {
903 			md.md_sectorsize = secsize;
904 		} else {
905 			if (val < 0 || (val % secsize) != 0 || !powerof2(val)) {
906 				gctl_error(r, "Invalid sector size.");
907 				goto out;
908 			}
909 			md.md_sectorsize = val;
910 		}
911 
912 		/* Use different salt and Master Key for each provider. */
913 		arc4random_buf(md.md_salt, sizeof(md.md_salt));
914 		arc4random_buf(md.md_mkeys, sizeof(md.md_mkeys));
915 
916 		/* Generate user key. */
917 		if (eli_genkey(r, &ctxtemplate, &md, key, true) == NULL) {
918 			/*
919 			 * Error generating key - details added to geom request
920 			 * by eli_genkey().
921 			 */
922 			goto out;
923 		}
924 
925 		/* Encrypt the first and the only Master Key. */
926 		error = g_eli_mkey_encrypt(md.md_ealgo, key, md.md_keylen,
927 		    md.md_mkeys);
928 		if (error != 0) {
929 			gctl_error(r, "Cannot encrypt Master Key: %s.",
930 			    strerror(error));
931 			goto out;
932 		}
933 
934 		/* Convert metadata to on-disk format. */
935 		eli_metadata_encode(&md, sector);
936 
937 		/* Store metadata to disk. */
938 		error = g_metadata_store(prov, sector, sizeof(sector));
939 		if (error != 0) {
940 			gctl_error(r, "Cannot store metadata on %s: %s.", prov,
941 			    strerror(error));
942 			goto out;
943 		}
944 		if (verbose)
945 			printf("Metadata value stored on %s.\n", prov);
946 
947 		/* Backup metadata to a file. */
948 		const char *p = prov;
949 		unsigned int j;
950 
951 		/*
952 		 * Check if provider string includes the devfs mountpoint
953 		 * (typically /dev/).
954 		 */
955 		if (strncmp(p, _PATH_DEV, sizeof(_PATH_DEV) - 1) == 0) {
956 			/* Skip forward to the device filename only. */
957 			p += sizeof(_PATH_DEV) - 1;
958 		}
959 
960 		str = gctl_get_ascii(r, "backupfile");
961 		if (str[0] != '\0') {
962 			/* Backupfile given by the user, just copy it. */
963 			strlcpy(backfile, str, sizeof(backfile));
964 
965 			/* If multiple providers have been initialized in one
966 			 * command, and the backup filename has been specified
967 			 * as anything other than "none", make the backup
968 			 * filename unique for each provider. */
969 			if (nargs > 1 && strcmp(backfile, "none") != 0) {
970 				/*
971 				 * Replace first occurrence of "PROV" with
972 				 * provider name.
973 				 */
974 				str = strnstr(backfile, "PROV",
975 				    sizeof(backfile));
976 				if (str != NULL) {
977 					char suffix[MAXPATHLEN];
978 					j = str - backfile;
979 					strlcpy(suffix, &backfile[j+4],
980 					    sizeof(suffix));
981 					backfile[j] = '\0';
982 					strlcat(backfile, p, sizeof(backfile));
983 					strlcat(backfile, suffix,
984 					    sizeof(backfile));
985 				} else {
986 					/*
987 					 * "PROV" not found in backfile, append
988 					 * provider name.
989 					 */
990 					strlcat(backfile, "-",
991 					    sizeof(backfile));
992 					strlcat(backfile, p, sizeof(backfile));
993 				}
994 			}
995 		} else {
996 			/* Generate filename automatically. */
997 			snprintf(backfile, sizeof(backfile), "%s%s.eli",
998 			    GELI_BACKUP_DIR, p);
999 			/* Replace all / with _. */
1000 			for (j = strlen(GELI_BACKUP_DIR); backfile[j] != '\0';
1001 			    j++) {
1002 				if (backfile[j] == '/')
1003 					backfile[j] = '_';
1004 			}
1005 		}
1006 		if (strcmp(backfile, "none") != 0 &&
1007 		    eli_backup_create(r, prov, backfile) == 0) {
1008 			printf("\nMetadata backup for provider %s can be found "
1009 			    "in %s\n", prov, backfile);
1010 			printf("and can be restored with the following "
1011 			    "command:\n");
1012 			printf("\n\t# geli restore %s %s\n\n", backfile, prov);
1013 		}
1014 
1015 out:
1016 		/*
1017 		 * Print error for this request, and set parent request error
1018 		 * message.
1019 		 */
1020 		if (r->error != NULL && r->error[0] != '\0') {
1021 			warnx("%s", r->error);
1022 			gctl_error(req, "There was an error with at least one "
1023 			    "provider.");
1024 		}
1025 
1026 		gctl_free(r);
1027 
1028 		/*
1029 		 * Erase sensitive and provider specific data from memory.
1030 		 */
1031 		explicit_bzero(key, sizeof(key));
1032 		explicit_bzero(sector, sizeof(sector));
1033 		explicit_bzero(&md.md_provsize, sizeof(md.md_provsize));
1034 		explicit_bzero(&md.md_sectorsize, sizeof(md.md_sectorsize));
1035 		explicit_bzero(&md.md_salt, sizeof(md.md_salt));
1036 		explicit_bzero(&md.md_mkeys, sizeof(md.md_mkeys));
1037 	}
1038 
1039 	/* Clear the cached metadata, including keys. */
1040 	explicit_bzero(&md, sizeof(md));
1041 	explicit_bzero(&ctxtemplate, sizeof(ctxtemplate));
1042 }
1043 
1044 static void
1045 eli_attach(struct gctl_req *req)
1046 {
1047 	struct g_eli_metadata md;
1048 	struct gctl_req *r;
1049 	const char *prov;
1050 	off_t mediasize;
1051 	int i, nargs, nparams, param;
1052 	const int one = 1;
1053 	struct hmac_ctx ctxtemplate;
1054 
1055 	nargs = gctl_get_int(req, "nargs");
1056 	if (nargs <= 0) {
1057 		gctl_error(req, "Too few arguments.");
1058 		return;
1059 	}
1060 
1061 	unsigned char key[G_ELI_USERKEYLEN];
1062 
1063 	/*
1064 	 * Determine number of parameters in the parent geom request before the
1065 	 * nargs parameter and list of providers.
1066 	 */
1067 	nparams = req->narg - nargs - 1;
1068 
1069 	/* Generate HMAC context template. */
1070 	if (!eli_init_key_hmac_ctx(req, &ctxtemplate, false))
1071 		return;
1072 
1073 	/* Create new child request for each provider and issue to kernel */
1074 	for (i = 0; i < nargs; i++) {
1075 		r = gctl_get_handle();
1076 
1077 		/* Copy each parameter from the parent request to the child */
1078 		for (param = 0; param < nparams; param++) {
1079 			gctl_ro_param(r, req->arg[param].name,
1080 			    req->arg[param].len, req->arg[param].value);
1081 		}
1082 
1083 		/* Add a single provider to the parameter list of the child */
1084 		gctl_ro_param(r, "nargs", sizeof(one), &one);
1085 		prov = gctl_get_ascii(req, "arg%d", i);
1086 		gctl_ro_param(r, "arg0", -1, prov);
1087 
1088 		if (eli_metadata_read(r, prov, &md) == -1) {
1089 			/*
1090 			 * Error reading metadata - details added to geom
1091 			 * request by eli_metadata_read().
1092 			 */
1093 			goto out;
1094 		}
1095 
1096 		mediasize = g_get_mediasize(prov);
1097 		if (md.md_provsize != (uint64_t)mediasize) {
1098 			gctl_error(r, "Provider size mismatch.");
1099 			goto out;
1100 		}
1101 
1102 		if (eli_genkey(r, &ctxtemplate, &md, key, false) == NULL) {
1103 			/*
1104 			 * Error generating key - details added to geom request
1105 			 * by eli_genkey().
1106 			 */
1107 			goto out;
1108 		}
1109 
1110 		gctl_ro_param(r, "key", sizeof(key), key);
1111 
1112 		if (gctl_issue(r) == NULL) {
1113 			if (verbose)
1114 				printf("Attached to %s.\n", prov);
1115 		}
1116 
1117 out:
1118 		/*
1119 		 * Print error for this request, and set parent request error
1120 		 * message.
1121 		 */
1122 		if (r->error != NULL && r->error[0] != '\0') {
1123 			warnx("%s", r->error);
1124 			gctl_error(req, "There was an error with at least one "
1125 			    "provider.");
1126 		}
1127 
1128 		gctl_free(r);
1129 
1130 		/* Clear sensitive data from memory. */
1131 		explicit_bzero(key, sizeof(key));
1132 	}
1133 
1134 	/* Clear sensitive data from memory. */
1135 	explicit_bzero(cached_passphrase, sizeof(cached_passphrase));
1136 	explicit_bzero(&ctxtemplate, sizeof(ctxtemplate));
1137 }
1138 
1139 static void
1140 eli_configure_detached(struct gctl_req *req, const char *prov, int boot,
1141     int geliboot, int displaypass, int trim, int autoresize)
1142 {
1143 	struct g_eli_metadata md;
1144 	bool changed = 0;
1145 
1146 	if (eli_metadata_read(req, prov, &md) == -1)
1147 		return;
1148 
1149 	if (boot == 1 && (md.md_flags & G_ELI_FLAG_BOOT)) {
1150 		if (verbose)
1151 			printf("BOOT flag already configured for %s.\n", prov);
1152 	} else if (boot == 0 && !(md.md_flags & G_ELI_FLAG_BOOT)) {
1153 		if (verbose)
1154 			printf("BOOT flag not configured for %s.\n", prov);
1155 	} else if (boot >= 0) {
1156 		if (boot)
1157 			md.md_flags |= G_ELI_FLAG_BOOT;
1158 		else
1159 			md.md_flags &= ~G_ELI_FLAG_BOOT;
1160 		changed = 1;
1161 	}
1162 
1163 	if (geliboot == 1 && (md.md_flags & G_ELI_FLAG_GELIBOOT)) {
1164 		if (verbose)
1165 			printf("GELIBOOT flag already configured for %s.\n", prov);
1166 	} else if (geliboot == 0 && !(md.md_flags & G_ELI_FLAG_GELIBOOT)) {
1167 		if (verbose)
1168 			printf("GELIBOOT flag not configured for %s.\n", prov);
1169 	} else if (geliboot >= 0) {
1170 		if (geliboot)
1171 			md.md_flags |= G_ELI_FLAG_GELIBOOT;
1172 		else
1173 			md.md_flags &= ~G_ELI_FLAG_GELIBOOT;
1174 		changed = 1;
1175 	}
1176 
1177 	if (displaypass == 1 && (md.md_flags & G_ELI_FLAG_GELIDISPLAYPASS)) {
1178 		if (verbose)
1179 			printf("GELIDISPLAYPASS flag already configured for %s.\n", prov);
1180 	} else if (displaypass == 0 &&
1181 	    !(md.md_flags & G_ELI_FLAG_GELIDISPLAYPASS)) {
1182 		if (verbose)
1183 			printf("GELIDISPLAYPASS flag not configured for %s.\n", prov);
1184 	} else if (displaypass >= 0) {
1185 		if (displaypass)
1186 			md.md_flags |= G_ELI_FLAG_GELIDISPLAYPASS;
1187 		else
1188 			md.md_flags &= ~G_ELI_FLAG_GELIDISPLAYPASS;
1189 		changed = 1;
1190 	}
1191 
1192 	if (trim == 0 && (md.md_flags & G_ELI_FLAG_NODELETE)) {
1193 		if (verbose)
1194 			printf("TRIM disable flag already configured for %s.\n", prov);
1195 	} else if (trim == 1 && !(md.md_flags & G_ELI_FLAG_NODELETE)) {
1196 		if (verbose)
1197 			printf("TRIM disable flag not configured for %s.\n", prov);
1198 	} else if (trim >= 0) {
1199 		if (trim)
1200 			md.md_flags &= ~G_ELI_FLAG_NODELETE;
1201 		else
1202 			md.md_flags |= G_ELI_FLAG_NODELETE;
1203 		changed = 1;
1204 	}
1205 
1206 	if (autoresize == 1 && (md.md_flags & G_ELI_FLAG_AUTORESIZE)) {
1207 		if (verbose)
1208 			printf("AUTORESIZE flag already configured for %s.\n", prov);
1209 	} else if (autoresize == 0 && !(md.md_flags & G_ELI_FLAG_AUTORESIZE)) {
1210 		if (verbose)
1211 			printf("AUTORESIZE flag not configured for %s.\n", prov);
1212 	} else if (autoresize >= 0) {
1213 		if (autoresize)
1214 			md.md_flags |= G_ELI_FLAG_AUTORESIZE;
1215 		else
1216 			md.md_flags &= ~G_ELI_FLAG_AUTORESIZE;
1217 		changed = 1;
1218 	}
1219 
1220 	if (changed)
1221 		eli_metadata_store(req, prov, &md);
1222 	explicit_bzero(&md, sizeof(md));
1223 }
1224 
1225 static void
1226 eli_configure(struct gctl_req *req)
1227 {
1228 	const char *prov;
1229 	bool boot, noboot, geliboot, nogeliboot, displaypass, nodisplaypass;
1230 	bool autoresize, noautoresize, trim, notrim;
1231 	int doboot, dogeliboot, dodisplaypass, dotrim, doautoresize;
1232 	int i, nargs;
1233 
1234 	nargs = gctl_get_int(req, "nargs");
1235 	if (nargs == 0) {
1236 		gctl_error(req, "Too few arguments.");
1237 		return;
1238 	}
1239 
1240 	boot = gctl_get_int(req, "boot");
1241 	noboot = gctl_get_int(req, "noboot");
1242 	geliboot = gctl_get_int(req, "geliboot");
1243 	nogeliboot = gctl_get_int(req, "nogeliboot");
1244 	displaypass = gctl_get_int(req, "displaypass");
1245 	nodisplaypass = gctl_get_int(req, "nodisplaypass");
1246 	trim = gctl_get_int(req, "trim");
1247 	notrim = gctl_get_int(req, "notrim");
1248 	autoresize = gctl_get_int(req, "autoresize");
1249 	noautoresize = gctl_get_int(req, "noautoresize");
1250 
1251 	doboot = -1;
1252 	if (boot && noboot) {
1253 		gctl_error(req, "Options -b and -B are mutually exclusive.");
1254 		return;
1255 	}
1256 	if (boot)
1257 		doboot = 1;
1258 	else if (noboot)
1259 		doboot = 0;
1260 
1261 	dogeliboot = -1;
1262 	if (geliboot && nogeliboot) {
1263 		gctl_error(req, "Options -g and -G are mutually exclusive.");
1264 		return;
1265 	}
1266 	if (geliboot)
1267 		dogeliboot = 1;
1268 	else if (nogeliboot)
1269 		dogeliboot = 0;
1270 
1271 	dodisplaypass = -1;
1272 	if (displaypass && nodisplaypass) {
1273 		gctl_error(req, "Options -d and -D are mutually exclusive.");
1274 		return;
1275 	}
1276 	if (displaypass)
1277 		dodisplaypass = 1;
1278 	else if (nodisplaypass)
1279 		dodisplaypass = 0;
1280 
1281 	dotrim = -1;
1282 	if (trim && notrim) {
1283 		gctl_error(req, "Options -t and -T are mutually exclusive.");
1284 		return;
1285 	}
1286 	if (trim)
1287 		dotrim = 1;
1288 	else if (notrim)
1289 		dotrim = 0;
1290 
1291 	doautoresize = -1;
1292 	if (autoresize && noautoresize) {
1293 		gctl_error(req, "Options -r and -R are mutually exclusive.");
1294 		return;
1295 	}
1296 	if (autoresize)
1297 		doautoresize = 1;
1298 	else if (noautoresize)
1299 		doautoresize = 0;
1300 
1301 	if (doboot == -1 && dogeliboot == -1 && dodisplaypass == -1 &&
1302 	    dotrim == -1 && doautoresize == -1) {
1303 		gctl_error(req, "No option given.");
1304 		return;
1305 	}
1306 
1307 	/* First attached providers. */
1308 	gctl_issue(req);
1309 	/* Now the rest. */
1310 	for (i = 0; i < nargs; i++) {
1311 		prov = gctl_get_ascii(req, "arg%d", i);
1312 		if (!eli_is_attached(prov)) {
1313 			eli_configure_detached(req, prov, doboot, dogeliboot,
1314 			    dodisplaypass, dotrim, doautoresize);
1315 		}
1316 	}
1317 }
1318 
1319 static void
1320 eli_setkey_attached(struct gctl_req *req, struct g_eli_metadata *md)
1321 {
1322 	unsigned char key[G_ELI_USERKEYLEN];
1323 	intmax_t val, old = 0;
1324 	int error;
1325 
1326 	val = gctl_get_intmax(req, "iterations");
1327 	/* Check if iterations number should be changed. */
1328 	if (val != -1)
1329 		md->md_iterations = val;
1330 	else
1331 		old = md->md_iterations;
1332 
1333 	/* Generate key for Master Key encryption. */
1334 	if (eli_genkey_single(req, md, key, true) == NULL) {
1335 		explicit_bzero(key, sizeof(key));
1336 		return;
1337 	}
1338 	/*
1339 	 * If number of iterations has changed, but wasn't given as a
1340 	 * command-line argument, update the request.
1341 	 */
1342 	if (val == -1 && md->md_iterations != old) {
1343 		error = gctl_change_param(req, "iterations", sizeof(intmax_t),
1344 		    &md->md_iterations);
1345 		assert(error == 0);
1346 	}
1347 
1348 	gctl_ro_param(req, "key", sizeof(key), key);
1349 	gctl_issue(req);
1350 	explicit_bzero(key, sizeof(key));
1351 }
1352 
1353 static void
1354 eli_setkey_detached(struct gctl_req *req, const char *prov,
1355  struct g_eli_metadata *md)
1356 {
1357 	unsigned char key[G_ELI_USERKEYLEN], mkey[G_ELI_DATAIVKEYLEN];
1358 	unsigned char *mkeydst;
1359 	unsigned int nkey;
1360 	intmax_t val;
1361 	int error;
1362 
1363 	if (md->md_keys == 0) {
1364 		gctl_error(req, "No valid keys on %s.", prov);
1365 		return;
1366 	}
1367 
1368 	/* Generate key for Master Key decryption. */
1369 	if (eli_genkey_single(req, md, key, false) == NULL) {
1370 		explicit_bzero(key, sizeof(key));
1371 		return;
1372 	}
1373 
1374 	/* Decrypt Master Key. */
1375 	error = g_eli_mkey_decrypt_any(md, key, mkey, &nkey);
1376 	explicit_bzero(key, sizeof(key));
1377 	if (error != 0) {
1378 		explicit_bzero(md, sizeof(*md));
1379 		if (error == -1)
1380 			gctl_error(req, "Wrong key for %s.", prov);
1381 		else /* if (error > 0) */ {
1382 			gctl_error(req, "Cannot decrypt Master Key: %s.",
1383 			    strerror(error));
1384 		}
1385 		return;
1386 	}
1387 	if (verbose)
1388 		printf("Decrypted Master Key %u.\n", nkey);
1389 
1390 	val = gctl_get_intmax(req, "keyno");
1391 	if (val != -1)
1392 		nkey = val;
1393 #if 0
1394 	else
1395 		; /* Use the key number which was found during decryption. */
1396 #endif
1397 	if (nkey >= G_ELI_MAXMKEYS) {
1398 		gctl_error(req, "Invalid '%s' argument.", "keyno");
1399 		return;
1400 	}
1401 
1402 	val = gctl_get_intmax(req, "iterations");
1403 	/* Check if iterations number should and can be changed. */
1404 	if (val != -1 && md->md_iterations == -1) {
1405 		md->md_iterations = val;
1406 	} else if (val != -1 && val != md->md_iterations) {
1407 		if (bitcount32(md->md_keys) != 1) {
1408 			gctl_error(req, "To be able to use '-i' option, only "
1409 			    "one key can be defined.");
1410 			return;
1411 		}
1412 		if (md->md_keys != (1 << nkey)) {
1413 			gctl_error(req, "Only already defined key can be "
1414 			    "changed when '-i' option is used.");
1415 			return;
1416 		}
1417 		md->md_iterations = val;
1418 	}
1419 
1420 	mkeydst = md->md_mkeys + nkey * G_ELI_MKEYLEN;
1421 	md->md_keys |= (1 << nkey);
1422 
1423 	bcopy(mkey, mkeydst, sizeof(mkey));
1424 	explicit_bzero(mkey, sizeof(mkey));
1425 
1426 	/* Generate key for Master Key encryption. */
1427 	if (eli_genkey_single(req, md, key, true) == NULL) {
1428 		explicit_bzero(key, sizeof(key));
1429 		explicit_bzero(md, sizeof(*md));
1430 		return;
1431 	}
1432 
1433 	/* Encrypt the Master-Key with the new key. */
1434 	error = g_eli_mkey_encrypt(md->md_ealgo, key, md->md_keylen, mkeydst);
1435 	explicit_bzero(key, sizeof(key));
1436 	if (error != 0) {
1437 		explicit_bzero(md, sizeof(*md));
1438 		gctl_error(req, "Cannot encrypt Master Key: %s.",
1439 		    strerror(error));
1440 		return;
1441 	}
1442 
1443 	/* Store metadata with fresh key. */
1444 	eli_metadata_store(req, prov, md);
1445 	explicit_bzero(md, sizeof(*md));
1446 }
1447 
1448 static void
1449 eli_setkey(struct gctl_req *req)
1450 {
1451 	struct g_eli_metadata md;
1452 	const char *prov;
1453 	int nargs;
1454 
1455 	nargs = gctl_get_int(req, "nargs");
1456 	if (nargs != 1) {
1457 		gctl_error(req, "Invalid number of arguments.");
1458 		return;
1459 	}
1460 	prov = gctl_get_ascii(req, "arg0");
1461 
1462 	if (eli_metadata_read(req, prov, &md) == -1)
1463 		return;
1464 
1465 	if (eli_is_attached(prov))
1466 		eli_setkey_attached(req, &md);
1467 	else
1468 		eli_setkey_detached(req, prov, &md);
1469 
1470 	if (req->error == NULL || req->error[0] == '\0') {
1471 		printf("Note, that the master key encrypted with old keys "
1472 		    "and/or passphrase may still exists in a metadata backup "
1473 		    "file.\n");
1474 	}
1475 }
1476 
1477 static void
1478 eli_delkey_attached(struct gctl_req *req, const char *prov __unused)
1479 {
1480 
1481 	gctl_issue(req);
1482 }
1483 
1484 static void
1485 eli_delkey_detached(struct gctl_req *req, const char *prov)
1486 {
1487 	struct g_eli_metadata md;
1488 	unsigned char *mkeydst;
1489 	unsigned int nkey;
1490 	intmax_t val;
1491 	bool all, force;
1492 
1493 	if (eli_metadata_read(req, prov, &md) == -1)
1494 		return;
1495 
1496 	all = gctl_get_int(req, "all");
1497 	if (all)
1498 		arc4random_buf(md.md_mkeys, sizeof(md.md_mkeys));
1499 	else {
1500 		force = gctl_get_int(req, "force");
1501 		val = gctl_get_intmax(req, "keyno");
1502 		if (val == -1) {
1503 			gctl_error(req, "Key number has to be specified.");
1504 			return;
1505 		}
1506 		nkey = val;
1507 		if (nkey >= G_ELI_MAXMKEYS) {
1508 			gctl_error(req, "Invalid '%s' argument.", "keyno");
1509 			return;
1510 		}
1511 		if (!(md.md_keys & (1 << nkey)) && !force) {
1512 			gctl_error(req, "Master Key %u is not set.", nkey);
1513 			return;
1514 		}
1515 		md.md_keys &= ~(1 << nkey);
1516 		if (md.md_keys == 0 && !force) {
1517 			gctl_error(req, "This is the last Master Key. Use '-f' "
1518 			    "option if you really want to remove it.");
1519 			return;
1520 		}
1521 		mkeydst = md.md_mkeys + nkey * G_ELI_MKEYLEN;
1522 		arc4random_buf(mkeydst, G_ELI_MKEYLEN);
1523 	}
1524 
1525 	eli_metadata_store(req, prov, &md);
1526 	explicit_bzero(&md, sizeof(md));
1527 }
1528 
1529 static void
1530 eli_delkey(struct gctl_req *req)
1531 {
1532 	const char *prov;
1533 	int nargs;
1534 
1535 	nargs = gctl_get_int(req, "nargs");
1536 	if (nargs != 1) {
1537 		gctl_error(req, "Invalid number of arguments.");
1538 		return;
1539 	}
1540 	prov = gctl_get_ascii(req, "arg0");
1541 
1542 	if (eli_is_attached(prov))
1543 		eli_delkey_attached(req, prov);
1544 	else
1545 		eli_delkey_detached(req, prov);
1546 }
1547 
1548 static void
1549 eli_resume(struct gctl_req *req)
1550 {
1551 	struct g_eli_metadata md;
1552 	unsigned char key[G_ELI_USERKEYLEN];
1553 	const char *prov;
1554 	off_t mediasize;
1555 	int nargs;
1556 
1557 	nargs = gctl_get_int(req, "nargs");
1558 	if (nargs != 1) {
1559 		gctl_error(req, "Invalid number of arguments.");
1560 		return;
1561 	}
1562 	prov = gctl_get_ascii(req, "arg0");
1563 
1564 	if (eli_metadata_read(req, prov, &md) == -1)
1565 		return;
1566 
1567 	mediasize = g_get_mediasize(prov);
1568 	if (md.md_provsize != (uint64_t)mediasize) {
1569 		gctl_error(req, "Provider size mismatch.");
1570 		return;
1571 	}
1572 
1573 	if (eli_genkey_single(req, &md, key, false) == NULL) {
1574 		explicit_bzero(key, sizeof(key));
1575 		return;
1576 	}
1577 
1578 	gctl_ro_param(req, "key", sizeof(key), key);
1579 	if (gctl_issue(req) == NULL) {
1580 		if (verbose)
1581 			printf("Resumed %s.\n", prov);
1582 	}
1583 	explicit_bzero(key, sizeof(key));
1584 }
1585 
1586 static int
1587 eli_trash_metadata(struct gctl_req *req, const char *prov, int fd, off_t offset)
1588 {
1589 	unsigned int overwrites;
1590 	unsigned char *sector;
1591 	ssize_t size;
1592 	int error;
1593 
1594 	size = sizeof(overwrites);
1595 	if (sysctlbyname("kern.geom.eli.overwrites", &overwrites, &size,
1596 	    NULL, 0) == -1 || overwrites == 0) {
1597 		overwrites = G_ELI_OVERWRITES;
1598 	}
1599 
1600 	size = g_sectorsize(fd);
1601 	if (size <= 0) {
1602 		gctl_error(req, "Cannot obtain provider sector size %s: %s.",
1603 		    prov, strerror(errno));
1604 		return (-1);
1605 	}
1606 	sector = malloc(size);
1607 	if (sector == NULL) {
1608 		gctl_error(req, "Cannot allocate %zd bytes of memory.", size);
1609 		return (-1);
1610 	}
1611 
1612 	error = 0;
1613 	do {
1614 		arc4random_buf(sector, size);
1615 		if (pwrite(fd, sector, size, offset) != size) {
1616 			if (error == 0)
1617 				error = errno;
1618 		}
1619 		(void)g_flush(fd);
1620 	} while (--overwrites > 0);
1621 	free(sector);
1622 	if (error != 0) {
1623 		gctl_error(req, "Cannot trash metadata on provider %s: %s.",
1624 		    prov, strerror(error));
1625 		return (-1);
1626 	}
1627 	return (0);
1628 }
1629 
1630 static void
1631 eli_kill_detached(struct gctl_req *req, const char *prov)
1632 {
1633 	off_t offset;
1634 	int fd;
1635 
1636 	/*
1637 	 * NOTE: Maybe we should verify if this is geli provider first,
1638 	 *       but 'kill' command is quite critical so better don't waste
1639 	 *       the time.
1640 	 */
1641 #if 0
1642 	error = g_metadata_read(prov, (unsigned char *)&md, sizeof(md),
1643 	    G_ELI_MAGIC);
1644 	if (error != 0) {
1645 		gctl_error(req, "Cannot read metadata from %s: %s.", prov,
1646 		    strerror(error));
1647 		return;
1648 	}
1649 #endif
1650 
1651 	fd = g_open(prov, 1);
1652 	if (fd == -1) {
1653 		gctl_error(req, "Cannot open provider %s: %s.", prov,
1654 		    strerror(errno));
1655 		return;
1656 	}
1657 	offset = g_mediasize(fd) - g_sectorsize(fd);
1658 	if (offset <= 0) {
1659 		gctl_error(req,
1660 		    "Cannot obtain media size or sector size for provider %s: %s.",
1661 		    prov, strerror(errno));
1662 		(void)g_close(fd);
1663 		return;
1664 	}
1665 	(void)eli_trash_metadata(req, prov, fd, offset);
1666 	(void)g_close(fd);
1667 }
1668 
1669 static void
1670 eli_kill(struct gctl_req *req)
1671 {
1672 	const char *prov;
1673 	int i, nargs, all;
1674 
1675 	nargs = gctl_get_int(req, "nargs");
1676 	all = gctl_get_int(req, "all");
1677 	if (!all && nargs == 0) {
1678 		gctl_error(req, "Too few arguments.");
1679 		return;
1680 	}
1681 	/*
1682 	 * How '-a' option combine with a list of providers:
1683 	 * Delete Master Keys from all attached providers:
1684 	 * geli kill -a
1685 	 * Delete Master Keys from all attached providers and from
1686 	 * detached da0 and da1:
1687 	 * geli kill -a da0 da1
1688 	 * Delete Master Keys from (attached or detached) da0 and da1:
1689 	 * geli kill da0 da1
1690 	 */
1691 
1692 	/* First detached providers. */
1693 	for (i = 0; i < nargs; i++) {
1694 		prov = gctl_get_ascii(req, "arg%d", i);
1695 		if (!eli_is_attached(prov))
1696 			eli_kill_detached(req, prov);
1697 	}
1698 	/* Now attached providers. */
1699 	gctl_issue(req);
1700 }
1701 
1702 static int
1703 eli_backup_create(struct gctl_req *req, const char *prov, const char *file)
1704 {
1705 	unsigned char *sector;
1706 	ssize_t secsize;
1707 	int error, filefd, ret;
1708 
1709 	ret = -1;
1710 	filefd = -1;
1711 	sector = NULL;
1712 	secsize = 0;
1713 
1714 	secsize = g_get_sectorsize(prov);
1715 	if (secsize == 0) {
1716 		gctl_error(req, "Cannot get informations about %s: %s.", prov,
1717 		    strerror(errno));
1718 		goto out;
1719 	}
1720 	sector = malloc(secsize);
1721 	if (sector == NULL) {
1722 		gctl_error(req, "Cannot allocate memory.");
1723 		goto out;
1724 	}
1725 	/* Read metadata from the provider. */
1726 	error = g_metadata_read(prov, sector, secsize, G_ELI_MAGIC);
1727 	if (error != 0) {
1728 		gctl_error(req, "Unable to read metadata from %s: %s.", prov,
1729 		    strerror(error));
1730 		goto out;
1731 	}
1732 
1733 	filefd = open(file, O_WRONLY | O_TRUNC | O_CREAT, 0600);
1734 	if (filefd == -1) {
1735 		gctl_error(req, "Unable to open %s: %s.", file,
1736 		    strerror(errno));
1737 		goto out;
1738 	}
1739 	/* Write metadata to the destination file. */
1740 	if (write(filefd, sector, secsize) != secsize) {
1741 		gctl_error(req, "Unable to write to %s: %s.", file,
1742 		    strerror(errno));
1743 		(void)close(filefd);
1744 		(void)unlink(file);
1745 		goto out;
1746 	}
1747 	(void)fsync(filefd);
1748 	(void)close(filefd);
1749 	/* Success. */
1750 	ret = 0;
1751 out:
1752 	if (sector != NULL) {
1753 		explicit_bzero(sector, secsize);
1754 		free(sector);
1755 	}
1756 	return (ret);
1757 }
1758 
1759 static void
1760 eli_backup(struct gctl_req *req)
1761 {
1762 	const char *file, *prov;
1763 	int nargs;
1764 
1765 	nargs = gctl_get_int(req, "nargs");
1766 	if (nargs != 2) {
1767 		gctl_error(req, "Invalid number of arguments.");
1768 		return;
1769 	}
1770 	prov = gctl_get_ascii(req, "arg0");
1771 	file = gctl_get_ascii(req, "arg1");
1772 
1773 	eli_backup_create(req, prov, file);
1774 }
1775 
1776 static void
1777 eli_restore(struct gctl_req *req)
1778 {
1779 	struct g_eli_metadata md;
1780 	const char *file, *prov;
1781 	off_t mediasize;
1782 	int nargs;
1783 
1784 	nargs = gctl_get_int(req, "nargs");
1785 	if (nargs != 2) {
1786 		gctl_error(req, "Invalid number of arguments.");
1787 		return;
1788 	}
1789 	file = gctl_get_ascii(req, "arg0");
1790 	prov = gctl_get_ascii(req, "arg1");
1791 
1792 	/* Read metadata from the backup file. */
1793 	if (eli_metadata_read(req, file, &md) == -1)
1794 		return;
1795 	/* Obtain provider's mediasize. */
1796 	mediasize = g_get_mediasize(prov);
1797 	if (mediasize == 0) {
1798 		gctl_error(req, "Cannot get informations about %s: %s.", prov,
1799 		    strerror(errno));
1800 		return;
1801 	}
1802 	/* Check if the provider size has changed since we did the backup. */
1803 	if (md.md_provsize != (uint64_t)mediasize) {
1804 		if (gctl_get_int(req, "force")) {
1805 			md.md_provsize = mediasize;
1806 		} else {
1807 			gctl_error(req, "Provider size mismatch: "
1808 			    "wrong backup file?");
1809 			return;
1810 		}
1811 	}
1812 	/* Write metadata to the provider. */
1813 	(void)eli_metadata_store(req, prov, &md);
1814 }
1815 
1816 static void
1817 eli_resize(struct gctl_req *req)
1818 {
1819 	struct g_eli_metadata md;
1820 	const char *prov;
1821 	unsigned char *sector;
1822 	ssize_t secsize;
1823 	off_t mediasize, oldsize;
1824 	int error, nargs, provfd;
1825 
1826 	nargs = gctl_get_int(req, "nargs");
1827 	if (nargs != 1) {
1828 		gctl_error(req, "Invalid number of arguments.");
1829 		return;
1830 	}
1831 	prov = gctl_get_ascii(req, "arg0");
1832 
1833 	provfd = -1;
1834 	sector = NULL;
1835 	secsize = 0;
1836 
1837 	provfd = g_open(prov, 1);
1838 	if (provfd == -1) {
1839 		gctl_error(req, "Cannot open %s: %s.", prov, strerror(errno));
1840 		goto out;
1841 	}
1842 
1843 	mediasize = g_mediasize(provfd);
1844 	secsize = g_sectorsize(provfd);
1845 	if (mediasize == -1 || secsize == -1) {
1846 		gctl_error(req, "Cannot get information about %s: %s.", prov,
1847 		    strerror(errno));
1848 		goto out;
1849 	}
1850 
1851 	sector = malloc(secsize);
1852 	if (sector == NULL) {
1853 		gctl_error(req, "Cannot allocate memory.");
1854 		goto out;
1855 	}
1856 
1857 	oldsize = gctl_get_intmax(req, "oldsize");
1858 	if (oldsize < 0 || oldsize > mediasize) {
1859 		gctl_error(req, "Invalid oldsize: Out of range.");
1860 		goto out;
1861 	}
1862 
1863 	/* Read metadata from the 'oldsize' offset. */
1864 	if (pread(provfd, sector, secsize, oldsize - secsize) != secsize) {
1865 		gctl_error(req, "Cannot read old metadata: %s.",
1866 		    strerror(errno));
1867 		goto out;
1868 	}
1869 
1870 	/* Check if this sector contains geli metadata. */
1871 	error = eli_metadata_decode(sector, &md);
1872 	switch (error) {
1873 	case 0:
1874 		break;
1875 	case EOPNOTSUPP:
1876 		gctl_error(req,
1877 		    "Provider's %s metadata version %u is too new.\n"
1878 		    "geli: The highest supported version is %u.",
1879 		    prov, (unsigned int)md.md_version, G_ELI_VERSION);
1880 		goto out;
1881 	case EINVAL:
1882 		gctl_error(req, "Inconsistent provider's %s metadata.", prov);
1883 		goto out;
1884 	default:
1885 		gctl_error(req,
1886 		    "Unexpected error while decoding provider's %s metadata: %s.",
1887 		    prov, strerror(error));
1888 		goto out;
1889 	}
1890 
1891 	/*
1892 	 * If the old metadata doesn't have a correct provider size, refuse
1893 	 * to resize.
1894 	 */
1895 	if (md.md_provsize != (uint64_t)oldsize) {
1896 		gctl_error(req, "Provider size mismatch at oldsize.");
1897 		goto out;
1898 	}
1899 
1900 	/* The metadata is valid and nothing has changed.  Just exit. */
1901 	if (oldsize == mediasize)
1902 		goto out;
1903 
1904 	/*
1905 	 * Update the old metadata with the current provider size and write
1906 	 * it back to the correct place on the provider.
1907 	 */
1908 	md.md_provsize = mediasize;
1909 	/* Write metadata to the provider. */
1910 	(void)eli_metadata_store(req, prov, &md);
1911 	/* Now trash the old metadata. */
1912 	(void)eli_trash_metadata(req, prov, provfd, oldsize - secsize);
1913 out:
1914 	if (provfd != -1)
1915 		(void)g_close(provfd);
1916 	if (sector != NULL) {
1917 		explicit_bzero(sector, secsize);
1918 		free(sector);
1919 	}
1920 }
1921 
1922 static void
1923 eli_version(struct gctl_req *req)
1924 {
1925 	struct g_eli_metadata md;
1926 	const char *name;
1927 	unsigned int eli_version;
1928 	int error, i, nargs;
1929 
1930 	nargs = gctl_get_int(req, "nargs");
1931 
1932 	if (nargs == 0) {
1933 		unsigned int kernver;
1934 		ssize_t size;
1935 
1936 		size = sizeof(kernver);
1937 		if (sysctlbyname("kern.geom.eli.version", &kernver, &size,
1938 		    NULL, 0) == -1) {
1939 			warn("Unable to obtain GELI kernel version");
1940 		} else {
1941 			printf("kernel: %u\n", kernver);
1942 		}
1943 		printf("userland: %u\n", G_ELI_VERSION);
1944 		return;
1945 	}
1946 
1947 	for (i = 0; i < nargs; i++) {
1948 		name = gctl_get_ascii(req, "arg%d", i);
1949 		error = g_metadata_read(name, (unsigned char *)&md,
1950 		    sizeof(md), G_ELI_MAGIC);
1951 		if (error != 0) {
1952 			warn("%s: Unable to read metadata: %s.", name,
1953 			    strerror(error));
1954 			gctl_error(req, "Not fully done.");
1955 			continue;
1956 		}
1957 		eli_version = le32dec(&md.md_version);
1958 		printf("%s: %u\n", name, eli_version);
1959 	}
1960 }
1961 
1962 static void
1963 eli_clear(struct gctl_req *req)
1964 {
1965 	const char *name;
1966 	int error, i, nargs;
1967 
1968 	nargs = gctl_get_int(req, "nargs");
1969 	if (nargs < 1) {
1970 		gctl_error(req, "Too few arguments.");
1971 		return;
1972 	}
1973 
1974 	for (i = 0; i < nargs; i++) {
1975 		name = gctl_get_ascii(req, "arg%d", i);
1976 		error = g_metadata_clear(name, G_ELI_MAGIC);
1977 		if (error != 0) {
1978 			fprintf(stderr, "Cannot clear metadata on %s: %s.\n",
1979 			    name, strerror(error));
1980 			gctl_error(req, "Not fully done.");
1981 			continue;
1982 		}
1983 		if (verbose)
1984 			printf("Metadata cleared on %s.\n", name);
1985 	}
1986 }
1987 
1988 static void
1989 eli_dump(struct gctl_req *req)
1990 {
1991 	struct g_eli_metadata md;
1992 	const char *name;
1993 	int i, nargs;
1994 
1995 	nargs = gctl_get_int(req, "nargs");
1996 	if (nargs < 1) {
1997 		gctl_error(req, "Too few arguments.");
1998 		return;
1999 	}
2000 
2001 	for (i = 0; i < nargs; i++) {
2002 		name = gctl_get_ascii(req, "arg%d", i);
2003 		if (eli_metadata_read(NULL, name, &md) == -1) {
2004 			gctl_error(req, "Not fully done.");
2005 			continue;
2006 		}
2007 		printf("Metadata on %s:\n", name);
2008 		eli_metadata_dump(&md);
2009 		printf("\n");
2010 	}
2011 }
2012