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 * as published by the Free Software Foundation; either version 2
11 * of the License, or (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
30 #include <sys/types.h>
36 #include "libcryptsetup.h"
38 #include "utils_crypt.h"
40 #define log_dbg(x) crypt_log(NULL, CRYPT_LOG_DEBUG, x)
41 #define log_err(cd, x) crypt_log(cd, CRYPT_LOG_ERROR, x)
43 struct safe_allocation {
48 int crypt_parse_name_and_mode(const char *s, char *cipher, int *key_nums,
51 if (sscanf(s, "%" MAX_CIPHER_LEN_STR "[^-]-%" MAX_CIPHER_LEN_STR "s",
52 cipher, cipher_mode) == 2) {
53 if (!strcmp(cipher_mode, "plain"))
54 strncpy(cipher_mode, "cbc-plain", 10);
56 char *tmp = strchr(cipher, ':');
57 *key_nums = tmp ? atoi(++tmp) : 1;
65 /* Short version for "empty" cipher */
66 if (!strcmp(s, "null")) {
67 strncpy(cipher, "cipher_null", MAX_CIPHER_LEN);
68 strncpy(cipher_mode, "ecb", 9);
74 if (sscanf(s, "%" MAX_CIPHER_LEN_STR "[^-]", cipher) == 1) {
75 strncpy(cipher_mode, "cbc-plain", 10);
85 * Replacement for memset(s, 0, n) on stack that can be optimized out
86 * Also used in safe allocations for explicit memory wipe.
88 void crypt_memzero(void *s, size_t n)
90 volatile uint8_t *p = (volatile uint8_t *)s;
96 /* safe allocations */
97 void *crypt_safe_alloc(size_t size)
99 struct safe_allocation *alloc;
104 alloc = malloc(size + offsetof(struct safe_allocation, data));
109 crypt_memzero(&alloc->data, size);
111 /* coverity[leaked_storage] */
115 void crypt_safe_free(void *data)
117 struct safe_allocation *alloc;
122 alloc = (struct safe_allocation *)
123 ((char *)data - offsetof(struct safe_allocation, data));
125 crypt_memzero(data, alloc->size);
127 alloc->size = 0x55aa55aa;
131 void *crypt_safe_realloc(void *data, size_t size)
133 struct safe_allocation *alloc;
136 new_data = crypt_safe_alloc(size);
138 if (new_data && data) {
140 alloc = (struct safe_allocation *)
141 ((char *)data - offsetof(struct safe_allocation, data));
143 if (size > alloc->size)
146 memcpy(new_data, data, size);
149 crypt_safe_free(data);
153 /* Password reading helpers */
154 static int untimed_read(int fd, char *pass, size_t maxlen)
158 i = read(fd, pass, maxlen);
162 } else if (i == 0) { /* EOF */
169 static int timed_read(int fd, char *pass, size_t maxlen, long timeout)
172 fd_set fds = {}; /* Just to avoid scan-build false report for FD_SET */
180 if (select(fd+1, &fds, NULL, NULL, &t) > 0)
181 failed = untimed_read(fd, pass, maxlen);
186 static int interactive_pass(const char *prompt, char *pass, size_t maxlen,
189 struct termios orig, tmp;
196 /* Read and write to /dev/tty if available */
197 infd = open("/dev/tty", O_RDWR);
200 outfd = STDERR_FILENO;
204 if (tcgetattr(infd, &orig))
207 memcpy(&tmp, &orig, sizeof(tmp));
208 tmp.c_lflag &= ~ECHO;
210 if (prompt && write(outfd, prompt, strlen(prompt)) < 0)
213 tcsetattr(infd, TCSAFLUSH, &tmp);
215 failed = timed_read(infd, pass, maxlen, timeout);
217 failed = untimed_read(infd, pass, maxlen);
218 tcsetattr(infd, TCSAFLUSH, &orig);
221 if (!failed && write(outfd, "\n", 1)) {};
223 if (infd != STDIN_FILENO)
228 static int crypt_get_key_tty(const char *prompt,
229 char **key, size_t *key_size,
230 int timeout, int verify,
231 struct crypt_device *cd)
233 int key_size_max = DEFAULT_PASSPHRASE_SIZE_MAX;
235 char *pass = NULL, *pass_verify = NULL;
237 log_dbg("Interactive passphrase entry requested.");
239 pass = crypt_safe_alloc(key_size_max + 1);
241 log_err(cd, _("Out of memory while reading passphrase.\n"));
245 if (interactive_pass(prompt, pass, key_size_max, timeout)) {
246 log_err(cd, _("Error reading passphrase from terminal.\n"));
249 pass[key_size_max] = '\0';
252 pass_verify = crypt_safe_alloc(key_size_max);
254 log_err(cd, _("Out of memory while reading passphrase.\n"));
259 if (interactive_pass(_("Verify passphrase: "),
260 pass_verify, key_size_max, timeout)) {
261 log_err(cd, _("Error reading passphrase from terminal.\n"));
265 if (strncmp(pass, pass_verify, key_size_max)) {
266 log_err(cd, _("Passphrases do not match.\n"));
273 *key_size = strlen(pass);
276 crypt_safe_free(pass_verify);
278 crypt_safe_free(pass);
283 * A simple call to lseek(3) might not be possible for some inputs (e.g.
284 * reading from a pipe), so this function instead reads of up to BUFSIZ bytes
285 * at a time until the specified number of bytes. It returns -1 on read error
286 * or when it reaches EOF before the requested number of bytes have been
289 static int keyfile_seek(int fd, size_t bytes)
296 r = lseek(fd, bytes, SEEK_CUR);
299 if (r < 0 && errno != ESPIPE)
303 /* figure out how much to read */
304 next_read = bytes > sizeof(tmp) ? sizeof(tmp) : bytes;
306 bytes_r = read(fd, tmp, next_read);
322 return bytes == 0 ? 0 : -1;
326 * Note: --key-file=- is interpreted as a read from a binary file (stdin)
327 * key_size_max == 0 means detect maximum according to input type (tty/file)
328 * timeout and verify options only applies to tty input
330 int crypt_get_key(const char *prompt,
331 char **key, size_t *key_size,
332 size_t keyfile_offset, size_t keyfile_size_max,
333 const char *key_file, int timeout, int verify,
334 struct crypt_device *cd)
336 int fd, regular_file, read_stdin, char_read, unlimited_read = 0;
339 size_t buflen, i, file_read_size;
345 /* Passphrase read from stdin? */
346 read_stdin = (!key_file || !strcmp(key_file, "-")) ? 1 : 0;
348 if (read_stdin && isatty(STDIN_FILENO)) {
349 if (keyfile_offset) {
350 log_err(cd, _("Cannot use offset with terminal input.\n"));
353 return crypt_get_key_tty(prompt, key, key_size, timeout, verify, cd);
357 log_dbg("STDIN descriptor passphrase entry requested.");
359 log_dbg("File descriptor passphrase entry requested.");
361 /* If not requsted otherwise, we limit input to prevent memory exhaustion */
362 if (keyfile_size_max == 0) {
363 keyfile_size_max = DEFAULT_KEYFILE_SIZE_MAXKB * 1024;
367 fd = read_stdin ? STDIN_FILENO : open(key_file, O_RDONLY);
369 log_err(cd, _("Failed to open key file.\n"));
373 /* use 4k for buffer (page divisor but avoid huge pages) */
374 buflen = 4096 - sizeof(struct safe_allocation);
377 if(stat(key_file, &st) < 0) {
378 log_err(cd, _("Failed to stat key file.\n"));
381 if(S_ISREG(st.st_mode)) {
383 file_read_size = (size_t)st.st_size;
385 if (keyfile_offset > file_read_size) {
386 log_err(cd, _("Cannot seek to requested keyfile offset.\n"));
389 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 else if (file_read_size)
395 buflen = file_read_size;
399 pass = crypt_safe_alloc(buflen);
401 log_err(cd, _("Out of memory while reading passphrase.\n"));
405 /* Discard keyfile_offset bytes on input */
406 if (keyfile_offset && keyfile_seek(fd, keyfile_offset) < 0) {
407 log_err(cd, _("Cannot seek to requested keyfile offset.\n"));
411 for(i = 0; i < keyfile_size_max; i++) {
414 pass = crypt_safe_realloc(pass, buflen);
416 log_err(cd, _("Out of memory while reading passphrase.\n"));
422 char_read = read(fd, &pass[i], 1);
424 log_err(cd, _("Error reading passphrase.\n"));
428 /* Stop on newline only if not requested read from keyfile */
429 if(char_read == 0 || (!key_file && pass[i] == '\n'))
433 /* Fail if piped input dies reading nothing */
434 if(!i && !regular_file) {
435 log_dbg("Nothing read on input.");
440 /* Fail if we exceeded internal default (no specified size) */
441 if (unlimited_read && i == keyfile_size_max) {
442 log_err(cd, _("Maximum keyfile size exceeded.\n"));
446 if (!unlimited_read && i != keyfile_size_max) {
447 log_err(cd, _("Cannot read requested amount of data.\n"));
455 if(fd != STDIN_FILENO)
459 crypt_safe_free(pass);
463 ssize_t crypt_hex_to_bytes(const char *hex, char **result, int safe_alloc)
465 char buf[3] = "xx\0", *endp, *bytes;
473 bytes = safe_alloc ? crypt_safe_alloc(len) : malloc(len);
477 for (i = 0; i < len; i++) {
478 memcpy(buf, &hex[i * 2], 2);
479 bytes[i] = strtoul(buf, &endp, 16);
480 if (endp != &buf[2]) {
481 safe_alloc ? crypt_safe_free(bytes) : free(bytes);
490 * Device size string parsing, suffixes:
491 * s|S - 512 bytes sectors
492 * k |K |m |M |g |G |t |T - 1024 base
493 * kiB|KiB|miB|MiB|giB|GiB|tiB|TiB - 1024 base
494 * kb |KB |mM |MB |gB |GB |tB |TB - 1000 base
496 int crypt_string_to_size(struct crypt_device *cd, const char *s, uint64_t *size)
500 uint64_t mult_base, mult, tmp;
502 *size = strtoull(s, &endp, 10);
503 if (!isdigit(s[0]) ||
504 (errno == ERANGE && *size == ULLONG_MAX) ||
505 (errno != 0 && *size == 0))
512 /* Allow "B" and "iB" suffixes */
514 (len == 3 && (endp[1] != 'i' || endp[2] != 'B')) ||
515 (len == 2 && endp[1] != 'B'))
518 if (len == 1 || len == 3)
526 case 'S': mult = 512;
529 case 'T': mult *= mult_base;
532 case 'G': mult *= mult_base;
535 case 'M': mult *= mult_base;
538 case 'K': mult *= mult_base;
545 if ((tmp / *size) != mult) {
546 log_dbg("Device size overflow.");