1 #include <signal.h>
2 #include <stdio.h>
3 #include <string.h>
4 #include <termios.h>
5 #include <unistd.h>
6 
7 #include "insecure_memzero.h"
8 #include "warnp.h"
9 
10 #include "readpass.h"
11 
12 #define MAXPASSLEN 2048
13 
14 /* Signals we need to block. */
15 static const int badsigs[] = {
16 	SIGALRM, SIGHUP, SIGINT,
17 	SIGPIPE, SIGQUIT, SIGTERM,
18 	SIGTSTP, SIGTTIN, SIGTTOU
19 };
20 #define NSIGS sizeof(badsigs)/sizeof(badsigs[0])
21 
22 /* Highest signal number we care about. */
23 #define MAX2(a, b) ((a) > (b) ? (a) : (b))
24 #define MAX4(a, b, c, d) MAX2(MAX2(a, b), MAX2(c, d))
25 #define MAX8(a, b, c, d, e, f, g, h) MAX2(MAX4(a, b, c, d), MAX4(e, f, g, h))
26 #define MAXBADSIG	MAX2(SIGALRM, MAX8(SIGHUP, SIGINT, SIGPIPE, SIGQUIT, \
27 			    SIGTERM, SIGTSTP, SIGTTIN, SIGTTOU))
28 
29 /* Has a signal of this type been received? */
30 static volatile sig_atomic_t gotsig[MAXBADSIG + 1];
31 
32 /* Signal handler. */
33 static void
handle(int sig)34 handle(int sig)
35 {
36 
37 	gotsig[sig] = 1;
38 }
39 
40 /* Restore old signals and re-issue intercepted signals. */
41 static void
resetsigs(struct sigaction savedsa[NSIGS])42 resetsigs(struct sigaction savedsa[NSIGS])
43 {
44 	size_t i;
45 
46 	/* Restore old signals. */
47 	for (i = 0; i < NSIGS; i++)
48 		sigaction(badsigs[i], &savedsa[i], NULL);
49 
50 	/* If we intercepted a signal, re-issue it. */
51 	for (i = 0; i < NSIGS; i++) {
52 		if (gotsig[badsigs[i]])
53 			raise(badsigs[i]);
54 	}
55 }
56 
57 /**
58  * readpass(passwd, prompt, confirmprompt, devtty):
59  * If ${devtty} is 0, read a password from stdin.  If ${devtty} is 1, read a
60  * password from /dev/tty if possible; if not, read from stdin.  If ${devtty}
61  * is 2, read a password from /dev/tty if possible; if not, exit with an error.
62  * If reading from a tty (either /dev/tty or stdin), disable echo and prompt
63  * the user by printing ${prompt} to stderr.  If ${confirmprompt} is non-NULL,
64  * read a second password (prompting if a terminal is being used) and repeat
65  * until the user enters the same password twice.  Return the password as a
66  * malloced NUL-terminated string via ${passwd}.
67  */
68 int
readpass(char ** passwd,const char * prompt,const char * confirmprompt,int devtty)69 readpass(char ** passwd, const char * prompt,
70     const char * confirmprompt, int devtty)
71 {
72 	FILE * readfrom;
73 	char passbuf[MAXPASSLEN];
74 	char confpassbuf[MAXPASSLEN];
75 	struct sigaction sa, savedsa[NSIGS];
76 	struct termios term, term_old;
77 	size_t i;
78 	int usingtty;
79 
80 	/* Where should we read the password from? */
81 	switch (devtty) {
82 	case 0:
83 		/* Read directly from stdin. */
84 		readfrom = stdin;
85 		break;
86 	case 1:
87 		/* Try to open /dev/tty; if that fails, read from stdin. */
88 		if ((readfrom = fopen("/dev/tty", "r")) == NULL)
89 			readfrom = stdin;
90 		break;
91 	case 2:
92 		/* Try to open /dev/tty; if that fails, bail. */
93 		if ((readfrom = fopen("/dev/tty", "r")) == NULL) {
94 			warnp("fopen(/dev/tty)");
95 			goto err1;
96 		}
97 		break;
98 	default:
99 		warn0("readpass does not support devtty=%d", devtty);
100 		goto err1;
101 	}
102 
103 	/* We have not received any signals yet. */
104 	for (i = 0; i <= MAXBADSIG; i++)
105 		gotsig[i] = 0;
106 
107 	/*
108 	 * If we receive a signal while we're reading the password, we might
109 	 * end up with echo disabled; to prevent this, we catch the signals
110 	 * here, and we'll re-send them to ourselves later after we re-enable
111 	 * terminal echo.
112 	 */
113 	sa.sa_handler = handle;
114 	sa.sa_flags = 0;
115 	sigemptyset(&sa.sa_mask);
116 	for (i = 0; i < NSIGS; i++)
117 		sigaction(badsigs[i], &sa, &savedsa[i]);
118 
119 	/* If we're reading from a terminal, try to disable echo. */
120 	if ((usingtty = isatty(fileno(readfrom))) != 0) {
121 		if (tcgetattr(fileno(readfrom), &term_old)) {
122 			warnp("Cannot read terminal settings");
123 			goto err2;
124 		}
125 		memcpy(&term, &term_old, sizeof(struct termios));
126 		term.c_lflag = (term.c_lflag & ~((tcflag_t)ECHO)) | ECHONL;
127 		if (tcsetattr(fileno(readfrom), TCSANOW, &term)) {
128 			warnp("Cannot set terminal settings");
129 			goto err2;
130 		}
131 	}
132 
133 retry:
134 	/* If we have a terminal, prompt the user to enter the password. */
135 	if (usingtty)
136 		fprintf(stderr, "%s: ", prompt);
137 
138 	/* Read the password. */
139 	if (fgets(passbuf, MAXPASSLEN, readfrom) == NULL) {
140 		if (feof(readfrom))
141 			warn0("EOF reading password");
142 		else
143 			warnp("Cannot read password");
144 		goto err3;
145 	}
146 
147 	/* Confirm the password if necessary. */
148 	if (confirmprompt != NULL) {
149 		if (usingtty)
150 			fprintf(stderr, "%s: ", confirmprompt);
151 		if (fgets(confpassbuf, MAXPASSLEN, readfrom) == NULL) {
152 			if (feof(readfrom))
153 				warn0("EOF reading password");
154 			else
155 				warnp("Cannot read password");
156 			goto err3;
157 		}
158 		if (strcmp(passbuf, confpassbuf)) {
159 			fprintf(stderr,
160 			    "Passwords mismatch, please try again\n");
161 			goto retry;
162 		}
163 	}
164 
165 	/* Terminate the string at the first "\r" or "\n" (if any). */
166 	passbuf[strcspn(passbuf, "\r\n")] = '\0';
167 
168 	/* If we changed terminal settings, reset them. */
169 	if (usingtty)
170 		tcsetattr(fileno(readfrom), TCSANOW, &term_old);
171 
172 	/* Restore old signals and re-issue intercepted signals. */
173 	resetsigs(savedsa);
174 
175 	/* Close /dev/tty if we opened it. */
176 	if (readfrom != stdin)
177 		fclose(readfrom);
178 
179 	/* Copy the password out. */
180 	if ((*passwd = strdup(passbuf)) == NULL) {
181 		warnp("Cannot allocate memory");
182 		goto err1;
183 	}
184 
185 	/*
186 	 * Zero any stored passwords.  This is not guaranteed to work, since a
187 	 * "sufficiently intelligent" compiler can optimize these out due to
188 	 * the values not being accessed again; and even if we outwitted the
189 	 * compiler, all we can do is ensure that *a* buffer is zeroed but
190 	 * not that it is the only buffer containing the data in question.
191 	 * Unfortunately the C standard does not provide any way to mark data
192 	 * as "sensitive" in order to prevent extra copies being sprinkled
193 	 * around the implementation address space.
194 	 */
195 	insecure_memzero(passbuf, MAXPASSLEN);
196 	insecure_memzero(confpassbuf, MAXPASSLEN);
197 
198 	/* Success! */
199 	return (0);
200 
201 err3:
202 	/* Reset terminal settings if necessary. */
203 	if (usingtty)
204 		tcsetattr(fileno(readfrom), TCSAFLUSH, &term_old);
205 err2:
206 	/* Close /dev/tty if we opened it. */
207 	if (readfrom != stdin)
208 		fclose(readfrom);
209 
210 	/* Restore old signals and re-issue intercepted signals. */
211 	resetsigs(savedsa);
212 err1:
213 	/* Zero any stored passwords. */
214 	insecure_memzero(passbuf, MAXPASSLEN);
215 	insecure_memzero(confpassbuf, MAXPASSLEN);
216 
217 	/* Failure! */
218 	return (-1);
219 }
220