xref: /openbsd/usr.bin/ssh/readpass.c (revision da632ffb)
1 /* $OpenBSD: readpass.c,v 1.71 2024/03/30 04:27:44 djm Exp $ */
2 /*
3  * Copyright (c) 2001 Markus Friedl.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
15  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
16  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
17  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
18  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
19  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
21  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
23  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24  */
25 
26 #include <sys/types.h>
27 #include <sys/wait.h>
28 
29 #include <errno.h>
30 #include <fcntl.h>
31 #include <paths.h>
32 #include <readpassphrase.h>
33 #include <signal.h>
34 #include <stdarg.h>
35 #include <stdio.h>
36 #include <stdlib.h>
37 #include <string.h>
38 #include <unistd.h>
39 
40 #include "xmalloc.h"
41 #include "misc.h"
42 #include "pathnames.h"
43 #include "log.h"
44 #include "ssh.h"
45 #include "uidswap.h"
46 
47 static char *
ssh_askpass(char * askpass,const char * msg,const char * env_hint)48 ssh_askpass(char *askpass, const char *msg, const char *env_hint)
49 {
50 	pid_t pid, ret;
51 	size_t len;
52 	char *pass;
53 	int p[2], status;
54 	char buf[1024];
55 	void (*osigchld)(int);
56 
57 	if (fflush(stdout) != 0)
58 		error_f("fflush: %s", strerror(errno));
59 	if (askpass == NULL)
60 		fatal("internal error: askpass undefined");
61 	if (pipe(p) == -1) {
62 		error_f("pipe: %s", strerror(errno));
63 		return NULL;
64 	}
65 	osigchld = ssh_signal(SIGCHLD, SIG_DFL);
66 	if ((pid = fork()) == -1) {
67 		error_f("fork: %s", strerror(errno));
68 		ssh_signal(SIGCHLD, osigchld);
69 		return NULL;
70 	}
71 	if (pid == 0) {
72 		close(p[0]);
73 		if (dup2(p[1], STDOUT_FILENO) == -1)
74 			fatal_f("dup2: %s", strerror(errno));
75 		if (env_hint != NULL)
76 			setenv("SSH_ASKPASS_PROMPT", env_hint, 1);
77 		execlp(askpass, askpass, msg, (char *)NULL);
78 		fatal_f("exec(%s): %s", askpass, strerror(errno));
79 	}
80 	close(p[1]);
81 
82 	len = 0;
83 	do {
84 		ssize_t r = read(p[0], buf + len, sizeof(buf) - 1 - len);
85 
86 		if (r == -1 && errno == EINTR)
87 			continue;
88 		if (r <= 0)
89 			break;
90 		len += r;
91 	} while (sizeof(buf) - 1 - len > 0);
92 	buf[len] = '\0';
93 
94 	close(p[0]);
95 	while ((ret = waitpid(pid, &status, 0)) == -1)
96 		if (errno != EINTR)
97 			break;
98 	ssh_signal(SIGCHLD, osigchld);
99 	if (ret == -1 || !WIFEXITED(status) || WEXITSTATUS(status) != 0) {
100 		explicit_bzero(buf, sizeof(buf));
101 		return NULL;
102 	}
103 
104 	buf[strcspn(buf, "\r\n")] = '\0';
105 	pass = xstrdup(buf);
106 	explicit_bzero(buf, sizeof(buf));
107 	return pass;
108 }
109 
110 /* private/internal read_passphrase flags */
111 #define RP_ASK_PERMISSION	0x8000 /* pass hint to askpass for confirm UI */
112 
113 /*
114  * Reads a passphrase from /dev/tty with echo turned off/on.  Returns the
115  * passphrase (allocated with xmalloc).  Exits if EOF is encountered. If
116  * RP_ALLOW_STDIN is set, the passphrase will be read from stdin if no
117  * tty is or askpass program is available
118  */
119 char *
read_passphrase(const char * prompt,int flags)120 read_passphrase(const char *prompt, int flags)
121 {
122 	char cr = '\r', *askpass = NULL, *ret, buf[1024];
123 	int rppflags, ttyfd, use_askpass = 0, allow_askpass = 0;
124 	const char *askpass_hint = NULL;
125 	const char *s;
126 
127 	if (((s = getenv("DISPLAY")) != NULL && *s != '\0') ||
128 	    ((s = getenv("WAYLAND_DISPLAY")) != NULL && *s != '\0'))
129 		allow_askpass = 1;
130 	if ((s = getenv(SSH_ASKPASS_REQUIRE_ENV)) != NULL) {
131 		if (strcasecmp(s, "force") == 0) {
132 			use_askpass = 1;
133 			allow_askpass = 1;
134 		} else if (strcasecmp(s, "prefer") == 0)
135 			use_askpass = allow_askpass;
136 		else if (strcasecmp(s, "never") == 0)
137 			allow_askpass = 0;
138 	}
139 
140 	rppflags = (flags & RP_ECHO) ? RPP_ECHO_ON : RPP_ECHO_OFF;
141 	if (use_askpass)
142 		debug_f("requested to askpass");
143 	else if (flags & RP_USE_ASKPASS)
144 		use_askpass = 1;
145 	else if (flags & RP_ALLOW_STDIN) {
146 		if (!isatty(STDIN_FILENO)) {
147 			debug_f("stdin is not a tty");
148 			use_askpass = 1;
149 		}
150 	} else {
151 		rppflags |= RPP_REQUIRE_TTY;
152 		ttyfd = open(_PATH_TTY, O_RDWR);
153 		if (ttyfd >= 0) {
154 			/*
155 			 * If we're on a tty, ensure that show the prompt at
156 			 * the beginning of the line. This will hopefully
157 			 * clobber any password characters the user has
158 			 * optimistically typed before echo is disabled.
159 			 */
160 			(void)write(ttyfd, &cr, 1);
161 			close(ttyfd);
162 		} else {
163 			debug_f("can't open %s: %s", _PATH_TTY,
164 			    strerror(errno));
165 			use_askpass = 1;
166 		}
167 	}
168 
169 	if ((flags & RP_USE_ASKPASS) && !allow_askpass)
170 		return (flags & RP_ALLOW_EOF) ? NULL : xstrdup("");
171 
172 	if (use_askpass && allow_askpass) {
173 		if (getenv(SSH_ASKPASS_ENV))
174 			askpass = getenv(SSH_ASKPASS_ENV);
175 		else
176 			askpass = _PATH_SSH_ASKPASS_DEFAULT;
177 		if ((flags & RP_ASK_PERMISSION) != 0)
178 			askpass_hint = "confirm";
179 		if ((ret = ssh_askpass(askpass, prompt, askpass_hint)) == NULL)
180 			if (!(flags & RP_ALLOW_EOF))
181 				return xstrdup("");
182 		return ret;
183 	}
184 
185 	if (readpassphrase(prompt, buf, sizeof buf, rppflags) == NULL) {
186 		if (flags & RP_ALLOW_EOF)
187 			return NULL;
188 		return xstrdup("");
189 	}
190 
191 	ret = xstrdup(buf);
192 	explicit_bzero(buf, sizeof(buf));
193 	return ret;
194 }
195 
196 int
ask_permission(const char * fmt,...)197 ask_permission(const char *fmt, ...)
198 {
199 	va_list args;
200 	char *p, prompt[1024];
201 	int allowed = 0;
202 
203 	va_start(args, fmt);
204 	vsnprintf(prompt, sizeof(prompt), fmt, args);
205 	va_end(args);
206 
207 	p = read_passphrase(prompt,
208 	    RP_USE_ASKPASS|RP_ALLOW_EOF|RP_ASK_PERMISSION);
209 	if (p != NULL) {
210 		/*
211 		 * Accept empty responses and responses consisting
212 		 * of the word "yes" as affirmative.
213 		 */
214 		if (*p == '\0' || *p == '\n' ||
215 		    strcasecmp(p, "yes") == 0)
216 			allowed = 1;
217 		free(p);
218 	}
219 
220 	return (allowed);
221 }
222 
223 static void
writemsg(const char * msg)224 writemsg(const char *msg)
225 {
226 	(void)write(STDERR_FILENO, "\r", 1);
227 	(void)write(STDERR_FILENO, msg, strlen(msg));
228 	(void)write(STDERR_FILENO, "\r\n", 2);
229 }
230 
231 struct notifier_ctx {
232 	pid_t pid;
233 	void (*osigchld)(int);
234 };
235 
236 struct notifier_ctx *
notify_start(int force_askpass,const char * fmt,...)237 notify_start(int force_askpass, const char *fmt, ...)
238 {
239 	va_list args;
240 	char *prompt = NULL;
241 	pid_t pid = -1;
242 	void (*osigchld)(int) = NULL;
243 	const char *askpass, *s;
244 	struct notifier_ctx *ret = NULL;
245 
246 	va_start(args, fmt);
247 	xvasprintf(&prompt, fmt, args);
248 	va_end(args);
249 
250 	if (fflush(NULL) != 0)
251 		error_f("fflush: %s", strerror(errno));
252 	if (!force_askpass && isatty(STDERR_FILENO)) {
253 		writemsg(prompt);
254 		goto out_ctx;
255 	}
256 	if ((askpass = getenv("SSH_ASKPASS")) == NULL)
257 		askpass = _PATH_SSH_ASKPASS_DEFAULT;
258 	if (*askpass == '\0') {
259 		debug3_f("cannot notify: no askpass");
260 		goto out;
261 	}
262 	if (getenv("DISPLAY") == NULL && getenv("WAYLAND_DISPLAY") == NULL &&
263 	    ((s = getenv(SSH_ASKPASS_REQUIRE_ENV)) == NULL ||
264 	    strcmp(s, "force") != 0)) {
265 		debug3_f("cannot notify: no display");
266 		goto out;
267 	}
268 	osigchld = ssh_signal(SIGCHLD, SIG_DFL);
269 	if ((pid = fork()) == -1) {
270 		error_f("fork: %s", strerror(errno));
271 		ssh_signal(SIGCHLD, osigchld);
272 		free(prompt);
273 		return NULL;
274 	}
275 	if (pid == 0) {
276 		if (stdfd_devnull(1, 1, 0) == -1)
277 			fatal_f("stdfd_devnull failed");
278 		closefrom(STDERR_FILENO + 1);
279 		setenv("SSH_ASKPASS_PROMPT", "none", 1); /* hint to UI */
280 		execlp(askpass, askpass, prompt, (char *)NULL);
281 		error_f("exec(%s): %s", askpass, strerror(errno));
282 		_exit(1);
283 		/* NOTREACHED */
284 	}
285  out_ctx:
286 	if ((ret = calloc(1, sizeof(*ret))) == NULL) {
287 		if (pid != -1)
288 			kill(pid, SIGTERM);
289 		fatal_f("calloc failed");
290 	}
291 	ret->pid = pid;
292 	ret->osigchld = osigchld;
293  out:
294 	free(prompt);
295 	return ret;
296 }
297 
298 void
notify_complete(struct notifier_ctx * ctx,const char * fmt,...)299 notify_complete(struct notifier_ctx *ctx, const char *fmt, ...)
300 {
301 	int ret;
302 	char *msg = NULL;
303 	va_list args;
304 
305 	if (ctx != NULL && fmt != NULL && ctx->pid == -1) {
306 		/*
307 		 * notify_start wrote to stderr, so send conclusion message
308 		 * there too
309 		*/
310 		va_start(args, fmt);
311 		xvasprintf(&msg, fmt, args);
312 		va_end(args);
313 		writemsg(msg);
314 		free(msg);
315 	}
316 
317 	if (ctx == NULL || ctx->pid <= 0) {
318 		free(ctx);
319 		return;
320 	}
321 	kill(ctx->pid, SIGTERM);
322 	while ((ret = waitpid(ctx->pid, NULL, 0)) == -1) {
323 		if (errno != EINTR)
324 			break;
325 	}
326 	if (ret == -1)
327 		fatal_f("waitpid: %s", strerror(errno));
328 	ssh_signal(SIGCHLD, ctx->osigchld);
329 	free(ctx);
330 }
331