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);
100 void crypt_safe_free(void *data)
102 struct safe_allocation *alloc;
107 alloc = (struct safe_allocation *)
108 ((char *)data - offsetof(struct safe_allocation, data));
110 memset(data, 0, alloc->size);
112 alloc->size = 0x55aa55aa;
116 void *crypt_safe_realloc(void *data, size_t size)
118 struct safe_allocation *alloc;
121 new_data = crypt_safe_alloc(size);
123 if (new_data && data) {
125 alloc = (struct safe_allocation *)
126 ((char *)data - offsetof(struct safe_allocation, data));
128 if (size > alloc->size)
131 memcpy(new_data, data, size);
134 crypt_safe_free(data);
138 /* Password reading helpers */
139 static int untimed_read(int fd, char *pass, size_t maxlen)
143 i = read(fd, pass, maxlen);
147 } else if (i == 0) { /* EOF */
154 static int timed_read(int fd, char *pass, size_t maxlen, long timeout)
165 if (select(fd+1, &fds, NULL, NULL, &t) > 0)
166 failed = untimed_read(fd, pass, maxlen);
171 static int interactive_pass(const char *prompt, char *pass, size_t maxlen,
174 struct termios orig, tmp;
176 int infd = STDIN_FILENO, outfd;
181 /* Read and write to /dev/tty if available */
182 if ((infd = outfd = open("/dev/tty", O_RDWR)) == -1) {
184 outfd = STDERR_FILENO;
187 if (tcgetattr(infd, &orig))
190 memcpy(&tmp, &orig, sizeof(tmp));
191 tmp.c_lflag &= ~ECHO;
193 if (prompt && write(outfd, prompt, strlen(prompt)) < 0)
196 tcsetattr(infd, TCSAFLUSH, &tmp);
198 failed = timed_read(infd, pass, maxlen, timeout);
200 failed = untimed_read(infd, pass, maxlen);
201 tcsetattr(infd, TCSAFLUSH, &orig);
204 if (!failed && write(outfd, "\n", 1)) {};
206 if (infd != STDIN_FILENO)
211 static int crypt_get_key_tty(const char *prompt,
212 char **key, size_t *key_size,
213 int timeout, int verify,
214 struct crypt_device *cd)
216 int key_size_max = DEFAULT_PASSPHRASE_SIZE_MAX;
218 char *pass = NULL, *pass_verify = NULL;
220 log_dbg("Interactive passphrase entry requested.");
222 pass = crypt_safe_alloc(key_size_max + 1);
224 log_err(cd, _("Out of memory while reading passphrase.\n"));
228 if (interactive_pass(prompt, pass, key_size_max, timeout)) {
229 log_err(cd, _("Error reading passphrase from terminal.\n"));
232 pass[key_size_max] = '\0';
235 pass_verify = crypt_safe_alloc(key_size_max);
237 log_err(cd, _("Out of memory while reading passphrase.\n"));
242 if (interactive_pass(_("Verify passphrase: "),
243 pass_verify, key_size_max, timeout)) {
244 log_err(cd, _("Error reading passphrase from terminal.\n"));
248 if (strncmp(pass, pass_verify, key_size_max)) {
249 log_err(cd, _("Passphrases do not match.\n"));
256 *key_size = strlen(pass);
259 crypt_safe_free(pass_verify);
261 crypt_safe_free(pass);
266 * A simple call to lseek(3) might not be possible for some inputs (e.g.
267 * reading from a pipe), so this function instead reads of up to BUFSIZ bytes
268 * at a time until the specified number of bytes. It returns -1 on read error
269 * or when it reaches EOF before the requested number of bytes have been
272 static int keyfile_seek(int fd, size_t bytes)
279 r = lseek(fd, bytes, SEEK_CUR);
282 if (r < 0 && errno != ESPIPE)
286 /* figure out how much to read */
287 next_read = bytes > sizeof(tmp) ? sizeof(tmp) : bytes;
289 bytes_r = read(fd, tmp, next_read);
305 return bytes == 0 ? 0 : -1;
309 * Note: --key-file=- is interpreted as a read from a binary file (stdin)
310 * key_size_max == 0 means detect maximum according to input type (tty/file)
311 * timeout and verify options only applies to tty input
313 int crypt_get_key(const char *prompt,
314 char **key, size_t *key_size,
315 size_t keyfile_offset, size_t keyfile_size_max,
316 const char *key_file, int timeout, int verify,
317 struct crypt_device *cd)
319 int fd, regular_file, read_stdin, char_read, unlimited_read = 0;
322 size_t buflen, i, file_read_size;
328 /* Passphrase read from stdin? */
329 read_stdin = (!key_file || !strcmp(key_file, "-")) ? 1 : 0;
331 if (read_stdin && isatty(STDIN_FILENO)) {
332 if (keyfile_offset) {
333 log_err(cd, _("Cannot use offset with terminal input.\n"));
336 return crypt_get_key_tty(prompt, key, key_size, timeout, verify, cd);
340 log_dbg("STDIN descriptor passphrase entry requested.");
342 log_dbg("File descriptor passphrase entry requested.");
344 /* If not requsted otherwise, we limit input to prevent memory exhaustion */
345 if (keyfile_size_max == 0) {
346 keyfile_size_max = DEFAULT_KEYFILE_SIZE_MAXKB * 1024;
350 fd = read_stdin ? STDIN_FILENO : open(key_file, O_RDONLY);
352 log_err(cd, _("Failed to open key file.\n"));
356 /* use 4k for buffer (page divisor but avoid huge pages) */
357 buflen = 4096 - sizeof(struct safe_allocation);
360 if(stat(key_file, &st) < 0) {
361 log_err(cd, _("Failed to stat key file.\n"));
364 if(S_ISREG(st.st_mode)) {
366 file_read_size = (size_t)st.st_size;
368 if (keyfile_offset > file_read_size) {
369 log_err(cd, _("Cannot seek to requested keyfile offset.\n"));
372 file_read_size -= keyfile_offset;
374 /* known keyfile size, alloc it in one step */
375 if (file_read_size >= keyfile_size_max)
376 buflen = keyfile_size_max;
377 else if (file_read_size)
378 buflen = file_read_size;
382 pass = crypt_safe_alloc(buflen);
384 log_err(cd, _("Out of memory while reading passphrase.\n"));
388 /* Discard keyfile_offset bytes on input */
389 if (keyfile_offset && keyfile_seek(fd, keyfile_offset) < 0) {
390 log_err(cd, _("Cannot seek to requested keyfile offset.\n"));
394 for(i = 0; i < keyfile_size_max; i++) {
397 pass = crypt_safe_realloc(pass, buflen);
399 log_err(cd, _("Out of memory while reading passphrase.\n"));
405 char_read = read(fd, &pass[i], 1);
407 log_err(cd, _("Error reading passphrase.\n"));
411 /* Stop on newline only if not requested read from keyfile */
412 if(char_read == 0 || (!key_file && pass[i] == '\n'))
416 /* Fail if piped input dies reading nothing */
417 if(!i && !regular_file) {
418 log_dbg("Nothing read on input.");
423 /* Fail if we exceeded internal default (no specified size) */
424 if (unlimited_read && i == keyfile_size_max) {
425 log_err(cd, _("Maximum keyfile size exceeded.\n"));
429 if (!unlimited_read && i != keyfile_size_max) {
430 log_err(cd, _("Cannot read requested amount of data.\n"));
438 if(fd != STDIN_FILENO)
442 crypt_safe_free(pass);
446 ssize_t crypt_hex_to_bytes(const char *hex, char **result, int safe_alloc)
448 char buf[3] = "xx\0", *endp, *bytes;
456 bytes = safe_alloc ? crypt_safe_alloc(len) : malloc(len);
460 for (i = 0; i < len; i++) {
461 memcpy(buf, &hex[i * 2], 2);
462 bytes[i] = strtoul(buf, &endp, 16);
463 if (endp != &buf[2]) {
464 safe_alloc ? crypt_safe_free(bytes) : free(bytes);
473 * Device size string parsing, suffixes:
474 * s|S - 512 bytes sectors
475 * k |K |m |M |g |G |t |T - 1024 base
476 * kiB|KiB|miB|MiB|giB|GiB|tiB|TiB - 1024 base
477 * kb |KB |mM |MB |gB |GB |tB |TB - 1000 base
479 int crypt_string_to_size(struct crypt_device *cd, const char *s, uint64_t *size)
483 uint64_t mult_base, mult, tmp;
485 *size = strtoull(s, &endp, 10);
486 if (!isdigit(s[0]) ||
487 (errno == ERANGE && *size == ULLONG_MAX) ||
488 (errno != 0 && *size == 0))
495 /* Allow "B" and "iB" suffixes */
497 (len == 3 && (endp[1] != 'i' || endp[2] != 'B')) ||
498 (len == 2 && endp[1] != 'B'))
501 if (len == 1 || len == 3)
509 case 'S': mult = 512;
512 case 'T': mult *= mult_base;
514 case 'G': mult *= mult_base;
516 case 'M': mult *= mult_base;
518 case 'K': mult *= mult_base;
525 if ((tmp / *size) != mult) {
526 log_dbg("Device size overflow.");