utils_crypt.c 8.37 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
/*
 * util_crypt - cipher utilities for cryptsetup
 *
 * Copyright (C) 2004-2007, Clemens Fruhwirth <clemens@endorphin.org>
 * Copyright (C) 2009-2011, Red Hat, Inc. All rights reserved.
 *
 * 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
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

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

32 33
#include "libcryptsetup.h"
#include "nls.h"
Milan Broz's avatar
Milan Broz committed
34
#include "utils_crypt.h"
35

36 37 38
#define log_dbg(x) crypt_log(NULL, CRYPT_LOG_DEBUG, x)
#define log_err(cd, x) crypt_log(cd, CRYPT_LOG_ERROR, x)

39 40 41 42 43
struct safe_allocation {
	size_t	size;
	char	data[0];
};

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

58 59 60 61
		return 0;
	}

	if (sscanf(s, "%" MAX_CIPHER_LEN_STR "[^-]", cipher) == 1) {
62
		strncpy(cipher_mode, "cbc-plain", 10);
63 64
		if (key_nums)
			*key_nums = 1;
65 66 67 68 69
		return 0;
	}

	return -EINVAL;
}
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94

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

	return &alloc->data;
}

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

	if (!data)
		return;

95 96
	alloc = (struct safe_allocation *)
		((char *)data - offsetof(struct safe_allocation, data));
97 98 99 100 101 102 103 104 105

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

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

void *crypt_safe_realloc(void *data, size_t size)
{
106
	struct safe_allocation *alloc;
107 108 109 110 111 112
	void *new_data;

	new_data = crypt_safe_alloc(size);

	if (new_data && data) {

113 114
		alloc = (struct safe_allocation *)
			((char *)data - offsetof(struct safe_allocation, data));
115 116 117 118 119 120 121 122 123 124

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

		memcpy(new_data, data, size);
	}

	crypt_safe_free(data);
	return new_data;
}
125 126 127 128 129 130 131 132 133 134 135 136 137 138 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

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

181
	if (prompt && write(outfd, prompt, strlen(prompt)) < 0)
182 183 184 185 186 187 188 189 190 191
		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:
192
	if (!failed && write(outfd, "\n", 1)) {};
193 194 195 196 197 198

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

199 200 201 202 203 204 205 206 207 208 209 210 211 212 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"));
			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;
}

252 253
/*
 * Note: --key-file=- is interpreted as a read from a binary file (stdin)
254 255
 * key_size_max == 0 means detect maximum according to input type (tty/file)
 * timeout and verify options only applies to tty input
256
 */
257 258 259 260
int crypt_get_key(const char *prompt,
		  char **key, size_t *key_size,
		  size_t keyfile_size_max, const char *key_file,
		  int timeout, int verify,
261
		  struct crypt_device *cd)
262
{
263 264
	int fd, regular_file, read_stdin, char_read, unlimited_read = 0;
	int r = -EINVAL;
265
	char *pass = NULL;
266
	size_t buflen, i;
267 268
	struct stat st;

269 270 271
	*key = NULL;
	*key_size = 0;

272 273 274
	/* Passphrase read from stdin? */
	read_stdin = (!key_file || !strcmp(key_file, "-")) ? 1 : 0;

275 276 277
	if(read_stdin && isatty(STDIN_FILENO))
		return crypt_get_key_tty(prompt, key, key_size, timeout, verify, cd);

278 279 280 281 282
	if (read_stdin)
		log_dbg("STDIN descriptor passphrase entry requested.");
	else
		log_dbg("File descriptor passphrase entry requested.");

283 284 285 286 287
	/* 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;
	}
288 289 290

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

295 296 297 298 299 300
	/* 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"));
301 302
			goto out_err;
		}
303 304 305
		if(S_ISREG(st.st_mode)) {
			regular_file = 1;
			/* known keyfile size, alloc it in one step */
306
			if ((size_t)st.st_size >= keyfile_size_max)
307
				buflen = keyfile_size_max;
308
			else
309
				buflen = st.st_size;
310
		}
311
	}
312

313 314 315 316 317 318 319 320 321 322 323 324 325
	pass = crypt_safe_alloc(buflen);
	if (!pass) {
		log_err(cd, _("Out of memory while reading passphrase.\n"));
		goto out_err;
	}

	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;
326 327 328
				goto out_err;
			}
		}
329 330 331 332

		char_read = read(fd, &pass[i], 1);
		if (char_read < 0) {
			log_err(cd, _("Error reading passphrase.\n"));
333
			goto out_err;
334 335 336 337 338 339 340 341
		}

		/* 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 */
342 343 344
	if(!i && !regular_file) {
		log_dbg("Nothing read on input.");
		r = -EPIPE;
345
		goto out_err;
346
	}
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362

	/* Fail if we exceeded internal default (no specified size) */
	if (unlimited_read && i == keyfile_size_max) {
		log_err(cd, _("Maximum keyfile size exceeeded.\n"));
		goto out_err;
	}

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

	/* Well, for historical reasons reading empty keyfile is not fail. */
	if(!i) {
		crypt_safe_free(pass);
		pass = NULL;
363 364
	}

365 366 367
	*key = pass;
	*key_size = i;
	r = 0;
368
out_err:
369
	if(fd != STDIN_FILENO)
370
		close(fd);
371 372

	if (r)
373
		crypt_safe_free(pass);
374
	return r;
375
}