cryptsetup.c 18.2 KB
Newer Older
1 2 3 4 5 6 7
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <inttypes.h>
#include <errno.h>
#include <unistd.h>
8
#include <fcntl.h>
9 10 11 12 13 14 15 16 17
#include <assert.h>

#include <libcryptsetup.h>
#include <popt.h>

#include "../config.h"

#include "cryptsetup.h"

18 19
static int opt_verbose = 0;
static int opt_debug = 0;
20
static char *opt_cipher = NULL;
21
static char *opt_hash = NULL;
22 23 24 25 26 27 28 29 30 31 32 33 34 35
static int opt_verify_passphrase = 0;
static char *opt_key_file = NULL;
static unsigned int opt_key_size = 0;
static int opt_key_slot = -1;
static uint64_t opt_size = 0;
static uint64_t opt_offset = 0;
static uint64_t opt_skip = 0;
static int opt_readonly = 0;
static int opt_iteration_time = 1000;
static int opt_batch_mode = 0;
static int opt_version_mode = 0;
static int opt_timeout = 0;
static int opt_tries = 3;
static int opt_align_payload = 0;
36
static int opt_non_exclusive = 0;
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56

static const char **action_argv;
static int action_argc;

static int action_create(int arg);
static int action_remove(int arg);
static int action_resize(int arg);
static int action_status(int arg);
static int action_luksFormat(int arg);
static int action_luksOpen(int arg);
static int action_luksAddKey(int arg);
static int action_luksDelKey(int arg);
static int action_luksKillSlot(int arg);
static int action_luksRemoveKey(int arg);
static int action_isLuks(int arg);
static int action_luksUUID(int arg);
static int action_luksDump(int arg);

static struct action_type {
	const char *type;
57
	int (*handler)(int);
58 59
	int arg;
	int required_action_argc;
60 61 62
	int required_dm_backend;
	int required_memlock;
	int show_status;
63 64 65
	const char *arg_desc;
	const char *desc;
} action_types[] = {
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
	{ "create",	action_create,		0, 2, 1, 1, 1, N_("<name> <device>"),N_("create device") },
	{ "remove",	action_remove,		0, 1, 1, 0, 1, N_("<name>"), N_("remove device") },
	{ "resize",	action_resize,		0, 1, 1, 1, 1, N_("<name>"), N_("resize active device") },
	{ "status",	action_status,		0, 1, 1, 0, 1, N_("<name>"), N_("show device status") },
	{ "luksFormat", action_luksFormat,	0, 1, 1, 1, 1, N_("<device> [<new key file>]"), N_("formats a LUKS device") },
	{ "luksOpen",	action_luksOpen,	0, 2, 1, 1, 1, N_("<device> <name> "), N_("open LUKS device as mapping <name>") },
	{ "luksAddKey",	action_luksAddKey,	0, 1, 1, 1, 1, N_("<device> [<new key file>]"), N_("add key to LUKS device") },
	{ "luksRemoveKey",action_luksRemoveKey,	0, 1, 1, 1, 1, N_("<device> [<key file>]"), N_("removes supplied key or key file from LUKS device") },
	{ "luksKillSlot",  action_luksKillSlot, 0, 2, 1, 1, 1, N_("<device> <key slot>"), N_("wipes key with number <key slot> from LUKS device") },
	{ "luksUUID",	action_luksUUID,	0, 1, 0, 0, 1, N_("<device>"), N_("print UUID of LUKS device") },
	{ "isLuks",	action_isLuks,		0, 1, 0, 0, 0, N_("<device>"), N_("tests <device> for LUKS partition header") },
	{ "luksClose",	action_remove,		0, 1, 1, 0, 1, N_("<name>"), N_("remove LUKS mapping") },
	{ "luksDump",	action_luksDump,	0, 1, 0, 0, 1, N_("<device>"), N_("dump LUKS partition information") },
	{ "luksDelKey", action_luksDelKey,	0, 2, 1, 1, 1, N_("<device> <key slot>"), N_("identical to luksKillSlot - DEPRECATED - see man page") },
	{ "reload",	action_create,		1, 2, 1, 1, 1, N_("<name> <device>"), N_("modify active device - DEPRECATED - see man page") },
	{ NULL, NULL, 0, 0, 0, 0, 0, NULL, NULL }
82 83 84 85 86
};

/* Interface Callbacks */
static int yesDialog(char *msg)
{
87 88 89 90
	char *answer = NULL;
	size_t size = 0;
	int r = 1;

91
	if(isatty(0) && !opt_batch_mode) {
92 93
		log_std("\nWARNING!\n========\n");
		log_std("%s\n\nAre you sure? (Type uppercase yes): ", msg);
94 95 96
		if(getline(&answer, &size, stdin) == -1) {
			perror("getline");
			free(answer);
97
			return 0;
98 99 100
		}
		if(strcmp(answer, "YES\n"))
			r = 0;
101
		free(answer);
102 103
	}

104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
	return r;
}

static void cmdLineLog(int class, char *msg) {
    switch(class) {

    case CRYPT_LOG_NORMAL:
            fputs(msg, stdout);
            break;
    case CRYPT_LOG_ERROR:
            fputs(msg, stderr);
            break;
    default:
            fprintf(stderr, "Internal error on logging class for msg: %s", msg);
            break;
    }
}

static struct interface_callbacks cmd_icb = {
        .yesDialog = yesDialog,
        .log = cmdLineLog,
};

/* End ICBs */

static void show_status(int errcode)
{
	char error[256];

133 134 135
	if(!errcode && opt_verbose) {
		log_std(_("Command successful.\n"));
		return;
136 137 138
	}

	crypt_get_error(error, sizeof(error));
139

140 141 142 143 144 145 146 147
	if (!opt_verbose) {
		char *error_ = strerror_r(errcode, error, sizeof(error));
		if (error_ != error) {
			strncpy(error, error_, sizeof(error));
			error[sizeof error - 1] = '\0';
		}
	}

148
	log_err(_("Command failed"));
149
	if (*error)
150
		log_err(": %s\n", error);
151
	else
152
		log_err(".\n");
153 154 155 156 157 158 159 160 161
	return;
}

static int action_create(int reload)
{
	struct crypt_options options = {
		.name = action_argv[0],
		.device = action_argv[1],
		.cipher = opt_cipher?opt_cipher:DEFAULT_CIPHER,
162
		.hash = opt_hash ?: DEFAULT_HASH,
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
		.key_file = opt_key_file,
		.key_size = ((opt_key_size)?opt_key_size:DEFAULT_KEY_SIZE)/8,
		.key_slot = opt_key_slot,
		.passphrase_fd = 0,	/* stdin */
		.flags = 0,
		.size = opt_size,
		.offset = opt_offset,
		.skip = opt_skip,
		.timeout = opt_timeout,
		.tries = opt_tries,
		.icb = &cmd_icb,
	};
	int r;

        if(reload) 
178
                log_err(_("The reload action is deprecated. Please use \"dmsetup reload\" in case you really need this functionality.\nWARNING: do not use reload to touch LUKS devices. If that is the case, hit Ctrl-C now.\n"));
179 180 181 182 183 184 185 186 187 188 189 190

	if (options.hash && strcmp(options.hash, "plain") == 0)
		options.hash = NULL;
	if (opt_verify_passphrase)
		options.flags |= CRYPT_FLAG_VERIFY;
	if (opt_readonly)
		options.flags |= CRYPT_FLAG_READONLY;

	if (reload)
		r = crypt_update_device(&options);
	else
		r = crypt_create_device(&options);
191

192 193 194 195 196 197 198 199 200 201
	return r;
}

static int action_remove(int arg)
{
	struct crypt_options options = {
		.name = action_argv[0],
		.icb = &cmd_icb,
	};

202
	return crypt_remove_device(&options);
203 204 205 206 207 208 209 210 211 212
}

static int action_resize(int arg)
{
	struct crypt_options options = {
		.name = action_argv[0],
		.size = opt_size,
		.icb = &cmd_icb,
	};

213
	return crypt_resize_device(&options);
214 215 216 217 218 219 220 221 222 223 224
}

static int action_status(int arg)
{
	struct crypt_options options = {
		.name = action_argv[0],
		.icb = &cmd_icb,
	};
	int r;

	r = crypt_query_device(&options);
225 226 227 228
	if (r < 0)
		return r;

	if (r == 0) {
229
		/* inactive */
230
		log_std("%s/%s is inactive.\n", crypt_get_dir(), options.name);
231 232 233
		r = 1;
	} else {
		/* active */
234 235 236 237 238 239
		log_std("%s/%s is active:\n", crypt_get_dir(), options.name);
		log_std("  cipher:  %s\n", options.cipher);
		log_std("  keysize: %d bits\n", options.key_size * 8);
		log_std("  device:  %s\n", options.device);
		log_std("  offset:  %" PRIu64 " sectors\n", options.offset);
		log_std("  size:    %" PRIu64 " sectors\n", options.size);
240
		if (options.skip)
241 242
			log_std("  skipped: %" PRIu64 " sectors\n", options.skip);
		log_std("  mode:    %s\n", (options.flags & CRYPT_FLAG_READONLY)
243 244 245 246 247 248 249 250 251 252
		                           ? "readonly" : "read/write");
		crypt_put_options(&options);
		r = 0;
	}
	return r;
}

static int action_luksFormat(int arg)
{
	struct crypt_options options = {
253
		.key_size = (opt_key_size ?: DEFAULT_LUKS_KEY_SIZE) / 8,
254 255
		.key_slot = opt_key_slot,
		.device = action_argv[0],
256
		.cipher = opt_cipher ?: DEFAULT_LUKS_CIPHER,
257
		.hash = opt_hash ?: DEFAULT_LUKS_HASH,
258 259 260 261 262 263 264 265 266
		.new_key_file = action_argc > 1 ? action_argv[1] : NULL,
		.flags = opt_verify_passphrase ? CRYPT_FLAG_VERIFY : (!opt_batch_mode?CRYPT_FLAG_VERIFY_IF_POSSIBLE :  0),
		.iteration_time = opt_iteration_time,
		.timeout = opt_timeout,
		.align_payload = opt_align_payload,
		.icb = &cmd_icb,
	};
	int r = 0; char *msg = NULL;

267 268 269 270 271 272
	/* Avoid overwriting possibly wrong part of device than user requested by rejecting these options */
	if (opt_offset || opt_skip) {
		fprintf(stderr,"Options --offset and --skip are not supported for luksFormat.\n"); 
		return -EINVAL;
	}

273 274
	if(asprintf(&msg, _("This will overwrite data on %s irrevocably."), options.device) == -1) {
		fputs(_("memory allocation error in action_luksFormat"), stderr);
275
		return -ENOMEM;
276
	}
277 278 279 280 281 282 283
	r = yesDialog(msg);
	free(msg);

	if (!r)
		return -EINVAL;

	return crypt_luksFormat(&options);
284 285 286 287 288 289 290 291
}

static int action_luksOpen(int arg)
{
	struct crypt_options options = {
		.name = action_argv[1],
		.device = action_argv[0],
		.key_file = opt_key_file,
292
		.key_size = opt_key_file ? (opt_key_size / 8) : 0, /* limit bytes read from keyfile */
293
		.timeout = opt_timeout,
294
		.tries = opt_key_file ? 1 : opt_tries, /* verify is usefull only for tty */
295 296 297 298 299
		.icb = &cmd_icb,
	};

	if (opt_readonly)
		options.flags |= CRYPT_FLAG_READONLY;
300 301
	if (opt_non_exclusive)
		options.flags |= CRYPT_FLAG_NON_EXCLUSIVE_ACCESS;
302
	return crypt_luksOpen(&options);
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
}

static int action_luksDelKey(int arg)
{
    fprintf(stderr,"luksDelKey is a deprecated action name.\nPlease use luksKillSlot.\n"); 
    return action_luksKillSlot(arg);
}

static int action_luksKillSlot(int arg)
{
	struct crypt_options options = {
		.device = action_argv[0],
		.key_slot = atoi(action_argv[1]),
		.key_file = opt_key_file,
		.timeout = opt_timeout,
		.flags = !opt_batch_mode?CRYPT_FLAG_VERIFY_ON_DELKEY : 0,
		.icb = &cmd_icb,
	};

322
	return crypt_luksKillSlot(&options);
323 324 325 326 327 328 329 330 331 332 333 334 335
}

static int action_luksRemoveKey(int arg)
{
	struct crypt_options options = {
		.device = action_argv[0],
		.new_key_file = action_argc>1?action_argv[1]:NULL,
		.key_file = opt_key_file,
		.timeout = opt_timeout,
		.flags = !opt_batch_mode?CRYPT_FLAG_VERIFY_ON_DELKEY : 0,
		.icb = &cmd_icb,
	};

336
	return crypt_luksRemoveKey(&options);
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
}

static int action_luksAddKey(int arg)
{
	struct crypt_options options = {
		.device = action_argv[0],
		.new_key_file = action_argc>1?action_argv[1]:NULL,
		.key_file = opt_key_file,
		.key_slot = opt_key_slot,
		.flags = opt_verify_passphrase ? CRYPT_FLAG_VERIFY : (!opt_batch_mode?CRYPT_FLAG_VERIFY_IF_POSSIBLE : 0),
		.iteration_time = opt_iteration_time,
		.timeout = opt_timeout,
		.icb = &cmd_icb,
	};

352
	return crypt_luksAddKey(&options);
353 354 355 356 357 358 359 360
}

static int action_isLuks(int arg)
{
	struct crypt_options options = {
		.device = action_argv[0],
		.icb = &cmd_icb,
	};
361

362 363 364 365 366 367 368 369 370 371
	return crypt_isLuks(&options);
}

static int action_luksUUID(int arg)
{
	struct crypt_options options = {
		.device = action_argv[0],
		.icb = &cmd_icb,
	};

372
	return crypt_luksUUID(&options);
373 374 375 376 377 378 379 380 381
}

static int action_luksDump(int arg)
{
	struct crypt_options options = {
		.device = action_argv[0],
		.icb = &cmd_icb,
	};

382
	return crypt_luksDump(&options);
383 384 385 386 387 388 389
}

static void usage(poptContext popt_context, int exitcode,
                  const char *error, const char *more)
{
	poptPrintUsage(popt_context, stderr, 0);
	if (error)
390
		log_err("%s: %s\n", more, error);
391 392 393 394 395 396 397 398 399
	exit(exitcode);
}

static void help(poptContext popt_context, enum poptCallbackReason reason,
                 struct poptOption *key, const char * arg, void *data)
{
	if (key->shortName == '?') {
		struct action_type *action;

400
		log_std("%s\n",PACKAGE_STRING);
401 402 403

		poptPrintHelp(popt_context, stdout, 0);

404
		log_std(_("\n"
405 406 407
			 "<action> is one of:\n"));

		for(action = action_types; action->type; action++)
408 409 410
			log_std("\t%s %s - %s\n", action->type, _(action->arg_desc), _(action->desc));

		log_std(_("\n"
411 412 413 414 415 416 417 418
			 "<name> is the device to create under %s\n"
			 "<device> is the encrypted device\n"
			 "<key slot> is the LUKS key slot number to modify\n"
			 "<key file> optional key file for the new key for luksAddKey action\n"),
			crypt_get_dir());
		exit(0);
	} else
		usage(popt_context, 0, NULL, NULL);
419 420
}

421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
void set_debug_level(int level);

static void _dbg_version_and_cmd(int argc, char **argv)
{
	int i;

	log_std("# %s %s processing \"", PACKAGE_NAME, PACKAGE_VERSION);
	for (i = 0; i < argc; i++) {
		if (i)
			log_std(" ");
		log_std(argv[i]);
	}
	log_std("\"\n");
}

436 437 438 439 440
static int run_action(struct action_type *action)
{
	int r;

	if (dm_init(NULL, action->required_dm_backend) < 1) {
441
		log_err("Cannot communicate with device-mapper. Is dm_mod kernel module loaded?\n");
442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460
		return -ENOSYS;
	}

	if (action->required_memlock)
		memlock_inc(NULL);

	r = action->handler(action->arg);

	if (action->required_memlock)
		memlock_dec(NULL);

	if (action->required_dm_backend)
		dm_exit();

	if (r < 0 && (opt_verbose || action->show_status))
		show_status(-r);

	return r;
}
461 462 463 464 465 466 467 468 469 470 471 472 473

int main(int argc, char **argv)
{
	static char *popt_tmp;
	static struct poptOption popt_help_options[] = {
		{ NULL,    '\0', POPT_ARG_CALLBACK, help, 0, NULL,                         NULL },
		{ "help",  '?',  POPT_ARG_NONE,     NULL, 0, N_("Show this help message"), NULL },
		{ "usage", '\0', POPT_ARG_NONE,     NULL, 0, N_("Display brief usage"),    NULL },
		POPT_TABLEEND
	};
	static struct poptOption popt_options[] = {
		{ NULL,                '\0', POPT_ARG_INCLUDE_TABLE,                      popt_help_options,      0, N_("Help options:"),                                                   NULL },
		{ "verbose",           'v',  POPT_ARG_NONE,                               &opt_verbose,           0, N_("Shows more detailed error messages"),                              NULL },
474
		{ "debug",             '\0', POPT_ARG_NONE,                               &opt_debug,             0, N_("Show debug messsgages"),                                           NULL },
475 476 477 478 479 480 481 482 483 484 485 486 487
		{ "cipher",            'c',  POPT_ARG_STRING | POPT_ARGFLAG_SHOW_DEFAULT, &opt_cipher,            0, N_("The cipher used to encrypt the disk (see /proc/crypto)"),          NULL },
		{ "hash",              'h',  POPT_ARG_STRING | POPT_ARGFLAG_SHOW_DEFAULT, &opt_hash,              0, N_("The hash used to create the encryption key from the passphrase"),  NULL },
		{ "verify-passphrase", 'y',  POPT_ARG_NONE,                               &opt_verify_passphrase, 0, N_("Verifies the passphrase by asking for it twice"),                  NULL },
		{ "key-file",          'd',  POPT_ARG_STRING,                             &opt_key_file,          0, N_("Read the key from a file (can be /dev/random)"),                   NULL },
		{ "key-size",          's',  POPT_ARG_INT    | POPT_ARGFLAG_SHOW_DEFAULT, &opt_key_size,          0, N_("The size of the encryption key"),                                  N_("BITS") },
		{ "key-slot",          'S',  POPT_ARG_INT,                                &opt_key_slot,          0, N_("Slot number for new key (default is first free)"),      NULL },
		{ "size",              'b',  POPT_ARG_STRING,                             &popt_tmp,              1, N_("The size of the device"),                                          N_("SECTORS") },
		{ "offset",            'o',  POPT_ARG_STRING,                             &popt_tmp,              2, N_("The start offset in the backend device"),                          N_("SECTORS") },
		{ "skip",              'p',  POPT_ARG_STRING,                             &popt_tmp,              3, N_("How many sectors of the encrypted data to skip at the beginning"), N_("SECTORS") },
		{ "readonly",          'r',  POPT_ARG_NONE,                               &opt_readonly,          0, N_("Create a readonly mapping"),                                       NULL },
		{ "iter-time",         'i',  POPT_ARG_INT,                                &opt_iteration_time,    0, N_("PBKDF2 iteration time for LUKS (in ms)"),
		  N_("msecs") },
		{ "batch-mode",        'q',  POPT_ARG_NONE,                               &opt_batch_mode,        0, N_("Do not ask for confirmation"),                                     NULL },
488
		{ "version",        '\0',  POPT_ARG_NONE,                                 &opt_version_mode,        0, N_("Print package version"),                                     NULL },
489 490 491 492
		{ "timeout",           't',  POPT_ARG_INT,                                &opt_timeout,           0, N_("Timeout for interactive passphrase prompt (in seconds)"),          N_("secs") },
		{ "tries",             'T',  POPT_ARG_INT,                                &opt_tries,             0, N_("How often the input of the passphrase canbe retried"),            NULL },
		{ "align-payload",     '\0',  POPT_ARG_INT,                               &opt_align_payload,     0, N_("Align payload at <n> sector boundaries - for luksFormat"),         N_("SECTORS") },
		{ "non-exclusive",     '\0',  POPT_ARG_NONE,                              &opt_non_exclusive,     0, N_("Allows non-exclusive access for luksOpen, WARNING see manpage."),        NULL },
493 494 495 496 497 498 499 500
		POPT_TABLEEND
	};
	poptContext popt_context;
	struct action_type *action;
	char *aname;
	int r;
	const char *null_action_argv[] = {NULL};

501 502
	set_default_log(cmdLineLog);

503
	setlocale(LC_ALL, "");
504 505
	bindtextdomain(PACKAGE, LOCALEDIR);
	textdomain(PACKAGE);
506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539

	popt_context = poptGetContext(PACKAGE, argc, (const char **)argv,
	                              popt_options, 0);
	poptSetOtherOptionHelp(popt_context,
	                       N_("[OPTION...] <action> <action-specific>]"));

	while((r = poptGetNextOpt(popt_context)) > 0) {
		unsigned long long ull_value;
		char *endp;

		ull_value = strtoull(popt_tmp, &endp, 0);
		if (*endp || !*popt_tmp)
			r = POPT_ERROR_BADNUMBER;

		switch(r) {
			case 1:
				opt_size = ull_value;
				break;
			case 2:
				opt_offset = ull_value;
				break;
			case 3:
				opt_skip = ull_value;
				break;
		}

		if (r < 0)
			break;
	}

	if (r < -1)
		usage(popt_context, 1, poptStrerror(r),
		      poptBadOption(popt_context, POPT_BADOPTION_NOALIAS));
	if (opt_version_mode) {
540
		log_std("%s %s\n", PACKAGE_NAME, PACKAGE_VERSION);
541 542
		exit(0);
	}
543

544 545 546 547
	if (opt_key_size % 8)
		usage(popt_context, 1,
		      _("Key size must be a multiple of 8 bits"),
		      poptGetInvocationName(popt_context));
548

549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
	if (!(aname = (char *)poptGetArg(popt_context)))
		usage(popt_context, 1, _("Argument <action> missing."),
		      poptGetInvocationName(popt_context));
	for(action = action_types; action->type; action++)
		if (strcmp(action->type, aname) == 0)
			break;
	if (!action->type)
		usage(popt_context, 1, _("Unknown action."),
		      poptGetInvocationName(popt_context));

	action_argc = 0;
	action_argv = poptGetArgs(popt_context);
	/* Make return values of poptGetArgs more consistent in case of remaining argc = 0 */
	if(!action_argv) 
		action_argv = null_action_argv;
564

565 566 567 568 569 570 571 572 573
	/* Count args, somewhat unnice, change? */
	while(action_argv[action_argc] != NULL)
		action_argc++;

	if(action_argc < action->required_action_argc) {
		char buf[128];
		snprintf(buf, 128,_("%s: requires %s as arguments"), action->type, action->arg_desc);
		usage(popt_context, 1, buf,
		      poptGetInvocationName(popt_context));
574
	}
575

576 577 578 579 580 581
	if (opt_debug) {
		opt_verbose = 1;
		crypt_set_debug_level(-1);
		_dbg_version_and_cmd(argc, argv);
	}

582 583
	return run_action(action);
}