Skip to content

Commit

Permalink
hsm_encryption: read from STDIN if not in a TTY
Browse files Browse the repository at this point in the history
Changelog-Added: hsmtool: allow piped passwords
  • Loading branch information
openoms committed Jun 1, 2021
1 parent 0ed7c0d commit 4c82545
Showing 1 changed file with 37 additions and 25 deletions.
62 changes: 37 additions & 25 deletions common/hsm_encryption.c
Original file line number Diff line number Diff line change
Expand Up @@ -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)
{
Expand Down Expand Up @@ -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;
}

/* 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;
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';

/* 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;
Expand Down

0 comments on commit 4c82545

Please sign in to comment.