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);
84 /* safe allocations */
85 void *crypt_safe_alloc(size_t size)
87 struct safe_allocation *alloc;
92 alloc = malloc(size + offsetof(struct safe_allocation, data));
97 memset(&alloc->data, 0, size);
99 /* coverity[leaked_storage] */
103 void crypt_safe_free(void *data)
105 struct safe_allocation *alloc;
110 alloc = (struct safe_allocation *)
111 ((char *)data - offsetof(struct safe_allocation, data));
113 memset(data, 0, alloc->size);
115 alloc->size = 0x55aa55aa;
119 void *crypt_safe_realloc(void *data, size_t size)
121 struct safe_allocation *alloc;
124 new_data = crypt_safe_alloc(size);
126 if (new_data && data) {
128 alloc = (struct safe_allocation *)
129 ((char *)data - offsetof(struct safe_allocation, data));
131 if (size > alloc->size)
134 memcpy(new_data, data, size);
137 crypt_safe_free(data);
141 /* Password reading helpers */
142 static int untimed_read(int fd, char *pass, size_t maxlen)
146 i = read(fd, pass, maxlen);
150 } else if (i == 0) { /* EOF */
157 static int timed_read(int fd, char *pass, size_t maxlen, long timeout)
168 if (select(fd+1, &fds, NULL, NULL, &t) > 0)
169 failed = untimed_read(fd, pass, maxlen);
174 static int interactive_pass(const char *prompt, char *pass, size_t maxlen,
177 struct termios orig, tmp;
179 int infd = STDIN_FILENO, outfd;
184 /* Read and write to /dev/tty if available */
185 if ((infd = outfd = open("/dev/tty", O_RDWR)) == -1) {
187 outfd = STDERR_FILENO;
190 if (tcgetattr(infd, &orig))
193 memcpy(&tmp, &orig, sizeof(tmp));
194 tmp.c_lflag &= ~ECHO;
196 if (prompt && write(outfd, prompt, strlen(prompt)) < 0)
199 tcsetattr(infd, TCSAFLUSH, &tmp);
201 failed = timed_read(infd, pass, maxlen, timeout);
203 failed = untimed_read(infd, pass, maxlen);
204 tcsetattr(infd, TCSAFLUSH, &orig);
207 if (!failed && write(outfd, "\n", 1)) {};
209 if (infd != STDIN_FILENO)
214 static int crypt_get_key_tty(const char *prompt,
215 char **key, size_t *key_size,
216 int timeout, int verify,
217 struct crypt_device *cd)
219 int key_size_max = DEFAULT_PASSPHRASE_SIZE_MAX;
221 char *pass = NULL, *pass_verify = NULL;
223 log_dbg("Interactive passphrase entry requested.");
225 pass = crypt_safe_alloc(key_size_max + 1);
227 log_err(cd, _("Out of memory while reading passphrase.\n"));
231 if (interactive_pass(prompt, pass, key_size_max, timeout)) {
232 log_err(cd, _("Error reading passphrase from terminal.\n"));
235 pass[key_size_max] = '\0';
238 pass_verify = crypt_safe_alloc(key_size_max);
240 log_err(cd, _("Out of memory while reading passphrase.\n"));
245 if (interactive_pass(_("Verify passphrase: "),
246 pass_verify, key_size_max, timeout)) {
247 log_err(cd, _("Error reading passphrase from terminal.\n"));
251 if (strncmp(pass, pass_verify, key_size_max)) {
252 log_err(cd, _("Passphrases do not match.\n"));
259 *key_size = strlen(pass);
262 crypt_safe_free(pass_verify);
264 crypt_safe_free(pass);
269 * A simple call to lseek(3) might not be possible for some inputs (e.g.
270 * reading from a pipe), so this function instead reads of up to BUFSIZ bytes
271 * at a time until the specified number of bytes. It returns -1 on read error
272 * or when it reaches EOF before the requested number of bytes have been
275 static int keyfile_seek(int fd, size_t bytes)
282 r = lseek(fd, bytes, SEEK_CUR);
285 if (r < 0 && errno != ESPIPE)
289 /* figure out how much to read */
290 next_read = bytes > sizeof(tmp) ? sizeof(tmp) : bytes;
292 bytes_r = read(fd, tmp, next_read);
308 return bytes == 0 ? 0 : -1;
312 * Note: --key-file=- is interpreted as a read from a binary file (stdin)
313 * key_size_max == 0 means detect maximum according to input type (tty/file)
314 * timeout and verify options only applies to tty input
316 int crypt_get_key(const char *prompt,
317 char **key, size_t *key_size,
318 size_t keyfile_offset, size_t keyfile_size_max,
319 const char *key_file, int timeout, int verify,
320 struct crypt_device *cd)
322 int fd, regular_file, read_stdin, char_read, unlimited_read = 0;
325 size_t buflen, i, file_read_size;
331 /* Passphrase read from stdin? */
332 read_stdin = (!key_file || !strcmp(key_file, "-")) ? 1 : 0;
334 if (read_stdin && isatty(STDIN_FILENO)) {
335 if (keyfile_offset) {
336 log_err(cd, _("Cannot use offset with terminal input.\n"));
339 return crypt_get_key_tty(prompt, key, key_size, timeout, verify, cd);
343 log_dbg("STDIN descriptor passphrase entry requested.");
345 log_dbg("File descriptor passphrase entry requested.");
347 /* If not requsted otherwise, we limit input to prevent memory exhaustion */
348 if (keyfile_size_max == 0) {
349 keyfile_size_max = DEFAULT_KEYFILE_SIZE_MAXKB * 1024;
353 fd = read_stdin ? STDIN_FILENO : open(key_file, O_RDONLY);
355 log_err(cd, _("Failed to open key file.\n"));
359 /* use 4k for buffer (page divisor but avoid huge pages) */
360 buflen = 4096 - sizeof(struct safe_allocation);
363 if(stat(key_file, &st) < 0) {
364 log_err(cd, _("Failed to stat key file.\n"));
367 if(S_ISREG(st.st_mode)) {
369 file_read_size = (size_t)st.st_size;
371 if (keyfile_offset > file_read_size) {
372 log_err(cd, _("Cannot seek to requested keyfile offset.\n"));
375 file_read_size -= keyfile_offset;
377 /* known keyfile size, alloc it in one step */
378 if (file_read_size >= keyfile_size_max)
379 buflen = keyfile_size_max;
380 else if (file_read_size)
381 buflen = file_read_size;
385 pass = crypt_safe_alloc(buflen);
387 log_err(cd, _("Out of memory while reading passphrase.\n"));
391 /* Discard keyfile_offset bytes on input */
392 if (keyfile_offset && keyfile_seek(fd, keyfile_offset) < 0) {
393 log_err(cd, _("Cannot seek to requested keyfile offset.\n"));
397 for(i = 0; i < keyfile_size_max; i++) {
400 pass = crypt_safe_realloc(pass, buflen);
402 log_err(cd, _("Out of memory while reading passphrase.\n"));
408 char_read = read(fd, &pass[i], 1);
410 log_err(cd, _("Error reading passphrase.\n"));
414 /* Stop on newline only if not requested read from keyfile */
415 if(char_read == 0 || (!key_file && pass[i] == '\n'))
419 /* Fail if piped input dies reading nothing */
420 if(!i && !regular_file) {
421 log_dbg("Nothing read on input.");
426 /* Fail if we exceeded internal default (no specified size) */
427 if (unlimited_read && i == keyfile_size_max) {
428 log_err(cd, _("Maximum keyfile size exceeded.\n"));
432 if (!unlimited_read && i != keyfile_size_max) {
433 log_err(cd, _("Cannot read requested amount of data.\n"));
441 if(fd != STDIN_FILENO)
445 crypt_safe_free(pass);
449 ssize_t crypt_hex_to_bytes(const char *hex, char **result, int safe_alloc)
451 char buf[3] = "xx\0", *endp, *bytes;
459 bytes = safe_alloc ? crypt_safe_alloc(len) : malloc(len);
463 for (i = 0; i < len; i++) {
464 memcpy(buf, &hex[i * 2], 2);
465 bytes[i] = strtoul(buf, &endp, 16);
466 if (endp != &buf[2]) {
467 safe_alloc ? crypt_safe_free(bytes) : free(bytes);
476 * Device size string parsing, suffixes:
477 * s|S - 512 bytes sectors
478 * k |K |m |M |g |G |t |T - 1024 base
479 * kiB|KiB|miB|MiB|giB|GiB|tiB|TiB - 1024 base
480 * kb |KB |mM |MB |gB |GB |tB |TB - 1000 base
482 int crypt_string_to_size(struct crypt_device *cd, const char *s, uint64_t *size)
486 uint64_t mult_base, mult, tmp;
488 *size = strtoull(s, &endp, 10);
489 if (!isdigit(s[0]) ||
490 (errno == ERANGE && *size == ULLONG_MAX) ||
491 (errno != 0 && *size == 0))
498 /* Allow "B" and "iB" suffixes */
500 (len == 3 && (endp[1] != 'i' || endp[2] != 'B')) ||
501 (len == 2 && endp[1] != 'B'))
504 if (len == 1 || len == 3)
512 case 'S': mult = 512;
515 case 'T': mult *= mult_base;
518 case 'G': mult *= mult_base;
521 case 'M': mult *= mult_base;
524 case 'K': mult *= mult_base;
531 if ((tmp / *size) != mult) {
532 log_dbg("Device size overflow.");