utils_crypt.c 11.8 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 10 11 12 13 14 15 16 17 18
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * version 2 as published by the Free Software Foundation.
 *
 * 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
19
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 21
 */

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

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

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

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

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

61 62 63
		return 0;
	}

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

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

	return -EINVAL;
}
82 83 84 85 86 87 88 89 90 91 92 93 94 95

/* 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;
96
	memset(&alloc->data, 0, size);
97

98
	/* coverity[leaked_storage] */
99 100 101 102 103 104 105 106 107 108
	return &alloc->data;
}

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

	if (!data)
		return;

109 110
	alloc = (struct safe_allocation *)
		((char *)data - offsetof(struct safe_allocation, data));
111 112 113 114 115 116 117 118 119

	memset(data, 0, alloc->size);

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

void *crypt_safe_realloc(void *data, size_t size)
{
120
	struct safe_allocation *alloc;
121 122 123 124 125 126
	void *new_data;

	new_data = crypt_safe_alloc(size);

	if (new_data && data) {

127 128
		alloc = (struct safe_allocation *)
			((char *)data - offsetof(struct safe_allocation, data));
129 130 131 132 133 134 135 136 137 138

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

		memcpy(new_data, data, size);
	}

	crypt_safe_free(data);
	return new_data;
}
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194

/* 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;
	fd_set fds;
	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;
	int infd = STDIN_FILENO, outfd;

	if (maxlen < 1)
		goto out_err;

	/* Read and write to /dev/tty if available */
	if ((infd = outfd = open("/dev/tty", O_RDWR)) == -1) {
		infd = STDIN_FILENO;
		outfd = STDERR_FILENO;
	}

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

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

195
	if (prompt && write(outfd, prompt, strlen(prompt)) < 0)
196 197 198 199 200 201 202 203 204 205
		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:
206
	if (!failed && write(outfd, "\n", 1)) {};
207 208 209 210 211 212

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

213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
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"));
252
			r = -EPERM;
253 254 255 256 257 258 259 260 261 262 263 264 265 266
			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;
}

267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 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
/*
 * 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;
}

310 311
/*
 * Note: --key-file=- is interpreted as a read from a binary file (stdin)
312 313
 * key_size_max == 0 means detect maximum according to input type (tty/file)
 * timeout and verify options only applies to tty input
314
 */
315 316
int crypt_get_key(const char *prompt,
		  char **key, size_t *key_size,
317 318
		  size_t keyfile_offset, size_t keyfile_size_max,
		  const char *key_file, int timeout, int verify,
319
		  struct crypt_device *cd)
320
{
321 322
	int fd, regular_file, read_stdin, char_read, unlimited_read = 0;
	int r = -EINVAL;
323
	char *pass = NULL;
324
	size_t buflen, i, file_read_size;
325 326
	struct stat st;

327 328 329
	*key = NULL;
	*key_size = 0;

330 331 332
	/* Passphrase read from stdin? */
	read_stdin = (!key_file || !strcmp(key_file, "-")) ? 1 : 0;

333 334 335 336 337
	if (read_stdin && isatty(STDIN_FILENO)) {
		if (keyfile_offset) {
			log_err(cd, _("Cannot use offset with terminal input.\n"));
			return -EINVAL;
		}
338
		return crypt_get_key_tty(prompt, key, key_size, timeout, verify, cd);
339
	}
340

341 342 343 344 345
	if (read_stdin)
		log_dbg("STDIN descriptor passphrase entry requested.");
	else
		log_dbg("File descriptor passphrase entry requested.");

346 347 348 349 350
	/* 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;
	}
351 352 353

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

358 359 360 361 362 363
	/* 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"));
364 365
			goto out_err;
		}
366 367
		if(S_ISREG(st.st_mode)) {
			regular_file = 1;
368 369 370 371 372 373 374 375
			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;

376
			/* known keyfile size, alloc it in one step */
377
			if (file_read_size >= keyfile_size_max)
378
				buflen = keyfile_size_max;
379 380
			else if (file_read_size)
				buflen = file_read_size;
381
		}
382
	}
383

384 385 386 387 388 389
	pass = crypt_safe_alloc(buflen);
	if (!pass) {
		log_err(cd, _("Out of memory while reading passphrase.\n"));
		goto out_err;
	}

390
	/* Discard keyfile_offset bytes on input */
391 392 393 394
	if (keyfile_offset && keyfile_seek(fd, keyfile_offset) < 0) {
		log_err(cd, _("Cannot seek to requested keyfile offset.\n"));
		goto out_err;
	}
395

396 397 398 399 400 401 402
	for(i = 0; i < keyfile_size_max; i++) {
		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;
403 404 405
				goto out_err;
			}
		}
406 407 408 409

		char_read = read(fd, &pass[i], 1);
		if (char_read < 0) {
			log_err(cd, _("Error reading passphrase.\n"));
410
			goto out_err;
411 412 413 414 415 416 417 418
		}

		/* Stop on newline only if not requested read from keyfile */
		if(char_read == 0 || (!key_file && pass[i] == '\n'))
			break;
	}

	/* Fail if piped input dies reading nothing */
419 420 421
	if(!i && !regular_file) {
		log_dbg("Nothing read on input.");
		r = -EPIPE;
422
		goto out_err;
423
	}
424 425 426

	/* Fail if we exceeded internal default (no specified size) */
	if (unlimited_read && i == keyfile_size_max) {
Yuri Chornoivan's avatar
Yuri Chornoivan committed
427
		log_err(cd, _("Maximum keyfile size exceeded.\n"));
428 429 430 431 432 433 434 435 436 437 438
		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;
439
out_err:
440
	if(fd != STDIN_FILENO)
441
		close(fd);
442 443

	if (r)
444
		crypt_safe_free(pass);
445
	return r;
446
}
447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472

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;
}
473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492

/*
 * 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;

493
	if (!endp || !*endp)
494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
		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;
515
		 /* Fall through */
516 517
	case 'g':
	case 'G': mult *= mult_base;
518
		 /* Fall through */
519 520
	case 'm':
	case 'M': mult *= mult_base;
521
		 /* Fall through */
522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537
	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;
}