From 28e5494976f58f3d629f050334a19d952fce9d57 Mon Sep 17 00:00:00 2001 From: openoms Date: Tue, 1 Jun 2021 08:29:37 +0100 Subject: [PATCH] hsm_encryption: read from STDIN if not in a TTY --- common/hsm_encryption.c | 61 +++++++++++++++++++++++++---------------- 1 file changed, 37 insertions(+), 24 deletions(-) diff --git a/common/hsm_encryption.c b/common/hsm_encryption.c index d33c0ff56ba6..ab762f642778 100644 --- a/common/hsm_encryption.c +++ b/common/hsm_encryption.c @@ -2,6 +2,8 @@ #include #include #include +#include +#include char *hsm_secret_encryption_key(const char *pass, struct secret *key) { @@ -84,31 +86,42 @@ char *read_stdin_pass(char **reason) char *passwd = NULL; size_t passwd_size = 0; - /* Set a temporary term, same as current but with ECHO disabled. */ - if (tcgetattr(fileno(stdin), ¤t_term) != 0) { - *reason = "Could not get current terminal options."; - return NULL; + if (isatty(fileno(stdin))) { + /* Set a temporary term, same as current but with ECHO disabled. */ + if (tcgetattr(fileno(stdin), ¤t_term) != 0) { + *reason = "Could not get current terminal options."; + return NULL; + } + temp_term = current_term; + temp_term.c_lflag &= ~ECHO; + if (tcsetattr(fileno(stdin), TCSAFLUSH, &temp_term) != 0) { + *reason = "Could not disable pass echoing."; + return NULL; + } + + /* Read the password, do not take the newline character into account. */ + if (getline(&passwd, &passwd_size, stdin) < 0) { + *reason = "Could not read pass from stdin."; + return NULL; + } + if (passwd[strlen(passwd) - 1] == '\n') + passwd[strlen(passwd) - 1] = '\0'; + + /* Restore the original terminal */ + if (tcsetattr(fileno(stdin), TCSAFLUSH, ¤t_term) != 0) { + *reason = "Could not restore terminal options."; + free(passwd); + return NULL; + } } - temp_term = current_term; - temp_term.c_lflag &= ~ECHO; - if (tcsetattr(fileno(stdin), TCSAFLUSH, &temp_term) != 0) { - *reason = "Could not disable pass echoing."; - return NULL; - } - - /* Read the password, do not take the newline character into account. */ - if (getline(&passwd, &passwd_size, stdin) < 0) { - *reason = "Could not read pass from stdin."; - return NULL; - } - if (passwd[strlen(passwd) - 1] == '\n') - passwd[strlen(passwd) - 1] = '\0'; - - /* Restore the original terminal */ - if (tcsetattr(fileno(stdin), TCSAFLUSH, ¤t_term) != 0) { - *reason = "Could not restore terminal options."; - free(passwd); - return NULL; + else { + /* Read from stdin, do not take the newline character into account. */ + if (getline(&passwd, &passwd_size, stdin) < 0) { + *reason = "Could not read pass from stdin."; + return NULL; + } + if (passwd[strlen(passwd) - 1] == '\n') + passwd[strlen(passwd) - 1] = '\0'; } return passwd;