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.
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * version 2 as published by the Free Software Foundation.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
28 #include <sys/types.h>
34 #include "libcryptsetup.h"
36 #include "utils_crypt.h"
38 #define log_dbg(x) crypt_log(NULL, CRYPT_LOG_DEBUG, x)
39 #define log_err(cd, x) crypt_log(cd, CRYPT_LOG_ERROR, x)
41 struct safe_allocation {
46 int crypt_parse_name_and_mode(const char *s, char *cipher, int *key_nums,
49 if (sscanf(s, "%" MAX_CIPHER_LEN_STR "[^-]-%" MAX_CIPHER_LEN_STR "s",
50 cipher, cipher_mode) == 2) {
51 if (!strcmp(cipher_mode, "plain"))
52 strncpy(cipher_mode, "cbc-plain", 10);
54 char *tmp = strchr(cipher, ':');
55 *key_nums = tmp ? atoi(++tmp) : 1;
63 /* Short version for "empty" cipher */
64 if (!strcmp(s, "null")) {
65 strncpy(cipher, "cipher_null", MAX_CIPHER_LEN);
66 strncpy(cipher_mode, "ecb", 9);
72 if (sscanf(s, "%" MAX_CIPHER_LEN_STR "[^-]", cipher) == 1) {
73 strncpy(cipher_mode, "cbc-plain", 10);
82 /* safe allocations */
83 void *crypt_safe_alloc(size_t size)
85 struct safe_allocation *alloc;
90 alloc = malloc(size + offsetof(struct safe_allocation, data));
95 memset(&alloc->data, 0, size);
97 /* coverity[leaked_storage] */
101 void crypt_safe_free(void *data)
103 struct safe_allocation *alloc;
108 alloc = (struct safe_allocation *)
109 ((char *)data - offsetof(struct safe_allocation, data));
111 memset(data, 0, alloc->size);
113 alloc->size = 0x55aa55aa;
117 void *crypt_safe_realloc(void *data, size_t size)
119 struct safe_allocation *alloc;
122 new_data = crypt_safe_alloc(size);
124 if (new_data && data) {
126 alloc = (struct safe_allocation *)
127 ((char *)data - offsetof(struct safe_allocation, data));
129 if (size > alloc->size)
132 memcpy(new_data, data, size);
135 crypt_safe_free(data);
139 /* Password reading helpers */
140 static int untimed_read(int fd, char *pass, size_t maxlen)
144 i = read(fd, pass, maxlen);
148 } else if (i == 0) { /* EOF */
155 static int timed_read(int fd, char *pass, size_t maxlen, long timeout)
166 if (select(fd+1, &fds, NULL, NULL, &t) > 0)
167 failed = untimed_read(fd, pass, maxlen);
172 static int interactive_pass(const char *prompt, char *pass, size_t maxlen,
175 struct termios orig, tmp;
177 int infd = STDIN_FILENO, outfd;
182 /* Read and write to /dev/tty if available */
183 if ((infd = outfd = open("/dev/tty", O_RDWR)) == -1) {
185 outfd = STDERR_FILENO;
188 if (tcgetattr(infd, &orig))
191 memcpy(&tmp, &orig, sizeof(tmp));
192 tmp.c_lflag &= ~ECHO;
194 if (prompt && write(outfd, prompt, strlen(prompt)) < 0)
197 tcsetattr(infd, TCSAFLUSH, &tmp);
199 failed = timed_read(infd, pass, maxlen, timeout);
201 failed = untimed_read(infd, pass, maxlen);
202 tcsetattr(infd, TCSAFLUSH, &orig);
205 if (!failed && write(outfd, "\n", 1)) {};
207 if (infd != STDIN_FILENO)
212 static int crypt_get_key_tty(const char *prompt,
213 char **key, size_t *key_size,
214 int timeout, int verify,
215 struct crypt_device *cd)
217 int key_size_max = DEFAULT_PASSPHRASE_SIZE_MAX;
219 char *pass = NULL, *pass_verify = NULL;
221 log_dbg("Interactive passphrase entry requested.");
223 pass = crypt_safe_alloc(key_size_max + 1);
225 log_err(cd, _("Out of memory while reading passphrase.\n"));
229 if (interactive_pass(prompt, pass, key_size_max, timeout)) {
230 log_err(cd, _("Error reading passphrase from terminal.\n"));
233 pass[key_size_max] = '\0';
236 pass_verify = crypt_safe_alloc(key_size_max);
238 log_err(cd, _("Out of memory while reading passphrase.\n"));
243 if (interactive_pass(_("Verify passphrase: "),
244 pass_verify, key_size_max, timeout)) {
245 log_err(cd, _("Error reading passphrase from terminal.\n"));
249 if (strncmp(pass, pass_verify, key_size_max)) {
250 log_err(cd, _("Passphrases do not match.\n"));
257 *key_size = strlen(pass);
260 crypt_safe_free(pass_verify);
262 crypt_safe_free(pass);
267 * A simple call to lseek(3) might not be possible for some inputs (e.g.
268 * reading from a pipe), so this function instead reads of up to BUFSIZ bytes
269 * at a time until the specified number of bytes. It returns -1 on read error
270 * or when it reaches EOF before the requested number of bytes have been
273 static int keyfile_seek(int fd, size_t bytes)
280 r = lseek(fd, bytes, SEEK_CUR);
283 if (r < 0 && errno != ESPIPE)
287 /* figure out how much to read */
288 next_read = bytes > sizeof(tmp) ? sizeof(tmp) : bytes;
290 bytes_r = read(fd, tmp, next_read);
306 return bytes == 0 ? 0 : -1;
310 * Note: --key-file=- is interpreted as a read from a binary file (stdin)
311 * key_size_max == 0 means detect maximum according to input type (tty/file)
312 * timeout and verify options only applies to tty input
314 int crypt_get_key(const char *prompt,
315 char **key, size_t *key_size,
316 size_t keyfile_offset, size_t keyfile_size_max,
317 const char *key_file, int timeout, int verify,
318 struct crypt_device *cd)
320 int fd, regular_file, read_stdin, char_read, unlimited_read = 0;
323 size_t buflen, i, file_read_size;
329 /* Passphrase read from stdin? */
330 read_stdin = (!key_file || !strcmp(key_file, "-")) ? 1 : 0;
332 if (read_stdin && isatty(STDIN_FILENO)) {
333 if (keyfile_offset) {
334 log_err(cd, _("Cannot use offset with terminal input.\n"));
337 return crypt_get_key_tty(prompt, key, key_size, timeout, verify, cd);
341 log_dbg("STDIN descriptor passphrase entry requested.");
343 log_dbg("File descriptor passphrase entry requested.");
345 /* If not requsted otherwise, we limit input to prevent memory exhaustion */
346 if (keyfile_size_max == 0) {
347 keyfile_size_max = DEFAULT_KEYFILE_SIZE_MAXKB * 1024;
351 fd = read_stdin ? STDIN_FILENO : open(key_file, O_RDONLY);
353 log_err(cd, _("Failed to open key file.\n"));
357 /* use 4k for buffer (page divisor but avoid huge pages) */
358 buflen = 4096 - sizeof(struct safe_allocation);
361 if(stat(key_file, &st) < 0) {
362 log_err(cd, _("Failed to stat key file.\n"));
365 if(S_ISREG(st.st_mode)) {
367 file_read_size = (size_t)st.st_size;
369 if (keyfile_offset > file_read_size) {
370 log_err(cd, _("Cannot seek to requested keyfile offset.\n"));
373 file_read_size -= keyfile_offset;
375 /* known keyfile size, alloc it in one step */
376 if (file_read_size >= keyfile_size_max)
377 buflen = keyfile_size_max;
378 else if (file_read_size)
379 buflen = file_read_size;
383 pass = crypt_safe_alloc(buflen);
385 log_err(cd, _("Out of memory while reading passphrase.\n"));
389 /* Discard keyfile_offset bytes on input */
390 if (keyfile_offset && keyfile_seek(fd, keyfile_offset) < 0) {
391 log_err(cd, _("Cannot seek to requested keyfile offset.\n"));
395 for(i = 0; i < keyfile_size_max; i++) {
398 pass = crypt_safe_realloc(pass, buflen);
400 log_err(cd, _("Out of memory while reading passphrase.\n"));
406 char_read = read(fd, &pass[i], 1);
408 log_err(cd, _("Error reading passphrase.\n"));
412 /* Stop on newline only if not requested read from keyfile */
413 if(char_read == 0 || (!key_file && pass[i] == '\n'))
417 /* Fail if piped input dies reading nothing */
418 if(!i && !regular_file) {
419 log_dbg("Nothing read on input.");
424 /* Fail if we exceeded internal default (no specified size) */
425 if (unlimited_read && i == keyfile_size_max) {
426 log_err(cd, _("Maximum keyfile size exceeded.\n"));
430 if (!unlimited_read && i != keyfile_size_max) {
431 log_err(cd, _("Cannot read requested amount of data.\n"));
439 if(fd != STDIN_FILENO)
443 crypt_safe_free(pass);
447 ssize_t crypt_hex_to_bytes(const char *hex, char **result, int safe_alloc)
449 char buf[3] = "xx\0", *endp, *bytes;
457 bytes = safe_alloc ? crypt_safe_alloc(len) : malloc(len);
461 for (i = 0; i < len; i++) {
462 memcpy(buf, &hex[i * 2], 2);
463 bytes[i] = strtoul(buf, &endp, 16);
464 if (endp != &buf[2]) {
465 safe_alloc ? crypt_safe_free(bytes) : free(bytes);
474 * Device size string parsing, suffixes:
475 * s|S - 512 bytes sectors
476 * k |K |m |M |g |G |t |T - 1024 base
477 * kiB|KiB|miB|MiB|giB|GiB|tiB|TiB - 1024 base
478 * kb |KB |mM |MB |gB |GB |tB |TB - 1000 base
480 int crypt_string_to_size(struct crypt_device *cd, const char *s, uint64_t *size)
484 uint64_t mult_base, mult, tmp;
486 *size = strtoull(s, &endp, 10);
487 if (!isdigit(s[0]) ||
488 (errno == ERANGE && *size == ULLONG_MAX) ||
489 (errno != 0 && *size == 0))
496 /* Allow "B" and "iB" suffixes */
498 (len == 3 && (endp[1] != 'i' || endp[2] != 'B')) ||
499 (len == 2 && endp[1] != 'B'))
502 if (len == 1 || len == 3)
510 case 'S': mult = 512;
513 case 'T': mult *= mult_base;
516 case 'G': mult *= mult_base;
519 case 'M': mult *= mult_base;
522 case 'K': mult *= mult_base;
529 if ((tmp / *size) != mult) {
530 log_dbg("Device size overflow.");