Merge branch 'upstream' into tizen
[platform/upstream/cryptsetup.git] / lib / utils_crypt.c
index 59582af..0b7dc37 100644 (file)
@@ -1,12 +1,14 @@
 /*
- * util_crypt - cipher utilities for cryptsetup
+ * utils_crypt - cipher utilities for cryptsetup
  *
- * Copyright (C) 2004-2007, Clemens Fruhwirth <clemens@endorphin.org>
- * Copyright (C) 2009-2011, Red Hat, Inc. All rights reserved.
+ * 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
- * version 2 as published by the Free Software Foundation.
+ * 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
  *
  * 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ * 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"
 
-#define log_dbg(x) crypt_log(NULL, CRYPT_LOG_DEBUG, x)
-#define log_err(cd, x) crypt_log(cd, CRYPT_LOG_ERROR, x)
-
-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, 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"))
-                       strncpy(cipher_mode, "cbc-plain", 10);
+                       strcpy(cipher_mode, "cbc-plain");
                if (key_nums) {
                        char *tmp = strchr(cipher, ':');
                        *key_nums = tmp ? atoi(++tmp) : 1;
@@ -58,8 +53,17 @@ int crypt_parse_name_and_mode(const char *s, char *cipher, int *key_nums,
                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", 10);
+               strcpy(cipher_mode, "cbc-plain");
                if (key_nums)
                        *key_nums = 1;
                return 0;
@@ -68,309 +72,276 @@ int crypt_parse_name_and_mode(const char *s, char *cipher, int *key_nums,
        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;
+       int ks = 0, r = 0;
 
-       alloc = (struct safe_allocation *)
-               ((char *)data - offsetof(struct safe_allocation, data));
+       if (!s || !integrity)
+               return -EINVAL;
 
-       memset(data, 0, alloc->size);
+       /* 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;
 
-       alloc->size = 0x55aa55aa;
-       free(alloc);
+       return r;
 }
 
-void *crypt_safe_realloc(void *data, size_t size)
+int crypt_parse_pbkdf(const char *s, const char **pbkdf)
 {
-       struct safe_allocation *alloc;
-       void *new_data;
-
-       new_data = crypt_safe_alloc(size);
+       const char *tmp = NULL;
 
-       if (new_data && data) {
+       if (!s)
+               return -EINVAL;
 
-               alloc = (struct safe_allocation *)
-                       ((char *)data - offsetof(struct safe_allocation, data));
+       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;
 
-               if (size > alloc->size)
-                       size = alloc->size;
+       if (!tmp)
+               return -EINVAL;
 
-               memcpy(new_data, data, size);
-       }
+       if (pbkdf)
+               *pbkdf = tmp;
 
-       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;
+       char *bytes;
+       size_t i, len;
+       int bl, bh;
 
-       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;
-       }
-
-       if (tcgetattr(infd, &orig))
-               goto out_err;
-
-       memcpy(&tmp, &orig, sizeof(tmp));
-       tmp.c_lflag &= ~ECHO;
-
-       if (prompt && write(outfd, prompt, strlen(prompt)) < 0)
-               goto out_err;
-
-       tcsetattr(infd, TCSAFLUSH, &tmp);
-       if (timeout)
-               failed = timed_read(infd, pass, maxlen, timeout);
-       else
-               failed = untimed_read(infd, pass, maxlen);
-       tcsetattr(infd, TCSAFLUSH, &orig);
-
-out_err:
-       if (!failed && write(outfd, "\n", 1)) {};
-
-       if (infd != STDIN_FILENO)
-               close(infd);
-       return failed;
-}
-
-static int crypt_get_key_tty(const char *prompt,
-                            char **key, size_t *key_size,
-                            int timeout, int verify,
-                            struct crypt_device *cd)
-{
-       int key_size_max = DEFAULT_PASSPHRASE_SIZE_MAX;
-       int r = -EINVAL;
-       char *pass = NULL, *pass_verify = NULL;
+       if (!hex || !result)
+               return -EINVAL;
 
-       log_dbg("Interactive passphrase entry requested.");
+       len = strlen(hex);
+       if (len % 2)
+               return -EINVAL;
+       len /= 2;
 
-       pass = crypt_safe_alloc(key_size_max + 1);
-       if (!pass) {
-               log_err(cd, _("Out of memory while reading passphrase.\n"));
+       bytes = safe_alloc ? crypt_safe_alloc(len) : malloc(len);
+       if (!bytes)
                return -ENOMEM;
-       }
-
-       if (interactive_pass(prompt, pass, key_size_max, timeout)) {
-               log_err(cd, _("Error reading passphrase from terminal.\n"));
-               goto out_err;
-       }
-       pass[key_size_max] = '\0';
-
-       if (verify) {
-               pass_verify = crypt_safe_alloc(key_size_max);
-               if (!pass_verify) {
-                       log_err(cd, _("Out of memory while reading passphrase.\n"));
-                       r = -ENOMEM;
-                       goto out_err;
-               }
 
-               if (interactive_pass(_("Verify passphrase: "),
-                   pass_verify, key_size_max, timeout)) {
-                       log_err(cd, _("Error reading passphrase from terminal.\n"));
-                       goto out_err;
-               }
-
-               if (strncmp(pass, pass_verify, key_size_max)) {
-                       log_err(cd, _("Passphrases do not match.\n"));
-                       r = -EPERM;
-                       goto out_err;
+       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;
        }
-
-       *key = pass;
-       *key_size = strlen(pass);
-       r = 0;
-out_err:
-       crypt_safe_free(pass_verify);
-       if (r)
-               crypt_safe_free(pass);
-       return r;
+       *result = bytes;
+       return i;
 }
 
-/*
- * Note: --key-file=- is interpreted as a read from a binary file (stdin)
- * key_size_max == 0 means detect maximum according to input type (tty/file)
- * timeout and verify options only applies to tty input
- */
-int crypt_get_key(const char *prompt,
-                 char **key, size_t *key_size,
-                 size_t keyfile_size_max, const char *key_file,
-                 int timeout, int verify,
-                 struct crypt_device *cd)
+char *crypt_bytes_to_hex(size_t size, const char *bytes)
 {
-       int fd, regular_file, read_stdin, char_read, unlimited_read = 0;
-       int r = -EINVAL;
-       char *pass = NULL;
-       size_t buflen, i;
-       struct stat st;
-
-       *key = NULL;
-       *key_size = 0;
+       unsigned i;
+       char *hex;
 
-       /* Passphrase read from stdin? */
-       read_stdin = (!key_file || !strcmp(key_file, "-")) ? 1 : 0;
-
-       if(read_stdin && isatty(STDIN_FILENO))
-               return crypt_get_key_tty(prompt, key, key_size, timeout, verify, cd);
+       if (size && !bytes)
+               return NULL;
 
-       if (read_stdin)
-               log_dbg("STDIN descriptor passphrase entry requested.");
+       /* Alloc adds trailing \0 */
+       if (size == 0)
+               hex = crypt_safe_alloc(2);
        else
-               log_dbg("File descriptor passphrase entry requested.");
+               hex = crypt_safe_alloc(size * 2 + 1);
+       if (!hex)
+               return NULL;
 
-       /* If not requsted otherwise, we limit input to prevent memory exhaustion */
-       if (keyfile_size_max == 0) {
-               keyfile_size_max = DEFAULT_KEYFILE_SIZE_MAXKB * 1024;
-               unlimited_read = 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);
        }
 
-       fd = read_stdin ? STDIN_FILENO : open(key_file, O_RDONLY);
-       if (fd < 0) {
-               log_err(cd, _("Failed to open key file.\n"));
-               return -EINVAL;
-       }
+       return hex;
+}
 
-       /* use 4k for buffer (page divisor but avoid huge pages) */
-       buflen = 4096 - sizeof(struct safe_allocation);
-       regular_file = 0;
-       if(!read_stdin) {
-               if(stat(key_file, &st) < 0) {
-                       log_err(cd, _("Failed to stat key file.\n"));
-                       goto out_err;
-               }
-               if(S_ISREG(st.st_mode)) {
-                       regular_file = 1;
-                       /* known keyfile size, alloc it in one step */
-                       if ((size_t)st.st_size >= keyfile_size_max)
-                               buflen = keyfile_size_max;
-                       else
-                               buflen = st.st_size;
-               }
+void crypt_log_hex(struct crypt_device *cd,
+                  const char *bytes, size_t size,
+                  const char *sep, int numwrap, const char *wrapsep)
+{
+       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);
        }
+}
 
-       pass = crypt_safe_alloc(buflen);
-       if (!pass) {
-               log_err(cd, _("Out of memory while reading passphrase.\n"));
-               goto out_err;
-       }
+bool crypt_is_cipher_null(const char *cipher_spec)
+{
+       if (!cipher_spec)
+               return false;
+       return (strstr(cipher_spec, "cipher_null") || !strcmp(cipher_spec, "null"));
+}
 
-       for(i = 0; i < keyfile_size_max; i++) {
-               if(i == buflen) {
-                       buflen += 4096;
-                       pass = crypt_safe_realloc(pass, buflen);
-                       if (!pass) {
-                               log_err(cd, _("Out of memory while reading passphrase.\n"));
-                               r = -ENOMEM;
-                               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;
 
-               char_read = read(fd, &pass[i], 1);
-               if (char_read < 0) {
-                       log_err(cd, _("Error reading passphrase.\n"));
-                       goto out_err;
-               }
+       if (!c_dm)
+               return -EINVAL;
 
-               /* Stop on newline only if not requested read from keyfile */
-               if(char_read == 0 || (!key_file && pass[i] == '\n'))
-                       break;
+       /* 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;
+                       }
+               } else
+                       *org_i = NULL;
+               return 0;
        }
 
-       /* Fail if piped input dies reading nothing */
-       if(!i && !regular_file) {
-               log_dbg("Nothing read on input.");
-               r = -EPIPE;
-               goto out_err;
-       }
+       /* 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;
 
-       /* Fail if we exceeded internal default (no specified size) */
-       if (unlimited_read && i == keyfile_size_max) {
-               log_err(cd, _("Maximum keyfile size exceeeded.\n"));
-               goto out_err;
-       }
+       len = strlen(tmp);
+       if (len < 2)
+               return -EINVAL;
 
-       if (!unlimited_read && i != keyfile_size_max) {
-               log_err(cd, _("Cannot read requested amount of data.\n"));
-               goto out_err;
+       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 {
+               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);
        }
 
-       /* Well, for historical reasons reading empty keyfile is not fail. */
-       if(!i) {
-               crypt_safe_free(pass);
-               pass = NULL;
+       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;
        }
 
-       *key = pass;
-       *key_size = i;
-       r = 0;
-out_err:
-       if(fd != STDIN_FILENO)
-               close(fd);
+       if (!(*org_c = strdup(dmcrypt_tmp))) {
+               free(*org_i);
+               *org_i = NULL;
+               return -ENOMEM;
+       }
 
-       if (r)
-               crypt_safe_free(pass);
-       return r;
+       return 0;
 }