utils_crypt.c 12.3 KB
Newer Older
1
/*
Milan Broz's avatar
Milan Broz committed
2
 * utils_crypt - cipher utilities for cryptsetup
3 4
 *
 * Copyright (C) 2004-2007, Clemens Fruhwirth <clemens@endorphin.org>
Milan Broz's avatar
Milan Broz committed
5
 * Copyright (C) 2009-2012, Red Hat, Inc. All rights reserved.
6
 * Copyright (C) 2009-2012, Milan Broz
7 8 9
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
10 11
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
12 13 14 15 16 17 18 19
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
20
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 22
 */

23 24
#include <stdlib.h>
#include <stddef.h>
25 26 27
#include <stdio.h>
#include <string.h>
#include <errno.h>
28 29
#include <ctype.h>
#include <limits.h>
30 31 32 33 34
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
35

36 37
#include "libcryptsetup.h"
#include "nls.h"
Milan Broz's avatar
Milan Broz committed
38
#include "utils_crypt.h"
39

40 41 42
#define log_dbg(x) crypt_log(NULL, CRYPT_LOG_DEBUG, x)
#define log_err(cd, x) crypt_log(cd, CRYPT_LOG_ERROR, x)

43 44 45 46 47
struct safe_allocation {
	size_t	size;
	char	data[0];
};

48 49
int crypt_parse_name_and_mode(const char *s, char *cipher, int *key_nums,
			      char *cipher_mode)
50 51 52
{
	if (sscanf(s, "%" MAX_CIPHER_LEN_STR "[^-]-%" MAX_CIPHER_LEN_STR "s",
		   cipher, cipher_mode) == 2) {
53 54
		if (!strcmp(cipher_mode, "plain"))
			strncpy(cipher_mode, "cbc-plain", 10);
55 56 57 58 59 60 61
		if (key_nums) {
			char *tmp = strchr(cipher, ':');
			*key_nums = tmp ? atoi(++tmp) : 1;
			if (!*key_nums)
				return -EINVAL;
		}

62 63 64
		return 0;
	}

65 66 67
	/* Short version for "empty" cipher */
	if (!strcmp(s, "null")) {
		strncpy(cipher, "cipher_null", MAX_CIPHER_LEN);
68
		strncpy(cipher_mode, "ecb", 9);
69 70 71 72 73
		if (key_nums)
			*key_nums = 0;
		return 0;
	}

74
	if (sscanf(s, "%" MAX_CIPHER_LEN_STR "[^-]", cipher) == 1) {
75
		strncpy(cipher_mode, "cbc-plain", 10);
76 77
		if (key_nums)
			*key_nums = 1;
78 79 80 81 82
		return 0;
	}

	return -EINVAL;
}
83

84 85 86 87 88 89 90 91 92 93 94 95
/*
 * Replacement for memset(s, 0, n) on stack that can be optimized out
 * Also used in safe allocations for explicit memory wipe.
 */
void crypt_memzero(void *s, size_t n)
{
	volatile uint8_t *p = (volatile uint8_t *)s;

	while(n--)
		*p++ = 0;
}

96 97 98 99 100 101 102 103 104 105 106 107 108
/* safe allocations */
void *crypt_safe_alloc(size_t size)
{
	struct safe_allocation *alloc;

	if (!size)
		return NULL;

	alloc = malloc(size + offsetof(struct safe_allocation, data));
	if (!alloc)
		return NULL;

	alloc->size = size;
109
	crypt_memzero(&alloc->data, size);
110

111
	/* coverity[leaked_storage] */
112 113 114 115 116 117 118 119 120 121
	return &alloc->data;
}

void crypt_safe_free(void *data)
{
	struct safe_allocation *alloc;

	if (!data)
		return;

122 123
	alloc = (struct safe_allocation *)
		((char *)data - offsetof(struct safe_allocation, data));
124

125
	crypt_memzero(data, alloc->size);
126 127 128 129 130 131 132

	alloc->size = 0x55aa55aa;
	free(alloc);
}

void *crypt_safe_realloc(void *data, size_t size)
{
133
	struct safe_allocation *alloc;
134 135 136 137 138 139
	void *new_data;

	new_data = crypt_safe_alloc(size);

	if (new_data && data) {

140 141
		alloc = (struct safe_allocation *)
			((char *)data - offsetof(struct safe_allocation, data));
142 143 144 145 146 147 148 149 150 151

		if (size > alloc->size)
			size = alloc->size;

		memcpy(new_data, data, size);
	}

	crypt_safe_free(data);
	return new_data;
}
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171

/* Password reading helpers */
static int untimed_read(int fd, char *pass, size_t maxlen)
{
	ssize_t i;

	i = read(fd, pass, maxlen);
	if (i > 0) {
		pass[i-1] = '\0';
		i = 0;
	} else if (i == 0) { /* EOF */
		*pass = 0;
		i = -1;
	}
	return i;
}

static int timed_read(int fd, char *pass, size_t maxlen, long timeout)
{
	struct timeval t;
172
	fd_set fds = {}; /* Just to avoid scan-build false report for FD_SET */
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
	int failed = -1;

	FD_ZERO(&fds);
	FD_SET(fd, &fds);
	t.tv_sec = timeout;
	t.tv_usec = 0;

	if (select(fd+1, &fds, NULL, NULL, &t) > 0)
		failed = untimed_read(fd, pass, maxlen);

	return failed;
}

static int interactive_pass(const char *prompt, char *pass, size_t maxlen,
		long timeout)
{
	struct termios orig, tmp;
	int failed = -1;
191
	int infd, outfd;
192 193

	if (maxlen < 1)
194
		return failed;
195 196

	/* Read and write to /dev/tty if available */
197 198
	infd = open("/dev/tty", O_RDWR);
	if (infd == -1) {
199 200
		infd = STDIN_FILENO;
		outfd = STDERR_FILENO;
201 202
	} else
		outfd = infd;
203 204 205 206 207 208 209

	if (tcgetattr(infd, &orig))
		goto out_err;

	memcpy(&tmp, &orig, sizeof(tmp));
	tmp.c_lflag &= ~ECHO;

210
	if (prompt && write(outfd, prompt, strlen(prompt)) < 0)
211 212 213 214 215 216 217 218 219 220
		goto out_err;

	tcsetattr(infd, TCSAFLUSH, &tmp);
	if (timeout)
		failed = timed_read(infd, pass, maxlen, timeout);
	else
		failed = untimed_read(infd, pass, maxlen);
	tcsetattr(infd, TCSAFLUSH, &orig);

out_err:
221
	if (!failed && write(outfd, "\n", 1)) {};
222 223 224 225 226 227

	if (infd != STDIN_FILENO)
		close(infd);
	return failed;
}

228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
static int crypt_get_key_tty(const char *prompt,
			     char **key, size_t *key_size,
			     int timeout, int verify,
			     struct crypt_device *cd)
{
	int key_size_max = DEFAULT_PASSPHRASE_SIZE_MAX;
	int r = -EINVAL;
	char *pass = NULL, *pass_verify = NULL;

	log_dbg("Interactive passphrase entry requested.");

	pass = crypt_safe_alloc(key_size_max + 1);
	if (!pass) {
		log_err(cd, _("Out of memory while reading passphrase.\n"));
		return -ENOMEM;
	}

	if (interactive_pass(prompt, pass, key_size_max, timeout)) {
		log_err(cd, _("Error reading passphrase from terminal.\n"));
		goto out_err;
	}
	pass[key_size_max] = '\0';

	if (verify) {
		pass_verify = crypt_safe_alloc(key_size_max);
		if (!pass_verify) {
			log_err(cd, _("Out of memory while reading passphrase.\n"));
			r = -ENOMEM;
			goto out_err;
		}

		if (interactive_pass(_("Verify passphrase: "),
		    pass_verify, key_size_max, timeout)) {
			log_err(cd, _("Error reading passphrase from terminal.\n"));
			goto out_err;
		}

		if (strncmp(pass, pass_verify, key_size_max)) {
			log_err(cd, _("Passphrases do not match.\n"));
267
			r = -EPERM;
268 269 270 271 272 273 274 275 276 277 278 279 280 281
			goto out_err;
		}
	}

	*key = pass;
	*key_size = strlen(pass);
	r = 0;
out_err:
	crypt_safe_free(pass_verify);
	if (r)
		crypt_safe_free(pass);
	return r;
}

282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
/*
 * A simple call to lseek(3) might not be possible for some inputs (e.g.
 * reading from a pipe), so this function instead reads of up to BUFSIZ bytes
 * at a time until the specified number of bytes. It returns -1 on read error
 * or when it reaches EOF before the requested number of bytes have been
 * discarded.
 */
static int keyfile_seek(int fd, size_t bytes)
{
	char tmp[BUFSIZ];
	size_t next_read;
	ssize_t bytes_r;
	off_t r;

	r = lseek(fd, bytes, SEEK_CUR);
	if (r > 0)
		return 0;
	if (r < 0 && errno != ESPIPE)
		return -1;

	while (bytes > 0) {
		/* figure out how much to read */
		next_read = bytes > sizeof(tmp) ? sizeof(tmp) : bytes;

		bytes_r = read(fd, tmp, next_read);
		if (bytes_r < 0) {
			if (errno == EINTR)
				continue;

			/* read error */
			return -1;
		}

		if (bytes_r == 0)
			/* EOF */
			break;

		bytes -= bytes_r;
	}

	return bytes == 0 ? 0 : -1;
}

325 326
/*
 * Note: --key-file=- is interpreted as a read from a binary file (stdin)
327 328
 * key_size_max == 0 means detect maximum according to input type (tty/file)
 * timeout and verify options only applies to tty input
329
 */
330 331
int crypt_get_key(const char *prompt,
		  char **key, size_t *key_size,
332 333
		  size_t keyfile_offset, size_t keyfile_size_max,
		  const char *key_file, int timeout, int verify,
334
		  struct crypt_device *cd)
335
{
336
	int fd, regular_file, read_stdin, char_read, unlimited_read = 0;
337
	int r = -EINVAL, newline;
338
	char *pass = NULL;
339
	size_t buflen, i, file_read_size;
340 341
	struct stat st;

342 343 344
	*key = NULL;
	*key_size = 0;

345 346 347
	/* Passphrase read from stdin? */
	read_stdin = (!key_file || !strcmp(key_file, "-")) ? 1 : 0;

348 349 350 351 352
	if (read_stdin && isatty(STDIN_FILENO)) {
		if (keyfile_offset) {
			log_err(cd, _("Cannot use offset with terminal input.\n"));
			return -EINVAL;
		}
353
		return crypt_get_key_tty(prompt, key, key_size, timeout, verify, cd);
354
	}
355

356 357 358 359 360
	if (read_stdin)
		log_dbg("STDIN descriptor passphrase entry requested.");
	else
		log_dbg("File descriptor passphrase entry requested.");

361 362 363 364 365
	/* If not requsted otherwise, we limit input to prevent memory exhaustion */
	if (keyfile_size_max == 0) {
		keyfile_size_max = DEFAULT_KEYFILE_SIZE_MAXKB * 1024;
		unlimited_read = 1;
	}
366 367 368

	fd = read_stdin ? STDIN_FILENO : open(key_file, O_RDONLY);
	if (fd < 0) {
369 370
		log_err(cd, _("Failed to open key file.\n"));
		return -EINVAL;
371 372
	}

373 374 375 376 377 378
	/* use 4k for buffer (page divisor but avoid huge pages) */
	buflen = 4096 - sizeof(struct safe_allocation);
	regular_file = 0;
	if(!read_stdin) {
		if(stat(key_file, &st) < 0) {
			log_err(cd, _("Failed to stat key file.\n"));
379 380
			goto out_err;
		}
381 382
		if(S_ISREG(st.st_mode)) {
			regular_file = 1;
383 384 385 386 387 388 389 390
			file_read_size = (size_t)st.st_size;

			if (keyfile_offset > file_read_size) {
				log_err(cd, _("Cannot seek to requested keyfile offset.\n"));
				goto out_err;
			}
			file_read_size -= keyfile_offset;

391
			/* known keyfile size, alloc it in one step */
392
			if (file_read_size >= keyfile_size_max)
393
				buflen = keyfile_size_max;
394 395
			else if (file_read_size)
				buflen = file_read_size;
396
		}
397
	}
398

399 400 401 402 403 404
	pass = crypt_safe_alloc(buflen);
	if (!pass) {
		log_err(cd, _("Out of memory while reading passphrase.\n"));
		goto out_err;
	}

405
	/* Discard keyfile_offset bytes on input */
406 407 408 409
	if (keyfile_offset && keyfile_seek(fd, keyfile_offset) < 0) {
		log_err(cd, _("Cannot seek to requested keyfile offset.\n"));
		goto out_err;
	}
410

411
	for(i = 0, newline = 0; i < keyfile_size_max; i++) {
412 413 414 415 416 417
		if(i == buflen) {
			buflen += 4096;
			pass = crypt_safe_realloc(pass, buflen);
			if (!pass) {
				log_err(cd, _("Out of memory while reading passphrase.\n"));
				r = -ENOMEM;
418 419 420
				goto out_err;
			}
		}
421 422 423 424

		char_read = read(fd, &pass[i], 1);
		if (char_read < 0) {
			log_err(cd, _("Error reading passphrase.\n"));
425
			goto out_err;
426 427 428
		}

		/* Stop on newline only if not requested read from keyfile */
429 430 431 432 433
		if (char_read == 0)
			break;
		if (!key_file && pass[i] == '\n') {
			newline = 1;
			pass[i] = '\0';
434
			break;
435
		}
436 437 438
	}

	/* Fail if piped input dies reading nothing */
439
	if(!i && !regular_file && !newline) {
440 441
		log_dbg("Nothing read on input.");
		r = -EPIPE;
442
		goto out_err;
443
	}
444 445 446

	/* Fail if we exceeded internal default (no specified size) */
	if (unlimited_read && i == keyfile_size_max) {
Yuri Chornoivan's avatar
Yuri Chornoivan committed
447
		log_err(cd, _("Maximum keyfile size exceeded.\n"));
448 449 450 451 452 453 454 455 456 457 458
		goto out_err;
	}

	if (!unlimited_read && i != keyfile_size_max) {
		log_err(cd, _("Cannot read requested amount of data.\n"));
		goto out_err;
	}

	*key = pass;
	*key_size = i;
	r = 0;
459
out_err:
460
	if(fd != STDIN_FILENO)
461
		close(fd);
462 463

	if (r)
464
		crypt_safe_free(pass);
465
	return r;
466
}
467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492

ssize_t crypt_hex_to_bytes(const char *hex, char **result, int safe_alloc)
{
	char buf[3] = "xx\0", *endp, *bytes;
	size_t i, len;

	len = strlen(hex);
	if (len % 2)
		return -EINVAL;
	len /= 2;

	bytes = safe_alloc ? crypt_safe_alloc(len) : malloc(len);
	if (!bytes)
		return -ENOMEM;

	for (i = 0; i < len; i++) {
		memcpy(buf, &hex[i * 2], 2);
		bytes[i] = strtoul(buf, &endp, 16);
		if (endp != &buf[2]) {
			safe_alloc ? crypt_safe_free(bytes) : free(bytes);
			return -EINVAL;
		}
	}
	*result = bytes;
	return i;
}
493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512

/*
 * Device size string parsing, suffixes:
 * s|S - 512 bytes sectors
 * k  |K  |m  |M  |g  |G  |t  |T   - 1024 base
 * kiB|KiB|miB|MiB|giB|GiB|tiB|TiB - 1024 base
 * kb |KB |mM |MB |gB |GB |tB |TB  - 1000 base
 */
int crypt_string_to_size(struct crypt_device *cd, const char *s, uint64_t *size)
{
	char *endp = NULL;
	size_t len;
	uint64_t mult_base, mult, tmp;

	*size = strtoull(s, &endp, 10);
	if (!isdigit(s[0]) ||
	    (errno == ERANGE && *size == ULLONG_MAX) ||
	    (errno != 0 && *size == 0))
		return -EINVAL;

513
	if (!endp || !*endp)
514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
		return 0;

	len = strlen(endp);
	/* Allow "B" and "iB" suffixes */
	if (len > 3 ||
	   (len == 3 && (endp[1] != 'i' || endp[2] != 'B')) ||
	   (len == 2 && endp[1] != 'B'))
		return -EINVAL;

	if (len == 1 || len == 3)
		mult_base = 1024;
	else
		mult_base = 1000;

	mult = 1;
	switch (endp[0]) {
	case 's':
	case 'S': mult = 512;
		break;
	case 't':
	case 'T': mult *= mult_base;
535
		 /* Fall through */
536 537
	case 'g':
	case 'G': mult *= mult_base;
538
		 /* Fall through */
539 540
	case 'm':
	case 'M': mult *= mult_base;
541
		 /* Fall through */
542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557
	case 'k':
	case 'K': mult *= mult_base;
		break;
	default:
		return -EINVAL;
	}

	tmp = *size * mult;
	if ((tmp / *size) != mult) {
		log_dbg("Device size overflow.");
		return -EINVAL;
	}

	*size = tmp;
	return 0;
}