Skip to content

Commit 1b060d6

Browse files
committed
hsm_encryption: read from STDIN if not in a TTY
Changelog-Added: hsmtool: allow piped passwords
1 parent 0ed7c0d commit 1b060d6

File tree

1 file changed

+37
-24
lines changed

1 file changed

+37
-24
lines changed

common/hsm_encryption.c

Lines changed: 37 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22
#include <common/hsm_encryption.h>
33
#include <sodium/utils.h>
44
#include <termios.h>
5+
#include <unistd.h>
6+
#include <stdio.h>
57

68
char *hsm_secret_encryption_key(const char *pass, struct secret *key)
79
{
@@ -84,31 +86,42 @@ char *read_stdin_pass(char **reason)
8486
char *passwd = NULL;
8587
size_t passwd_size = 0;
8688

87-
/* Set a temporary term, same as current but with ECHO disabled. */
88-
if (tcgetattr(fileno(stdin), &current_term) != 0) {
89-
*reason = "Could not get current terminal options.";
90-
return NULL;
89+
if (isatty(fileno(stdin))) {
90+
/* Set a temporary term, same as current but with ECHO disabled. */
91+
if (tcgetattr(fileno(stdin), &current_term) != 0) {
92+
*reason = "Could not get current terminal options.";
93+
return NULL;
94+
}
95+
temp_term = current_term;
96+
temp_term.c_lflag &= ~ECHO;
97+
if (tcsetattr(fileno(stdin), TCSAFLUSH, &temp_term) != 0) {
98+
*reason = "Could not disable pass echoing.";
99+
return NULL;
100+
}
101+
102+
/* Read the password, do not take the newline character into account. */
103+
if (getline(&passwd, &passwd_size, stdin) < 0) {
104+
*reason = "Could not read pass from stdin.";
105+
return NULL;
106+
}
107+
if (passwd[strlen(passwd) - 1] == '\n')
108+
passwd[strlen(passwd) - 1] = '\0';
109+
110+
/* Restore the original terminal */
111+
if (tcsetattr(fileno(stdin), TCSAFLUSH, &current_term) != 0) {
112+
*reason = "Could not restore terminal options.";
113+
free(passwd);
114+
return NULL;
115+
}
91116
}
92-
temp_term = current_term;
93-
temp_term.c_lflag &= ~ECHO;
94-
if (tcsetattr(fileno(stdin), TCSAFLUSH, &temp_term) != 0) {
95-
*reason = "Could not disable pass echoing.";
96-
return NULL;
97-
}
98-
99-
/* Read the password, do not take the newline character into account. */
100-
if (getline(&passwd, &passwd_size, stdin) < 0) {
101-
*reason = "Could not read pass from stdin.";
102-
return NULL;
103-
}
104-
if (passwd[strlen(passwd) - 1] == '\n')
105-
passwd[strlen(passwd) - 1] = '\0';
106-
107-
/* Restore the original terminal */
108-
if (tcsetattr(fileno(stdin), TCSAFLUSH, &current_term) != 0) {
109-
*reason = "Could not restore terminal options.";
110-
free(passwd);
111-
return NULL;
117+
else {
118+
/* Read from stdin, do not take the newline character into account. */
119+
if (getline(&passwd, &passwd_size, stdin) < 0) {
120+
*reason = "Could not read pass from stdin.";
121+
return NULL;
122+
}
123+
if (passwd[strlen(passwd) - 1] == '\n')
124+
passwd[strlen(passwd) - 1] = '\0';
112125
}
113126

114127
return passwd;

0 commit comments

Comments
 (0)