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));
99 void crypt_safe_free(void *data)
101 struct safe_allocation *alloc;
106 alloc = (struct safe_allocation *)
107 ((char *)data - offsetof(struct safe_allocation, data));
109 memset(data, 0, alloc->size);
111 alloc->size = 0x55aa55aa;
115 void *crypt_safe_realloc(void *data, size_t size)
117 struct safe_allocation *alloc;
120 new_data = crypt_safe_alloc(size);
122 if (new_data && data) {
124 alloc = (struct safe_allocation *)
125 ((char *)data - offsetof(struct safe_allocation, data));
127 if (size > alloc->size)
130 memcpy(new_data, data, size);
133 crypt_safe_free(data);
137 /* Password reading helpers */
138 static int untimed_read(int fd, char *pass, size_t maxlen)
142 i = read(fd, pass, maxlen);
146 } else if (i == 0) { /* EOF */
153 static int timed_read(int fd, char *pass, size_t maxlen, long timeout)
164 if (select(fd+1, &fds, NULL, NULL, &t) > 0)
165 failed = untimed_read(fd, pass, maxlen);
170 static int interactive_pass(const char *prompt, char *pass, size_t maxlen,
173 struct termios orig, tmp;
175 int infd = STDIN_FILENO, outfd;
180 /* Read and write to /dev/tty if available */
181 if ((infd = outfd = open("/dev/tty", O_RDWR)) == -1) {
183 outfd = STDERR_FILENO;
186 if (tcgetattr(infd, &orig))
189 memcpy(&tmp, &orig, sizeof(tmp));
190 tmp.c_lflag &= ~ECHO;
192 if (prompt && write(outfd, prompt, strlen(prompt)) < 0)
195 tcsetattr(infd, TCSAFLUSH, &tmp);
197 failed = timed_read(infd, pass, maxlen, timeout);
199 failed = untimed_read(infd, pass, maxlen);
200 tcsetattr(infd, TCSAFLUSH, &orig);
203 if (!failed && write(outfd, "\n", 1)) {};
205 if (infd != STDIN_FILENO)
210 static int crypt_get_key_tty(const char *prompt,
211 char **key, size_t *key_size,
212 int timeout, int verify,
213 struct crypt_device *cd)
215 int key_size_max = DEFAULT_PASSPHRASE_SIZE_MAX;
217 char *pass = NULL, *pass_verify = NULL;
219 log_dbg("Interactive passphrase entry requested.");
221 pass = crypt_safe_alloc(key_size_max + 1);
223 log_err(cd, _("Out of memory while reading passphrase.\n"));
227 if (interactive_pass(prompt, pass, key_size_max, timeout)) {
228 log_err(cd, _("Error reading passphrase from terminal.\n"));
231 pass[key_size_max] = '\0';
234 pass_verify = crypt_safe_alloc(key_size_max);
236 log_err(cd, _("Out of memory while reading passphrase.\n"));
241 if (interactive_pass(_("Verify passphrase: "),
242 pass_verify, key_size_max, timeout)) {
243 log_err(cd, _("Error reading passphrase from terminal.\n"));
247 if (strncmp(pass, pass_verify, key_size_max)) {
248 log_err(cd, _("Passphrases do not match.\n"));
255 *key_size = strlen(pass);
258 crypt_safe_free(pass_verify);
260 crypt_safe_free(pass);
265 * A simple call to lseek(3) might not be possible for some inputs (e.g.
266 * reading from a pipe), so this function instead reads of up to BUFSIZ bytes
267 * at a time until the specified number of bytes. It returns -1 on read error
268 * or when it reaches EOF before the requested number of bytes have been
271 static int keyfile_seek(int fd, size_t bytes)
278 r = lseek(fd, bytes, SEEK_CUR);
281 if (r < 0 && errno != ESPIPE)
285 /* figure out how much to read */
286 next_read = bytes > sizeof(tmp) ? sizeof(tmp) : bytes;
288 bytes_r = read(fd, tmp, next_read);
304 return bytes == 0 ? 0 : -1;
308 * Note: --key-file=- is interpreted as a read from a binary file (stdin)
309 * key_size_max == 0 means detect maximum according to input type (tty/file)
310 * timeout and verify options only applies to tty input
312 int crypt_get_key(const char *prompt,
313 char **key, size_t *key_size,
314 size_t keyfile_offset, size_t keyfile_size_max,
315 const char *key_file, int timeout, int verify,
316 struct crypt_device *cd)
318 int fd, regular_file, read_stdin, char_read, unlimited_read = 0;
321 size_t buflen, i, file_read_size;
327 /* Passphrase read from stdin? */
328 read_stdin = (!key_file || !strcmp(key_file, "-")) ? 1 : 0;
330 if (read_stdin && isatty(STDIN_FILENO)) {
331 if (keyfile_offset) {
332 log_err(cd, _("Cannot use offset with terminal input.\n"));
335 return crypt_get_key_tty(prompt, key, key_size, timeout, verify, cd);
339 log_dbg("STDIN descriptor passphrase entry requested.");
341 log_dbg("File descriptor passphrase entry requested.");
343 /* If not requsted otherwise, we limit input to prevent memory exhaustion */
344 if (keyfile_size_max == 0) {
345 keyfile_size_max = DEFAULT_KEYFILE_SIZE_MAXKB * 1024;
349 fd = read_stdin ? STDIN_FILENO : open(key_file, O_RDONLY);
351 log_err(cd, _("Failed to open key file.\n"));
355 /* use 4k for buffer (page divisor but avoid huge pages) */
356 buflen = 4096 - sizeof(struct safe_allocation);
359 if(stat(key_file, &st) < 0) {
360 log_err(cd, _("Failed to stat key file.\n"));
363 if(S_ISREG(st.st_mode)) {
365 file_read_size = (size_t)st.st_size;
367 if (keyfile_offset > file_read_size) {
368 log_err(cd, _("Cannot seek to requested keyfile offset.\n"));
371 file_read_size -= keyfile_offset;
373 /* known keyfile size, alloc it in one step */
374 if (file_read_size >= keyfile_size_max)
375 buflen = keyfile_size_max;
376 else if (file_read_size)
377 buflen = file_read_size;
381 pass = crypt_safe_alloc(buflen);
383 log_err(cd, _("Out of memory while reading passphrase.\n"));
387 /* Discard keyfile_offset bytes on input */
388 if (keyfile_offset && keyfile_seek(fd, keyfile_offset) < 0) {
389 log_err(cd, _("Cannot seek to requested keyfile offset.\n"));
393 for(i = 0; i < keyfile_size_max; i++) {
396 pass = crypt_safe_realloc(pass, buflen);
398 log_err(cd, _("Out of memory while reading passphrase.\n"));
404 char_read = read(fd, &pass[i], 1);
406 log_err(cd, _("Error reading passphrase.\n"));
410 /* Stop on newline only if not requested read from keyfile */
411 if(char_read == 0 || (!key_file && pass[i] == '\n'))
415 /* Fail if piped input dies reading nothing */
416 if(!i && !regular_file) {
417 log_dbg("Nothing read on input.");
422 /* Fail if we exceeded internal default (no specified size) */
423 if (unlimited_read && i == keyfile_size_max) {
424 log_err(cd, _("Maximum keyfile size exceeded.\n"));
428 if (!unlimited_read && i != keyfile_size_max) {
429 log_err(cd, _("Cannot read requested amount of data.\n"));
437 if(fd != STDIN_FILENO)
441 crypt_safe_free(pass);
445 ssize_t crypt_hex_to_bytes(const char *hex, char **result, int safe_alloc)
447 char buf[3] = "xx\0", *endp, *bytes;
455 bytes = safe_alloc ? crypt_safe_alloc(len) : malloc(len);
459 for (i = 0; i < len; i++) {
460 memcpy(buf, &hex[i * 2], 2);
461 bytes[i] = strtoul(buf, &endp, 16);
462 if (endp != &buf[2]) {
463 safe_alloc ? crypt_safe_free(bytes) : free(bytes);
472 * Device size string parsing, suffixes:
473 * s|S - 512 bytes sectors
474 * k |K |m |M |g |G |t |T - 1024 base
475 * kiB|KiB|miB|MiB|giB|GiB|tiB|TiB - 1024 base
476 * kb |KB |mM |MB |gB |GB |tB |TB - 1000 base
478 int crypt_string_to_size(struct crypt_device *cd, const char *s, uint64_t *size)
482 uint64_t mult_base, mult, tmp;
484 *size = strtoull(s, &endp, 10);
485 if (!isdigit(s[0]) ||
486 (errno == ERANGE && *size == ULLONG_MAX) ||
487 (errno != 0 && *size == 0))
494 /* Allow "B" and "iB" suffixes */
496 (len == 3 && (endp[1] != 'i' || endp[2] != 'B')) ||
497 (len == 2 && endp[1] != 'B'))
500 if (len == 1 || len == 3)
508 case 'S': mult = 512;
511 case 'T': mult *= mult_base;
513 case 'G': mult *= mult_base;
515 case 'M': mult *= mult_base;
517 case 'K': mult *= mult_base;
524 if ((tmp / *size) != mult) {
525 log_dbg("Device size overflow.");