+/*
+ * utils_crypt - cipher utilities for cryptsetup
+ *
+ * Copyright (C) 2004-2007 Clemens Fruhwirth <clemens@endorphin.org>
+ * Copyright (C) 2009-2023 Red Hat, Inc. All rights reserved.
+ * Copyright (C) 2009-2023 Milan Broz
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ */
+
#include <stdlib.h>
-#include <stddef.h>
#include <stdio.h>
#include <string.h>
-#include <errno.h>
-#include <sys/types.h>
-#include <sys/stat.h>
+#include <strings.h>
#include <unistd.h>
-#include <fcntl.h>
-#include <termios.h>
+#include <ctype.h>
+#include <errno.h>
#include "libcryptsetup.h"
-#include "nls.h"
#include "utils_crypt.h"
-struct safe_allocation {
- size_t size;
- char data[0];
-};
+#define MAX_CAPI_LEN_STR "143" /* for sscanf of crypto API string + 16 + \0 */
-int crypt_parse_name_and_mode(const char *s, char *cipher, char *cipher_mode)
+int crypt_parse_name_and_mode(const char *s, char *cipher, int *key_nums,
+ char *cipher_mode)
{
+ if (!s || !cipher || !cipher_mode)
+ return -EINVAL;
+
if (sscanf(s, "%" MAX_CIPHER_LEN_STR "[^-]-%" MAX_CIPHER_LEN_STR "s",
cipher, cipher_mode) == 2) {
+ if (!strcmp(cipher_mode, "plain"))
+ strcpy(cipher_mode, "cbc-plain");
+ if (key_nums) {
+ char *tmp = strchr(cipher, ':');
+ *key_nums = tmp ? atoi(++tmp) : 1;
+ if (!*key_nums)
+ return -EINVAL;
+ }
+
+ return 0;
+ }
+
+ /* Short version for "empty" cipher */
+ if (!strcmp(s, "null") || !strcmp(s, "cipher_null")) {
+ strcpy(cipher, "cipher_null");
+ strcpy(cipher_mode, "ecb");
+ if (key_nums)
+ *key_nums = 0;
return 0;
}
if (sscanf(s, "%" MAX_CIPHER_LEN_STR "[^-]", cipher) == 1) {
- strncpy(cipher_mode, "cbc-plain", 9);
+ strcpy(cipher_mode, "cbc-plain");
+ if (key_nums)
+ *key_nums = 1;
return 0;
}
return -EINVAL;
}
-/* safe allocations */
-void *crypt_safe_alloc(size_t size)
+int crypt_parse_hash_integrity_mode(const char *s, char *integrity)
{
- struct safe_allocation *alloc;
+ char mode[MAX_CIPHER_LEN], hash[MAX_CIPHER_LEN];
+ int r;
- if (!size)
- return NULL;
+ if (!s || !integrity || strchr(s, '(') || strchr(s, ')'))
+ return -EINVAL;
- alloc = malloc(size + offsetof(struct safe_allocation, data));
- if (!alloc)
- return NULL;
+ r = sscanf(s, "%" MAX_CIPHER_LEN_STR "[^-]-%" MAX_CIPHER_LEN_STR "s", mode, hash);
+ if (r == 2 && !isdigit(hash[0]))
+ r = snprintf(integrity, MAX_CIPHER_LEN, "%s(%s)", mode, hash);
+ else if (r == 2)
+ r = snprintf(integrity, MAX_CIPHER_LEN, "%s-%s", mode, hash);
+ else if (r == 1)
+ r = snprintf(integrity, MAX_CIPHER_LEN, "%s", mode);
+ else
+ return -EINVAL;
- alloc->size = size;
+ if (r < 0 || r >= MAX_CIPHER_LEN)
+ return -EINVAL;
- return &alloc->data;
+ return 0;
}
-void crypt_safe_free(void *data)
+int crypt_parse_integrity_mode(const char *s, char *integrity,
+ int *integrity_key_size)
{
- struct safe_allocation *alloc;
-
- if (!data)
- return;
-
- alloc = data - offsetof(struct safe_allocation, data);
-
- memset(data, 0, alloc->size);
-
- alloc->size = 0x55aa55aa;
- free(alloc);
+ int ks = 0, r = 0;
+
+ if (!s || !integrity)
+ return -EINVAL;
+
+ /* AEAD modes */
+ if (!strcmp(s, "aead") ||
+ !strcmp(s, "poly1305") ||
+ !strcmp(s, "none")) {
+ strncpy(integrity, s, MAX_CIPHER_LEN);
+ ks = 0;
+ } else if (!strcmp(s, "hmac-sha1")) {
+ strncpy(integrity, "hmac(sha1)", MAX_CIPHER_LEN);
+ ks = 20;
+ } else if (!strcmp(s, "hmac-sha256")) {
+ strncpy(integrity, "hmac(sha256)", MAX_CIPHER_LEN);
+ ks = 32;
+ } else if (!strcmp(s, "hmac-sha512")) {
+ ks = 64;
+ strncpy(integrity, "hmac(sha512)", MAX_CIPHER_LEN);
+ } else if (!strcmp(s, "cmac-aes")) {
+ ks = 16;
+ strncpy(integrity, "cmac(aes)", MAX_CIPHER_LEN);
+ } else
+ r = -EINVAL;
+
+ if (integrity_key_size)
+ *integrity_key_size = ks;
+
+ return r;
}
-void *crypt_safe_realloc(void *data, size_t size)
+int crypt_parse_pbkdf(const char *s, const char **pbkdf)
{
- void *new_data;
+ const char *tmp = NULL;
- new_data = crypt_safe_alloc(size);
+ if (!s)
+ return -EINVAL;
- if (new_data && data) {
- struct safe_allocation *alloc;
+ if (!strcasecmp(s, CRYPT_KDF_PBKDF2))
+ tmp = CRYPT_KDF_PBKDF2;
+ else if (!strcasecmp(s, CRYPT_KDF_ARGON2I))
+ tmp = CRYPT_KDF_ARGON2I;
+ else if (!strcasecmp(s, CRYPT_KDF_ARGON2ID))
+ tmp = CRYPT_KDF_ARGON2ID;
- alloc = data - offsetof(struct safe_allocation, data);
+ if (!tmp)
+ return -EINVAL;
- if (size > alloc->size)
- size = alloc->size;
+ if (pbkdf)
+ *pbkdf = tmp;
- memcpy(new_data, data, size);
- }
-
- crypt_safe_free(data);
- return new_data;
+ return 0;
}
-/* Password reading helpers */
-static int untimed_read(int fd, char *pass, size_t maxlen)
+/*
+ * Thanks Mikulas Patocka for these two char converting functions.
+ *
+ * This function is used to load cryptographic keys, so it is coded in such a
+ * way that there are no conditions or memory accesses that depend on data.
+ *
+ * Explanation of the logic:
+ * (ch - '9' - 1) is negative if ch <= '9'
+ * ('0' - 1 - ch) is negative if ch >= '0'
+ * we "and" these two values, so the result is negative if ch is in the range
+ * '0' ... '9'
+ * we are only interested in the sign, so we do a shift ">> 8"; note that right
+ * shift of a negative value is implementation-defined, so we cast the
+ * value to (unsigned) before the shift --- we have 0xffffff if ch is in
+ * the range '0' ... '9', 0 otherwise
+ * we "and" this value with (ch - '0' + 1) --- we have a value 1 ... 10 if ch is
+ * in the range '0' ... '9', 0 otherwise
+ * we add this value to -1 --- we have a value 0 ... 9 if ch is in the range '0'
+ * ... '9', -1 otherwise
+ * the next line is similar to the previous one, but we need to decode both
+ * uppercase and lowercase letters, so we use (ch & 0xdf), which converts
+ * lowercase to uppercase
+ */
+static int hex_to_bin(unsigned char ch)
{
- ssize_t i;
-
- i = read(fd, pass, maxlen);
- if (i > 0) {
- pass[i-1] = '\0';
- i = 0;
- } else if (i == 0) { /* EOF */
- *pass = 0;
- i = -1;
- }
- return i;
+ unsigned char cu = ch & 0xdf;
+ return -1 +
+ ((ch - '0' + 1) & (unsigned)((ch - '9' - 1) & ('0' - 1 - ch)) >> 8) +
+ ((cu - 'A' + 11) & (unsigned)((cu - 'F' - 1) & ('A' - 1 - cu)) >> 8);
}
-static int timed_read(int fd, char *pass, size_t maxlen, long timeout)
+static char hex2asc(unsigned char c)
{
- struct timeval t;
- fd_set fds;
- int failed = -1;
-
- FD_ZERO(&fds);
- FD_SET(fd, &fds);
- t.tv_sec = timeout;
- t.tv_usec = 0;
-
- if (select(fd+1, &fds, NULL, NULL, &t) > 0)
- failed = untimed_read(fd, pass, maxlen);
-
- return failed;
+ return c + '0' + ((unsigned)(9 - c) >> 4 & 0x27);
}
-static int interactive_pass(const char *prompt, char *pass, size_t maxlen,
- long timeout)
+ssize_t crypt_hex_to_bytes(const char *hex, char **result, int safe_alloc)
{
- struct termios orig, tmp;
- int failed = -1;
- int infd = STDIN_FILENO, outfd;
-
- if (maxlen < 1)
- goto out_err;
-
- /* Read and write to /dev/tty if available */
- if ((infd = outfd = open("/dev/tty", O_RDWR)) == -1) {
- infd = STDIN_FILENO;
- outfd = STDERR_FILENO;
+ char *bytes;
+ size_t i, len;
+ int bl, bh;
+
+ if (!hex || !result)
+ return -EINVAL;
+
+ len = strlen(hex);
+ if (len % 2)
+ return -EINVAL;
+ len /= 2;
+
+ bytes = safe_alloc ? crypt_safe_alloc(len) : malloc(len);
+ if (!bytes)
+ return -ENOMEM;
+
+ for (i = 0; i < len; i++) {
+ bh = hex_to_bin(hex[i * 2]);
+ bl = hex_to_bin(hex[i * 2 + 1]);
+ if (bh == -1 || bl == -1) {
+ safe_alloc ? crypt_safe_free(bytes) : free(bytes);
+ return -EINVAL;
+ }
+ bytes[i] = (bh << 4) | bl;
}
+ *result = bytes;
+ return i;
+}
- if (tcgetattr(infd, &orig))
- goto out_err;
-
- memcpy(&tmp, &orig, sizeof(tmp));
- tmp.c_lflag &= ~ECHO;
+char *crypt_bytes_to_hex(size_t size, const char *bytes)
+{
+ unsigned i;
+ char *hex;
- if (write(outfd, prompt, strlen(prompt)) < 0)
- goto out_err;
+ if (size && !bytes)
+ return NULL;
- tcsetattr(infd, TCSAFLUSH, &tmp);
- if (timeout)
- failed = timed_read(infd, pass, maxlen, timeout);
+ /* Alloc adds trailing \0 */
+ if (size == 0)
+ hex = crypt_safe_alloc(2);
else
- failed = untimed_read(infd, pass, maxlen);
- tcsetattr(infd, TCSAFLUSH, &orig);
+ hex = crypt_safe_alloc(size * 2 + 1);
+ if (!hex)
+ return NULL;
-out_err:
- if (!failed && write(outfd, "\n", 1));
+ if (size == 0)
+ hex[0] = '-';
+ else for (i = 0; i < size; i++) {
+ hex[i * 2] = hex2asc((const unsigned char)bytes[i] >> 4);
+ hex[i * 2 + 1] = hex2asc((const unsigned char)bytes[i] & 0xf);
+ }
- if (infd != STDIN_FILENO)
- close(infd);
- return failed;
+ return hex;
}
-/*
- * Password reading behaviour matrix of get_key
- * FIXME: rewrite this from scratch.
- * p v n h
- * -----------------+---+---+---+---
- * interactive | Y | Y | Y | Inf
- * from fd | N | N | Y | Inf
- * from binary file | N | N | N | Inf or options->key_size
- *
- * Legend: p..prompt, v..can verify, n..newline-stop, h..read horizon
- *
- * Note: --key-file=- is interpreted as a read from a binary file (stdin)
- */
-
-void crypt_get_key(char *prompt, char **key, unsigned int *passLen, int key_size,
- const char *key_file, int timeout, int verify,
- struct crypt_device *cd)
+void crypt_log_hex(struct crypt_device *cd,
+ const char *bytes, size_t size,
+ const char *sep, int numwrap, const char *wrapsep)
{
- int fd = -1;
- char *pass = NULL;
- int read_horizon;
- int regular_file = 0;
- int read_stdin;
- int r;
- struct stat st;
-
- /* Passphrase read from stdin? */
- read_stdin = (!key_file || !strcmp(key_file, "-")) ? 1 : 0;
-
- /* read_horizon applies only for real keyfile, not stdin or terminal */
- read_horizon = (key_file && !read_stdin) ? key_size : 0 /* until EOF */;
-
- /* Setup file descriptior */
- fd = read_stdin ? STDIN_FILENO : open(key_file, O_RDONLY);
- if (fd < 0) {
- crypt_log(cd, CRYPT_LOG_ERROR,
- _("Failed to open key file.\n"));
- goto out_err;
+ unsigned i;
+
+ for (i = 0; i < size; i++) {
+ if (wrapsep && numwrap && i && !(i % numwrap))
+ crypt_logf(cd, CRYPT_LOG_NORMAL, wrapsep);
+ crypt_logf(cd, CRYPT_LOG_NORMAL, "%c%c%s",
+ hex2asc((const unsigned char)bytes[i] >> 4),
+ hex2asc((const unsigned char)bytes[i] & 0xf), sep);
}
+}
- /* Interactive case */
- if(isatty(fd)) {
- int i;
+bool crypt_is_cipher_null(const char *cipher_spec)
+{
+ if (!cipher_spec)
+ return false;
+ return (strstr(cipher_spec, "cipher_null") || !strcmp(cipher_spec, "null"));
+}
- pass = crypt_safe_alloc(MAX_TTY_PASSWORD_LEN);
- if (!pass || (i = interactive_pass(prompt, pass, MAX_TTY_PASSWORD_LEN, timeout))) {
- crypt_log(cd, CRYPT_LOG_ERROR,
- _("Error reading passphrase from terminal.\n"));
- goto out_err;
- }
- if (verify) {
- char pass_verify[MAX_TTY_PASSWORD_LEN];
- i = interactive_pass(_("Verify passphrase: "), pass_verify, sizeof(pass_verify), timeout);
- if (i || strcmp(pass, pass_verify) != 0) {
- crypt_log(cd, CRYPT_LOG_ERROR,
- _("Passphrases do not match.\n"));
- goto out_err;
+int crypt_capi_to_cipher(char **org_c, char **org_i, const char *c_dm, const char *i_dm)
+{
+ char cipher[MAX_CAPI_ONE_LEN], mode[MAX_CAPI_ONE_LEN], iv[MAX_CAPI_ONE_LEN],
+ auth[MAX_CAPI_ONE_LEN], tmp[MAX_CAPI_LEN], dmcrypt_tmp[MAX_CAPI_LEN*2],
+ capi[MAX_CAPI_LEN+1];
+ size_t len;
+ int i;
+
+ if (!c_dm)
+ return -EINVAL;
+
+ /* legacy mode */
+ if (strncmp(c_dm, "capi:", 4)) {
+ if (!(*org_c = strdup(c_dm)))
+ return -ENOMEM;
+ if (i_dm) {
+ if (!(*org_i = strdup(i_dm))) {
+ free(*org_c);
+ *org_c = NULL;
+ return -ENOMEM;
}
- memset(pass_verify, 0, sizeof(pass_verify));
- }
- *passLen = strlen(pass);
- *key = pass;
+ } else
+ *org_i = NULL;
+ return 0;
+ }
+
+ /* modes with capi: prefix */
+ i = sscanf(c_dm, "capi:%" MAX_CAPI_LEN_STR "[^-]-%" MAX_CAPI_ONE_LEN_STR "s", tmp, iv);
+ if (i != 2)
+ return -EINVAL;
+
+ len = strlen(tmp);
+ if (len < 2)
+ return -EINVAL;
+
+ if (tmp[len-1] == ')')
+ tmp[len-1] = '\0';
+
+ if (sscanf(tmp, "rfc4309(%" MAX_CAPI_LEN_STR "s", capi) == 1) {
+ if (!(*org_i = strdup("aead")))
+ return -ENOMEM;
+ } else if (sscanf(tmp, "rfc7539(%" MAX_CAPI_LEN_STR "[^,],%" MAX_CAPI_ONE_LEN_STR "s", capi, auth) == 2) {
+ if (!(*org_i = strdup(auth)))
+ return -ENOMEM;
+ } else if (sscanf(tmp, "authenc(%" MAX_CAPI_ONE_LEN_STR "[^,],%" MAX_CAPI_LEN_STR "s", auth, capi) == 2) {
+ if (!(*org_i = strdup(auth)))
+ return -ENOMEM;
} else {
- /*
- * This is either a fd-input or a file, in neither case we can verify the input,
- * however we don't stop on new lines if it's a binary file.
- */
- int buflen, i;
-
- /* The following for control loop does an exhausting
- * read on the key material file, if requested with
- * key_size == 0, as it's done by LUKS. However, we
- * should warn the user, if it's a non-regular file,
- * such as /dev/random, because in this case, the loop
- * will read forever.
- */
- if(!read_stdin && read_horizon == 0) {
- if(stat(key_file, &st) < 0) {
- crypt_log(cd, CRYPT_LOG_ERROR,
- _("Failed to stat key file.\n"));
- goto out_err;
- }
- if(!S_ISREG(st.st_mode))
- crypt_log(cd, CRYPT_LOG_NORMAL,
- _("Warning: exhausting read requested, but key file"
- " is not a regular file, function might never return.\n"));
- else
- regular_file = 1;
- }
- buflen = 0;
- for(i = 0; read_horizon == 0 || i < read_horizon; i++) {
- if(i >= buflen - 1) {
- buflen += 128;
- pass = crypt_safe_realloc(pass, buflen);
- if (!pass) {
- crypt_log(cd, CRYPT_LOG_ERROR,
- _("Out of memory while reading passphrase.\n"));
- goto out_err;
- }
- }
+ if (i_dm) {
+ if (!(*org_i = strdup(i_dm)))
+ return -ENOMEM;
+ } else
+ *org_i = NULL;
+ memset(capi, 0, sizeof(capi));
+ strncpy(capi, tmp, sizeof(capi)-1);
+ }
- r = read(fd, pass + i, 1);
- if (r < 0) {
- crypt_log(cd, CRYPT_LOG_ERROR,
- _("Error reading passphrase.\n"));
- goto out_err;
- }
+ i = sscanf(capi, "%" MAX_CAPI_ONE_LEN_STR "[^(](%" MAX_CAPI_ONE_LEN_STR "[^)])", mode, cipher);
+ if (i == 2)
+ i = snprintf(dmcrypt_tmp, sizeof(dmcrypt_tmp), "%s-%s-%s", cipher, mode, iv);
+ else
+ i = snprintf(dmcrypt_tmp, sizeof(dmcrypt_tmp), "%s-%s", capi, iv);
+ if (i < 0 || (size_t)i >= sizeof(dmcrypt_tmp)) {
+ free(*org_i);
+ *org_i = NULL;
+ return -EINVAL;
+ }
- /* Stop on newline only if not requested read from keyfile */
- if(r == 0 || (!key_file && pass[i] == '\n'))
- break;
- }
- /* Fail if piped input dies reading nothing */
- if(!i && !regular_file)
- goto out_err;
- pass[i] = 0;
- *key = pass;
- *passLen = i;
+ if (!(*org_c = strdup(dmcrypt_tmp))) {
+ free(*org_i);
+ *org_i = NULL;
+ return -ENOMEM;
}
- if(fd != STDIN_FILENO)
- close(fd);
- return;
-
-out_err:
- if(fd >= 0 && fd != STDIN_FILENO)
- close(fd);
- if(pass)
- crypt_safe_free(pass);
- *key = NULL;
- *passLen = 0;
+
+ return 0;
}