hsm_encryption: read from STDIN if not in a TTY

Changelog-Added: hsmtool: allow piped passwords
This commit is contained in:
openoms 2021-06-01 18:38:16 +01:00 committed by Christian Decker
parent 5e1fadf799
commit b72c05fbda

View File

@ -2,6 +2,8 @@
#include <common/hsm_encryption.h>
#include <sodium/utils.h>
#include <termios.h>
#include <unistd.h>
#include <stdio.h>
char *hsm_secret_encryption_key(const char *pass, struct secret *key)
{
@ -84,31 +86,41 @@ 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), &current_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;
}
if (isatty(fileno(stdin))) {
/* Set a temporary term, same as current but with ECHO disabled. */
if (tcgetattr(fileno(stdin), &current_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';
/* 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, &current_term) != 0) {
*reason = "Could not restore terminal options.";
free(passwd);
return NULL;
/* Restore the original terminal */
if (tcsetattr(fileno(stdin), TCSAFLUSH, &current_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;