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 * Note: --key-file=- is interpreted as a read from a binary file (stdin)
266 * key_size_max == 0 means detect maximum according to input type (tty/file)
267 * timeout and verify options only applies to tty input
269 int crypt_get_key(const char *prompt,
270 char **key, size_t *key_size,
271 size_t keyfile_offset, size_t keyfile_size_max,
272 const char *key_file, int timeout, int verify,
273 struct crypt_device *cd)
275 int fd, regular_file, read_stdin, char_read, unlimited_read = 0;
277 char *pass = NULL, tmp;
278 size_t buflen, i, file_read_size;
284 /* Passphrase read from stdin? */
285 read_stdin = (!key_file || !strcmp(key_file, "-")) ? 1 : 0;
287 if (read_stdin && isatty(STDIN_FILENO)) {
288 if (keyfile_offset) {
289 log_err(cd, _("Cannot use offset with terminal input.\n"));
292 return crypt_get_key_tty(prompt, key, key_size, timeout, verify, cd);
296 log_dbg("STDIN descriptor passphrase entry requested.");
298 log_dbg("File descriptor passphrase entry requested.");
300 /* If not requsted otherwise, we limit input to prevent memory exhaustion */
301 if (keyfile_size_max == 0) {
302 keyfile_size_max = DEFAULT_KEYFILE_SIZE_MAXKB * 1024;
306 fd = read_stdin ? STDIN_FILENO : open(key_file, O_RDONLY);
308 log_err(cd, _("Failed to open key file.\n"));
312 /* use 4k for buffer (page divisor but avoid huge pages) */
313 buflen = 4096 - sizeof(struct safe_allocation);
316 if(stat(key_file, &st) < 0) {
317 log_err(cd, _("Failed to stat key file.\n"));
320 if(S_ISREG(st.st_mode)) {
322 file_read_size = (size_t)st.st_size;
324 if (keyfile_offset > file_read_size) {
325 log_err(cd, _("Cannot seek to requested keyfile offset.\n"));
328 file_read_size -= keyfile_offset;
330 /* known keyfile size, alloc it in one step */
331 if (file_read_size >= keyfile_size_max)
332 buflen = keyfile_size_max;
333 else if (file_read_size)
334 buflen = file_read_size;
338 pass = crypt_safe_alloc(buflen);
340 log_err(cd, _("Out of memory while reading passphrase.\n"));
344 /* Discard keyfile_offset bytes on input */
345 for(i = 0; i < keyfile_offset; i++)
346 if (read(fd, &tmp, 1) != 1) {
347 log_err(cd, _("Cannot seek to requested keyfile offset.\n"));
351 for(i = 0; i < keyfile_size_max; i++) {
354 pass = crypt_safe_realloc(pass, buflen);
356 log_err(cd, _("Out of memory while reading passphrase.\n"));
362 char_read = read(fd, &pass[i], 1);
364 log_err(cd, _("Error reading passphrase.\n"));
368 /* Stop on newline only if not requested read from keyfile */
369 if(char_read == 0 || (!key_file && pass[i] == '\n'))
373 /* Fail if piped input dies reading nothing */
374 if(!i && !regular_file) {
375 log_dbg("Nothing read on input.");
380 /* Fail if we exceeded internal default (no specified size) */
381 if (unlimited_read && i == keyfile_size_max) {
382 log_err(cd, _("Maximum keyfile size exceeded.\n"));
386 if (!unlimited_read && i != keyfile_size_max) {
387 log_err(cd, _("Cannot read requested amount of data.\n"));
395 if(fd != STDIN_FILENO)
399 crypt_safe_free(pass);
403 ssize_t crypt_hex_to_bytes(const char *hex, char **result, int safe_alloc)
405 char buf[3] = "xx\0", *endp, *bytes;
413 bytes = safe_alloc ? crypt_safe_alloc(len) : malloc(len);
417 for (i = 0; i < len; i++) {
418 memcpy(buf, &hex[i * 2], 2);
419 bytes[i] = strtoul(buf, &endp, 16);
420 if (endp != &buf[2]) {
421 safe_alloc ? crypt_safe_free(bytes) : free(bytes);
430 * Device size string parsing, suffixes:
431 * s|S - 512 bytes sectors
432 * k |K |m |M |g |G |t |T - 1024 base
433 * kiB|KiB|miB|MiB|giB|GiB|tiB|TiB - 1024 base
434 * kb |KB |mM |MB |gB |GB |tB |TB - 1000 base
436 int crypt_string_to_size(struct crypt_device *cd, const char *s, uint64_t *size)
440 uint64_t mult_base, mult, tmp;
442 *size = strtoull(s, &endp, 10);
443 if (!isdigit(s[0]) ||
444 (errno == ERANGE && *size == ULLONG_MAX) ||
445 (errno != 0 && *size == 0))
452 /* Allow "B" and "iB" suffixes */
454 (len == 3 && (endp[1] != 'i' || endp[2] != 'B')) ||
455 (len == 2 && endp[1] != 'B'))
458 if (len == 1 || len == 3)
466 case 'S': mult = 512;
469 case 'T': mult *= mult_base;
471 case 'G': mult *= mult_base;
473 case 'M': mult *= mult_base;
475 case 'K': mult *= mult_base;
482 if ((tmp / *size) != mult) {
483 log_dbg("Device size overflow.");