2 * utils_crypt - cipher utilities for cryptsetup
4 * Copyright (C) 2004-2007, Clemens Fruhwirth <clemens@endorphin.org>
5 * Copyright (C) 2009-2012, Red Hat, Inc. All rights reserved.
6 * Copyright (C) 2009-2012, Milan Broz
8 * This program is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU General Public License
10 * version 2 as published by the Free Software Foundation.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
29 #include <sys/types.h>
35 #include "libcryptsetup.h"
37 #include "utils_crypt.h"
39 #define log_dbg(x) crypt_log(NULL, CRYPT_LOG_DEBUG, x)
40 #define log_err(cd, x) crypt_log(cd, CRYPT_LOG_ERROR, x)
42 struct safe_allocation {
47 int crypt_parse_name_and_mode(const char *s, char *cipher, int *key_nums,
50 if (sscanf(s, "%" MAX_CIPHER_LEN_STR "[^-]-%" MAX_CIPHER_LEN_STR "s",
51 cipher, cipher_mode) == 2) {
52 if (!strcmp(cipher_mode, "plain"))
53 strncpy(cipher_mode, "cbc-plain", 10);
55 char *tmp = strchr(cipher, ':');
56 *key_nums = tmp ? atoi(++tmp) : 1;
64 /* Short version for "empty" cipher */
65 if (!strcmp(s, "null")) {
66 strncpy(cipher, "cipher_null", MAX_CIPHER_LEN);
67 strncpy(cipher_mode, "ecb", 9);
73 if (sscanf(s, "%" MAX_CIPHER_LEN_STR "[^-]", cipher) == 1) {
74 strncpy(cipher_mode, "cbc-plain", 10);
83 /* safe allocations */
84 void *crypt_safe_alloc(size_t size)
86 struct safe_allocation *alloc;
91 alloc = malloc(size + offsetof(struct safe_allocation, data));
96 memset(&alloc->data, 0, size);
98 /* coverity[leaked_storage] */
102 void crypt_safe_free(void *data)
104 struct safe_allocation *alloc;
109 alloc = (struct safe_allocation *)
110 ((char *)data - offsetof(struct safe_allocation, data));
112 memset(data, 0, alloc->size);
114 alloc->size = 0x55aa55aa;
118 void *crypt_safe_realloc(void *data, size_t size)
120 struct safe_allocation *alloc;
123 new_data = crypt_safe_alloc(size);
125 if (new_data && data) {
127 alloc = (struct safe_allocation *)
128 ((char *)data - offsetof(struct safe_allocation, data));
130 if (size > alloc->size)
133 memcpy(new_data, data, size);
136 crypt_safe_free(data);
140 /* Password reading helpers */
141 static int untimed_read(int fd, char *pass, size_t maxlen)
145 i = read(fd, pass, maxlen);
149 } else if (i == 0) { /* EOF */
156 static int timed_read(int fd, char *pass, size_t maxlen, long timeout)
167 if (select(fd+1, &fds, NULL, NULL, &t) > 0)
168 failed = untimed_read(fd, pass, maxlen);
173 static int interactive_pass(const char *prompt, char *pass, size_t maxlen,
176 struct termios orig, tmp;
178 int infd = STDIN_FILENO, outfd;
183 /* Read and write to /dev/tty if available */
184 if ((infd = outfd = open("/dev/tty", O_RDWR)) == -1) {
186 outfd = STDERR_FILENO;
189 if (tcgetattr(infd, &orig))
192 memcpy(&tmp, &orig, sizeof(tmp));
193 tmp.c_lflag &= ~ECHO;
195 if (prompt && write(outfd, prompt, strlen(prompt)) < 0)
198 tcsetattr(infd, TCSAFLUSH, &tmp);
200 failed = timed_read(infd, pass, maxlen, timeout);
202 failed = untimed_read(infd, pass, maxlen);
203 tcsetattr(infd, TCSAFLUSH, &orig);
206 if (!failed && write(outfd, "\n", 1)) {};
208 if (infd != STDIN_FILENO)
213 static int crypt_get_key_tty(const char *prompt,
214 char **key, size_t *key_size,
215 int timeout, int verify,
216 struct crypt_device *cd)
218 int key_size_max = DEFAULT_PASSPHRASE_SIZE_MAX;
220 char *pass = NULL, *pass_verify = NULL;
222 log_dbg("Interactive passphrase entry requested.");
224 pass = crypt_safe_alloc(key_size_max + 1);
226 log_err(cd, _("Out of memory while reading passphrase.\n"));
230 if (interactive_pass(prompt, pass, key_size_max, timeout)) {
231 log_err(cd, _("Error reading passphrase from terminal.\n"));
234 pass[key_size_max] = '\0';
237 pass_verify = crypt_safe_alloc(key_size_max);
239 log_err(cd, _("Out of memory while reading passphrase.\n"));
244 if (interactive_pass(_("Verify passphrase: "),
245 pass_verify, key_size_max, timeout)) {
246 log_err(cd, _("Error reading passphrase from terminal.\n"));
250 if (strncmp(pass, pass_verify, key_size_max)) {
251 log_err(cd, _("Passphrases do not match.\n"));
258 *key_size = strlen(pass);
261 crypt_safe_free(pass_verify);
263 crypt_safe_free(pass);
268 * A simple call to lseek(3) might not be possible for some inputs (e.g.
269 * reading from a pipe), so this function instead reads of up to BUFSIZ bytes
270 * at a time until the specified number of bytes. It returns -1 on read error
271 * or when it reaches EOF before the requested number of bytes have been
274 static int keyfile_seek(int fd, size_t bytes)
281 r = lseek(fd, bytes, SEEK_CUR);
284 if (r < 0 && errno != ESPIPE)
288 /* figure out how much to read */
289 next_read = bytes > sizeof(tmp) ? sizeof(tmp) : bytes;
291 bytes_r = read(fd, tmp, next_read);
307 return bytes == 0 ? 0 : -1;
311 * Note: --key-file=- is interpreted as a read from a binary file (stdin)
312 * key_size_max == 0 means detect maximum according to input type (tty/file)
313 * timeout and verify options only applies to tty input
315 int crypt_get_key(const char *prompt,
316 char **key, size_t *key_size,
317 size_t keyfile_offset, size_t keyfile_size_max,
318 const char *key_file, int timeout, int verify,
319 struct crypt_device *cd)
321 int fd, regular_file, read_stdin, char_read, unlimited_read = 0;
324 size_t buflen, i, file_read_size;
330 /* Passphrase read from stdin? */
331 read_stdin = (!key_file || !strcmp(key_file, "-")) ? 1 : 0;
333 if (read_stdin && isatty(STDIN_FILENO)) {
334 if (keyfile_offset) {
335 log_err(cd, _("Cannot use offset with terminal input.\n"));
338 return crypt_get_key_tty(prompt, key, key_size, timeout, verify, cd);
342 log_dbg("STDIN descriptor passphrase entry requested.");
344 log_dbg("File descriptor passphrase entry requested.");
346 /* If not requsted otherwise, we limit input to prevent memory exhaustion */
347 if (keyfile_size_max == 0) {
348 keyfile_size_max = DEFAULT_KEYFILE_SIZE_MAXKB * 1024;
352 fd = read_stdin ? STDIN_FILENO : open(key_file, O_RDONLY);
354 log_err(cd, _("Failed to open key file.\n"));
358 /* use 4k for buffer (page divisor but avoid huge pages) */
359 buflen = 4096 - sizeof(struct safe_allocation);
362 if(stat(key_file, &st) < 0) {
363 log_err(cd, _("Failed to stat key file.\n"));
366 if(S_ISREG(st.st_mode)) {
368 file_read_size = (size_t)st.st_size;
370 if (keyfile_offset > file_read_size) {
371 log_err(cd, _("Cannot seek to requested keyfile offset.\n"));
374 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 else if (file_read_size)
380 buflen = file_read_size;
384 pass = crypt_safe_alloc(buflen);
386 log_err(cd, _("Out of memory while reading passphrase.\n"));
390 /* Discard keyfile_offset bytes on input */
391 if (keyfile_offset && keyfile_seek(fd, keyfile_offset) < 0) {
392 log_err(cd, _("Cannot seek to requested keyfile offset.\n"));
396 for(i = 0; i < keyfile_size_max; i++) {
399 pass = crypt_safe_realloc(pass, buflen);
401 log_err(cd, _("Out of memory while reading passphrase.\n"));
407 char_read = read(fd, &pass[i], 1);
409 log_err(cd, _("Error reading passphrase.\n"));
413 /* Stop on newline only if not requested read from keyfile */
414 if(char_read == 0 || (!key_file && pass[i] == '\n'))
418 /* Fail if piped input dies reading nothing */
419 if(!i && !regular_file) {
420 log_dbg("Nothing read on input.");
425 /* Fail if we exceeded internal default (no specified size) */
426 if (unlimited_read && i == keyfile_size_max) {
427 log_err(cd, _("Maximum keyfile size exceeded.\n"));
431 if (!unlimited_read && i != keyfile_size_max) {
432 log_err(cd, _("Cannot read requested amount of data.\n"));
440 if(fd != STDIN_FILENO)
444 crypt_safe_free(pass);
448 ssize_t crypt_hex_to_bytes(const char *hex, char **result, int safe_alloc)
450 char buf[3] = "xx\0", *endp, *bytes;
458 bytes = safe_alloc ? crypt_safe_alloc(len) : malloc(len);
462 for (i = 0; i < len; i++) {
463 memcpy(buf, &hex[i * 2], 2);
464 bytes[i] = strtoul(buf, &endp, 16);
465 if (endp != &buf[2]) {
466 safe_alloc ? crypt_safe_free(bytes) : free(bytes);
475 * Device size string parsing, suffixes:
476 * s|S - 512 bytes sectors
477 * k |K |m |M |g |G |t |T - 1024 base
478 * kiB|KiB|miB|MiB|giB|GiB|tiB|TiB - 1024 base
479 * kb |KB |mM |MB |gB |GB |tB |TB - 1000 base
481 int crypt_string_to_size(struct crypt_device *cd, const char *s, uint64_t *size)
485 uint64_t mult_base, mult, tmp;
487 *size = strtoull(s, &endp, 10);
488 if (!isdigit(s[0]) ||
489 (errno == ERANGE && *size == ULLONG_MAX) ||
490 (errno != 0 && *size == 0))
497 /* Allow "B" and "iB" suffixes */
499 (len == 3 && (endp[1] != 'i' || endp[2] != 'B')) ||
500 (len == 2 && endp[1] != 'B'))
503 if (len == 1 || len == 3)
511 case 'S': mult = 512;
514 case 'T': mult *= mult_base;
517 case 'G': mult *= mult_base;
520 case 'M': mult *= mult_base;
523 case 'K': mult *= mult_base;
530 if ((tmp / *size) != mult) {
531 log_dbg("Device size overflow.");