diff --git a/lib/utils.c b/lib/utils.c index 6eb37fcc..7a6df4c2 100644 --- a/lib/utils.c +++ b/lib/utils.c @@ -190,6 +190,7 @@ int crypt_keyfile_device_read(struct crypt_device *cd, const char *keyfile, size_t buflen, i; uint64_t file_read_size; struct stat st; + bool close_fd = false; if (!key || !key_size_read) return -EINVAL; @@ -197,11 +198,15 @@ int crypt_keyfile_device_read(struct crypt_device *cd, const char *keyfile, *key = NULL; *key_size_read = 0; - fd = keyfile ? open(keyfile, O_RDONLY) : STDIN_FILENO; - if (fd < 0) { - log_err(cd, _("Failed to open key file.")); - return -EINVAL; - } + if (keyfile) { + fd = open(keyfile, O_RDONLY); + if (fd < 0) { + log_err(cd, _("Failed to open key file.")); + return -EINVAL; + } + close_fd = true; + } else + fd = STDIN_FILENO; if (isatty(fd)) { log_err(cd, _("Cannot read keyfile from a terminal.")); @@ -315,7 +320,7 @@ int crypt_keyfile_device_read(struct crypt_device *cd, const char *keyfile, *key_size_read = i; r = 0; out: - if (fd != STDIN_FILENO) + if (close_fd) close(fd); if (r) diff --git a/src/utils_luks.c b/src/utils_luks.c index c76529e9..d6d7894c 100644 --- a/src/utils_luks.c +++ b/src/utils_luks.c @@ -158,6 +158,7 @@ int tools_read_json_file(const char *file, char **json, size_t *json_size, bool ssize_t ret; int fd, block, r; void *buf = NULL; + bool close_fd = false; block = tools_signals_blocked(); if (block) @@ -174,6 +175,7 @@ int tools_read_json_file(const char *file, char **json, size_t *json_size, bool r = -EINVAL; goto out; } + close_fd = true; } buf = malloc(LUKS2_MAX_MDA_SIZE); @@ -205,7 +207,7 @@ int tools_read_json_file(const char *file, char **json, size_t *json_size, bool out: if (block && !quit) set_int_block(1); - if (fd >= 0 && fd != STDIN_FILENO) + if (close_fd) close(fd); if (r && buf) { memset(buf, 0, LUKS2_MAX_MDA_SIZE); diff --git a/src/utils_password.c b/src/utils_password.c index a0eff41b..1afd302a 100644 --- a/src/utils_password.c +++ b/src/utils_password.c @@ -160,6 +160,7 @@ static int interactive_pass(const char *prompt, char *pass, size_t maxlen, int failed = -1; int infd, outfd; size_t realsize = 0; + bool close_fd = false; if (maxlen < 1) return failed; @@ -169,8 +170,10 @@ static int interactive_pass(const char *prompt, char *pass, size_t maxlen, if (infd == -1) { infd = STDIN_FILENO; outfd = STDERR_FILENO; - } else + } else { outfd = infd; + close_fd = true; + } if (tcgetattr(infd, &orig)) goto out; @@ -193,7 +196,7 @@ out: if (realsize == maxlen) log_dbg("Read stopped at maximal interactive input length, passphrase can be trimmed."); - if (infd != STDIN_FILENO) + if (close_fd) close(infd); return failed; }