+/*
+ * utils - miscellaneous device utilities for cryptsetup
+ *
+ * Copyright (C) 2004 Jana Saout <jana@saout.de>
+ * 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 <stdio.h>
-#include <string.h>
-#include <stdlib.h>
-#include <stddef.h>
-#include <stdarg.h>
#include <errno.h>
-#include <linux/fs.h>
-#include <sys/types.h>
-#include <unistd.h>
-#include <sys/types.h>
+#include <sys/mman.h>
+#include <sys/resource.h>
#include <sys/stat.h>
-#include <sys/ioctl.h>
-#include <fcntl.h>
-#include <termios.h>
+#include <sys/utsname.h>
-#include "libcryptsetup.h"
#include "internal.h"
-
-struct safe_allocation {
- size_t size;
- char data[1];
-};
-
-static char *error=NULL;
-
-void set_error_va(const char *fmt, va_list va)
+size_t crypt_getpagesize(void)
{
-
- if(error) {
- free(error);
- error=NULL;
- }
-
- if(!fmt) return;
-
- if (vasprintf(&error, fmt, va) < 0) {
- free(error);
- error = NULL;
- }
+ long r = sysconf(_SC_PAGESIZE);
+ return r <= 0 ? DEFAULT_MEM_ALIGNMENT : (size_t)r;
}
-void set_error(const char *fmt, ...)
+unsigned crypt_cpusonline(void)
{
- va_list va;
-
- va_start(va, fmt);
- set_error_va(fmt, va);
- va_end(va);
+ long r = sysconf(_SC_NPROCESSORS_ONLN);
+ return r < 0 ? 1 : r;
}
-const char *get_error(void)
+uint64_t crypt_getphysmemory_kb(void)
{
- return error;
-}
+ long pagesize, phys_pages;
+ uint64_t phys_memory_kb;
-void *safe_alloc(size_t size)
-{
- struct safe_allocation *alloc;
-
- if (!size)
- return NULL;
-
- alloc = malloc(size + offsetof(struct safe_allocation, data));
- if (!alloc)
- return NULL;
-
- alloc->size = size;
-
- return &alloc->data;
-}
-
-void safe_free(void *data)
-{
- struct safe_allocation *alloc;
+ pagesize = sysconf(_SC_PAGESIZE);
+ phys_pages = sysconf(_SC_PHYS_PAGES);
- if (!data)
- return;
+ if (pagesize < 0 || phys_pages < 0)
+ return 0;
- alloc = data - offsetof(struct safe_allocation, data);
+ phys_memory_kb = pagesize / 1024;
+ phys_memory_kb *= phys_pages;
- memset(data, 0, alloc->size);
-
- alloc->size = 0x55aa55aa;
- free(alloc);
+ return phys_memory_kb;
}
-void *safe_realloc(void *data, size_t size)
+void crypt_process_priority(struct crypt_device *cd, int *priority, bool raise)
{
- void *new_data;
-
- new_data = safe_alloc(size);
-
- if (new_data && data) {
- struct safe_allocation *alloc;
-
- alloc = data - offsetof(struct safe_allocation, data);
-
- if (size > alloc->size)
- size = alloc->size;
+ int _priority, new_priority;
+
+ if (raise) {
+ _priority = getpriority(PRIO_PROCESS, 0);
+ if (_priority < 0)
+ _priority = 0;
+ if (priority)
+ *priority = _priority;
+
+ /*
+ * Do not bother checking CAP_SYS_NICE as device activation
+ * requires CAP_SYSADMIN later anyway.
+ */
+ if (getuid() || geteuid())
+ new_priority = 0;
+ else
+ new_priority = -18;
- memcpy(new_data, data, size);
+ if (setpriority(PRIO_PROCESS, 0, new_priority))
+ log_dbg(cd, "Cannot raise process priority.");
+ } else {
+ _priority = priority ? *priority : 0;
+ if (setpriority(PRIO_PROCESS, 0, _priority))
+ log_dbg(cd, "Cannot reset process priority.");
}
-
- safe_free(data);
- return new_data;
}
-char *safe_strdup(const char *s)
+/* Keyfile processing */
+
+/*
+ * A simple call to lseek(3) might not be possible for some inputs (e.g.
+ * reading from a pipe), so this function instead reads of up to BUFSIZ bytes
+ * at a time until the specified number of bytes. It returns -1 on read error
+ * or when it reaches EOF before the requested number of bytes have been
+ * discarded.
+ */
+static int keyfile_seek(int fd, uint64_t bytes)
{
- char *s2 = safe_alloc(strlen(s) + 1);
+ char tmp[BUFSIZ];
+ size_t next_read;
+ ssize_t bytes_r;
+ off_t r;
+
+ r = lseek(fd, bytes, SEEK_CUR);
+ if (r > 0)
+ return 0;
+ if (r < 0 && errno != ESPIPE)
+ return -1;
+
+ while (bytes > 0) {
+ /* figure out how much to read */
+ next_read = bytes > sizeof(tmp) ? sizeof(tmp) : (size_t)bytes;
+
+ bytes_r = read(fd, tmp, next_read);
+ if (bytes_r < 0) {
+ if (errno == EINTR)
+ continue;
+
+ crypt_safe_memzero(tmp, sizeof(tmp));
+ /* read error */
+ return -1;
+ }
- if (!s2)
- return NULL;
+ if (bytes_r == 0)
+ /* EOF */
+ break;
- return strcpy(s2, s);
-}
+ bytes -= bytes_r;
+ }
-static int get_alignment(int fd)
-{
- int alignment = DEFAULT_ALIGNMENT;
-
-#ifdef _PC_REC_XFER_ALIGN
- alignment = fpathconf(fd, _PC_REC_XFER_ALIGN);
- if (alignment < 0)
- alignment = DEFAULT_ALIGNMENT;
-#endif
- return alignment;
+ crypt_safe_memzero(tmp, sizeof(tmp));
+ return bytes == 0 ? 0 : -1;
}
-static void *aligned_malloc(void **base, int size, int alignment)
-{
-#ifdef HAVE_POSIX_MEMALIGN
- return posix_memalign(base, alignment, size) ? NULL : *base;
-#else
-/* Credits go to Michal's padlock patches for this alignment code */
- char *ptr;
-
- ptr = malloc(size + alignment);
- if(ptr == NULL) return NULL;
-
- *base = ptr;
- if(alignment > 1 && ((long)ptr & (alignment - 1))) {
- ptr += alignment - ((long)(ptr) & (alignment - 1));
- }
- return ptr;
-#endif
-}
-static int sector_size(int fd)
+int crypt_keyfile_device_read(struct crypt_device *cd, const char *keyfile,
+ char **key, size_t *key_size_read,
+ uint64_t keyfile_offset, size_t key_size,
+ uint32_t flags)
{
- int bsize;
- if (ioctl(fd,BLKSSZGET, &bsize) < 0)
- return -EINVAL;
- else
- return bsize;
-}
+ int fd, regular_file, char_to_read = 0, char_read = 0, unlimited_read = 0;
+ int r = -EINVAL, newline;
+ char *pass = NULL;
+ size_t buflen, i;
+ uint64_t file_read_size;
+ struct stat st;
-int sector_size_for_device(const char *device)
-{
- int fd = open(device, O_RDONLY);
- int r;
- if(fd < 0)
+ if (!key || !key_size_read)
return -EINVAL;
- r = sector_size(fd);
- close(fd);
- return r;
-}
-ssize_t write_blockwise(int fd, const void *orig_buf, size_t count)
-{
- void *hangover_buf, *hangover_buf_base = NULL;
- void *buf, *buf_base = NULL;
- int r, hangover, solid, bsize, alignment;
- ssize_t ret = -1;
+ *key = NULL;
+ *key_size_read = 0;
- if ((bsize = sector_size(fd)) < 0)
- return bsize;
+ fd = keyfile ? open(keyfile, O_RDONLY) : STDIN_FILENO;
+ if (fd < 0) {
+ log_err(cd, _("Failed to open key file."));
+ return -EINVAL;
+ }
- hangover = count % bsize;
- solid = count - hangover;
- alignment = get_alignment(fd);
+ if (isatty(fd)) {
+ log_err(cd, _("Cannot read keyfile from a terminal."));
+ goto out;
+ }
- if ((long)orig_buf & (alignment - 1)) {
- buf = aligned_malloc(&buf_base, count, alignment);
- if (!buf)
- goto out;
- memcpy(buf, orig_buf, count);
+ /* If not requested otherwise, we limit input to prevent memory exhaustion */
+ if (key_size == 0) {
+ key_size = DEFAULT_KEYFILE_SIZE_MAXKB * 1024 + 1;
+ unlimited_read = 1;
+ /* use 4k for buffer (page divisor but avoid huge pages) */
+ buflen = 4096 - 16; /* sizeof(struct safe_allocation); */
} else
- buf = (void *)orig_buf;
-
- r = write(fd, buf, solid);
- if (r < 0 || r != solid)
- goto out;
+ buflen = key_size;
- if (hangover) {
- hangover_buf = aligned_malloc(&hangover_buf_base, bsize, alignment);
- if (!hangover_buf)
+ regular_file = 0;
+ if (keyfile) {
+ if (stat(keyfile, &st) < 0) {
+ log_err(cd, _("Failed to stat key file."));
goto out;
+ }
+ if (S_ISREG(st.st_mode)) {
+ regular_file = 1;
+ file_read_size = (uint64_t)st.st_size;
- r = read(fd, hangover_buf, bsize);
- if(r < 0 || r != bsize) goto out;
-
- r = lseek(fd, -bsize, SEEK_CUR);
- if (r < 0)
- goto out;
- memcpy(hangover_buf, buf + solid, hangover);
+ if (keyfile_offset > file_read_size) {
+ log_err(cd, _("Cannot seek to requested keyfile offset."));
+ goto out;
+ }
+ file_read_size -= keyfile_offset;
- r = write(fd, hangover_buf, bsize);
- if(r < 0 || r != bsize) goto out;
- free(hangover_buf_base);
+ /* known keyfile size, alloc it in one step */
+ if (file_read_size >= (uint64_t)key_size)
+ buflen = key_size;
+ else if (file_read_size)
+ buflen = file_read_size;
+ }
}
- ret = count;
- out:
- if (buf != orig_buf)
- free(buf_base);
- return ret;
-}
-
-ssize_t read_blockwise(int fd, void *orig_buf, size_t count) {
- void *hangover_buf, *hangover_buf_base;
- void *buf, *buf_base = NULL;
- int r, hangover, solid, bsize, alignment;
- ssize_t ret = -1;
- if ((bsize = sector_size(fd)) < 0)
- return bsize;
-
- hangover = count % bsize;
- solid = count - hangover;
- alignment = get_alignment(fd);
-
- if ((long)orig_buf & (alignment - 1)) {
- buf = aligned_malloc(&buf_base, count, alignment);
- if (!buf)
- goto out;
- } else
- buf = orig_buf;
-
- r = read(fd, buf, solid);
- if(r < 0 || r != solid) {
- set_error("read failed in read_blockwise.\n");
+ pass = crypt_safe_alloc(buflen);
+ if (!pass) {
+ log_err(cd, _("Out of memory while reading passphrase."));
goto out;
}
- if (hangover) {
- hangover_buf = aligned_malloc(&hangover_buf_base, bsize, alignment);
- if (!hangover_buf)
- goto out;
- r = read(fd, hangover_buf, bsize);
- if (r < 0 || r != bsize)
- goto out;
-
- memcpy(buf + solid, hangover_buf, hangover);
- free(hangover_buf_base);
- }
- ret = count;
- out:
- if (buf != orig_buf) {
- memcpy(orig_buf, buf, count);
- free(buf_base);
+ /* Discard keyfile_offset bytes on input */
+ if (keyfile_offset && keyfile_seek(fd, keyfile_offset) < 0) {
+ log_err(cd, _("Cannot seek to requested keyfile offset."));
+ goto out;
}
- return ret;
-}
-
-/*
- * Combines llseek with blockwise write. write_blockwise can already deal with short writes
- * but we also need a function to deal with short writes at the start. But this information
- * is implicitly included in the read/write offset, which can not be set to non-aligned
- * boundaries. Hence, we combine llseek with write.
- */
-
-ssize_t write_lseek_blockwise(int fd, const char *buf, size_t count, off_t offset) {
- int bsize = sector_size(fd);
- const char *orig_buf = buf;
- char frontPadBuf[bsize];
- int frontHang = offset % bsize;
- int r;
- int innerCount = count < bsize ? count : bsize;
- if (bsize < 0)
- return bsize;
+ for (i = 0, newline = 0; i < key_size; i += char_read) {
+ if (i == buflen) {
+ buflen += 4096;
+ pass = crypt_safe_realloc(pass, buflen);
+ if (!pass) {
+ log_err(cd, _("Out of memory while reading passphrase."));
+ r = -ENOMEM;
+ goto out;
+ }
+ }
- lseek(fd, offset - frontHang, SEEK_SET);
- if(offset % bsize) {
- r = read(fd,frontPadBuf,bsize);
- if(r < 0) return -1;
+ if (flags & CRYPT_KEYFILE_STOP_EOL) {
+ /* If we should stop on newline, we must read the input
+ * one character at the time. Otherwise we might end up
+ * having read some bytes after the newline, which we
+ * promised not to do.
+ */
+ char_to_read = 1;
+ } else {
+ /* char_to_read = min(key_size - i, buflen - i) */
+ char_to_read = key_size < buflen ?
+ key_size - i : buflen - i;
+ }
+ char_read = read_buffer(fd, &pass[i], char_to_read);
+ if (char_read < 0) {
+ log_err(cd, _("Error reading passphrase."));
+ r = -EPIPE;
+ goto out;
+ }
- memcpy(frontPadBuf+frontHang, buf, innerCount);
+ if (char_read == 0)
+ break;
+ /* Stop on newline only if not requested read from keyfile */
+ if ((flags & CRYPT_KEYFILE_STOP_EOL) && pass[i] == '\n') {
+ newline = 1;
+ pass[i] = '\0';
+ break;
+ }
+ }
- lseek(fd, offset - frontHang, SEEK_SET);
- r = write(fd,frontPadBuf,bsize);
- if(r < 0) return -1;
+ /* Fail if piped input dies reading nothing */
+ if (!i && !regular_file && !newline) {
+ log_err(cd, _("Nothing to read on input."));
+ r = -EPIPE;
+ goto out;
+ }
- buf += innerCount;
- count -= innerCount;
+ /* Fail if we exceeded internal default (no specified size) */
+ if (unlimited_read && i == key_size) {
+ log_err(cd, _("Maximum keyfile size exceeded."));
+ goto out;
}
- if(count <= 0) return buf - orig_buf;
- return write_blockwise(fd, buf, count) + innerCount;
-}
+ if (!unlimited_read && i != key_size) {
+ log_err(cd, _("Cannot read requested amount of data."));
+ goto out;
+ }
-/* Password reading helpers */
+ *key = pass;
+ *key_size_read = i;
+ r = 0;
+out:
+ if (fd != STDIN_FILENO)
+ close(fd);
-static int untimed_read(int fd, char *pass, size_t maxlen)
-{
- 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;
+ if (r)
+ crypt_safe_free(pass);
+ return r;
}
-static int timed_read(int fd, char *pass, size_t maxlen, long timeout)
+int crypt_keyfile_read(struct crypt_device *cd, const char *keyfile,
+ char **key, size_t *key_size_read,
+ size_t keyfile_offset, size_t keyfile_size_max,
+ uint32_t flags)
{
- 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);
- else
- set_error("Operation timed out");
- return failed;
+ return crypt_keyfile_device_read(cd, keyfile, key, key_size_read,
+ keyfile_offset, keyfile_size_max, flags);
}
-static int interactive_pass(const char *prompt, char *pass, size_t maxlen,
- long timeout)
+int kernel_version(uint64_t *kversion)
{
- 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;
+ struct utsname uts;
+ uint16_t maj, min, patch, rel;
+ int r = -EINVAL;
+
+ if (uname(&uts) < 0)
+ return r;
+
+ if (sscanf(uts.release, "%" SCNu16 ".%" SCNu16 ".%" SCNu16 "-%" SCNu16,
+ &maj, &min, &patch, &rel) == 4)
+ r = 0;
+ else if (sscanf(uts.release, "%" SCNu16 ".%" SCNu16 ".%" SCNu16,
+ &maj, &min, &patch) == 3) {
+ rel = 0;
+ r = 0;
}
- if (tcgetattr(infd, &orig)) {
- set_error("Unable to get terminal");
- goto out_err;
- }
- memcpy(&tmp, &orig, sizeof(tmp));
- tmp.c_lflag &= ~ECHO;
-
- if (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)
- (void)write(outfd, "\n", 1);
- if (infd != STDIN_FILENO)
- close(infd);
- return failed;
-}
+ if (!r)
+ *kversion = compact_version(maj, min, patch, rel);
-/*
- * Password reading behaviour matrix of get_key
- *
- * 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)
- *
- * Returns true when more keys are available (that is when password
- * reading can be retried as for interactive terminals).
- */
+ return r;
+}
-int get_key(char *prompt, char **key, unsigned int *passLen, int key_size,
- const char *key_file, int passphrase_fd, int timeout, int how2verify)
+bool crypt_string_in(const char *str, char **list, size_t list_size)
{
- int fd;
- const int verify = how2verify & CRYPT_FLAG_VERIFY;
- const int verify_if_possible = how2verify & CRYPT_FLAG_VERIFY_IF_POSSIBLE;
- char *pass = NULL;
- int newline_stop;
- int read_horizon;
-
- if(key_file && !strcmp(key_file, "-")) {
- /* Allow binary reading from stdin */
- fd = passphrase_fd;
- newline_stop = 0;
- read_horizon = 0;
- } else if (key_file) {
- fd = open(key_file, O_RDONLY);
- if (fd < 0) {
- char buf[128];
- set_error("Error opening key file: %s",
- strerror_r(errno, buf, 128));
- goto out_err;
- }
- newline_stop = 0;
-
- /* This can either be 0 (LUKS) or the actually number
- * of key bytes (default or passed by -s) */
- read_horizon = key_size;
- } else {
- fd = passphrase_fd;
- newline_stop = 1;
- read_horizon = 0; /* Infinite, if read from terminal or fd */
- }
-
- /* Interactive case */
- if(isatty(fd)) {
- int i;
-
- pass = safe_alloc(512);
- if (!pass || (i = interactive_pass(prompt, pass, 512, timeout))) {
- set_error("Error reading passphrase");
- goto out_err;
- }
- if (verify || verify_if_possible) {
- char pass_verify[512];
- i = interactive_pass("Verify passphrase: ", pass_verify, sizeof(pass_verify), timeout);
- if (i || strcmp(pass, pass_verify) != 0) {
- set_error("Passphrases do not match");
- goto out_err;
- }
- memset(pass_verify, 0, sizeof(pass_verify));
- }
- *passLen = strlen(pass);
- *key = pass;
- } 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;
-
- if(verify) {
- set_error("Can't do passphrase verification on non-tty inputs");
- goto out_err;
- }
- /* 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(key_file && strcmp(key_file, "-") && read_horizon == 0) {
- struct stat st;
- if(stat(key_file, &st) < 0) {
- set_error("Can't stat key file");
- goto out_err;
- }
- if(!S_ISREG(st.st_mode)) {
- // set_error("Can't do exhausting read on non regular files");
- // goto out_err;
- fprintf(stderr,"Warning: exhausting read requested, but key file is not a regular file, function might never return.\n");
- }
- }
- buflen = 0;
- for(i = 0; read_horizon == 0 || i < read_horizon; i++) {
- if(i >= buflen - 1) {
- buflen += 128;
- pass = safe_realloc(pass, buflen);
- if (!pass) {
- set_error("Not enough memory while "
- "reading passphrase");
- goto out_err;
- }
- }
- if(read(fd, pass + i, 1) != 1 || (newline_stop && pass[i] == '\n'))
- break;
- }
- if(key_file)
- close(fd);
- pass[i] = 0;
- *key = pass;
- *passLen = i;
- }
+ size_t i;
- return isatty(fd); /* Return true, when password reading can be tried on interactive fds */
+ for (i = 0; *list && i < list_size; i++, list++)
+ if (!strcmp(str, *list))
+ return true;
-out_err:
- if(pass)
- safe_free(pass);
- *key = NULL;
- *passLen = 0;
- return 0;
+ return false;
}
+/* compare two strings (allows NULL values) */
+int crypt_strcmp(const char *a, const char *b)
+{
+ if (!a && !b)
+ return 0;
+ else if (!a || !b)
+ return 1;
+ return strcmp(a, b);
+}