1/* $OpenBSD: readpass.c,v 1.70 2022/05/27 04:27:49 dtucker 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 "includes.h"
27
28#include <sys/types.h>
29#include <sys/wait.h>
30
31#include <errno.h>
32#include <fcntl.h>
33#ifdef HAVE_PATHS_H
34# include <paths.h>
35#endif
36#include <signal.h>
37#include <stdarg.h>
38#include <stdio.h>
39#include <stdlib.h>
40#include <string.h>
41#include <unistd.h>
42
43#include "xmalloc.h"
44#include "misc.h"
45#include "pathnames.h"
46#include "log.h"
47#include "ssh.h"
48#include "uidswap.h"
49
50static char *
51ssh_askpass(char *askpass, const char *msg, const char *env_hint)
52{
53	pid_t pid, ret;
54	size_t len;
55	char *pass;
56	int p[2], status;
57	char buf[1024];
58	void (*osigchld)(int);
59
60	if (fflush(stdout) != 0)
61		error_f("fflush: %s", strerror(errno));
62	if (askpass == NULL)
63		fatal("internal error: askpass undefined");
64	if (pipe(p) == -1) {
65		error_f("pipe: %s", strerror(errno));
66		return NULL;
67	}
68	osigchld = ssh_signal(SIGCHLD, SIG_DFL);
69	if ((pid = fork()) == -1) {
70		error_f("fork: %s", strerror(errno));
71		ssh_signal(SIGCHLD, osigchld);
72		return NULL;
73	}
74	if (pid == 0) {
75		close(p[0]);
76		if (dup2(p[1], STDOUT_FILENO) == -1)
77			fatal_f("dup2: %s", strerror(errno));
78		if (env_hint != NULL)
79			setenv("SSH_ASKPASS_PROMPT", env_hint, 1);
80		execlp(askpass, askpass, msg, (char *)NULL);
81		fatal_f("exec(%s): %s", askpass, strerror(errno));
82	}
83	close(p[1]);
84
85	len = 0;
86	do {
87		ssize_t r = read(p[0], buf + len, sizeof(buf) - 1 - len);
88
89		if (r == -1 && errno == EINTR)
90			continue;
91		if (r <= 0)
92			break;
93		len += r;
94	} while (sizeof(buf) - 1 - len > 0);
95	buf[len] = '\0';
96
97	close(p[0]);
98	while ((ret = waitpid(pid, &status, 0)) == -1)
99		if (errno != EINTR)
100			break;
101	ssh_signal(SIGCHLD, osigchld);
102	if (ret == -1 || !WIFEXITED(status) || WEXITSTATUS(status) != 0) {
103		explicit_bzero(buf, sizeof(buf));
104		return NULL;
105	}
106
107	buf[strcspn(buf, "\r\n")] = '\0';
108	pass = xstrdup(buf);
109	explicit_bzero(buf, sizeof(buf));
110	return pass;
111}
112
113/* private/internal read_passphrase flags */
114#define RP_ASK_PERMISSION	0x8000 /* pass hint to askpass for confirm UI */
115
116/*
117 * Reads a passphrase from /dev/tty with echo turned off/on.  Returns the
118 * passphrase (allocated with xmalloc).  Exits if EOF is encountered. If
119 * RP_ALLOW_STDIN is set, the passphrase will be read from stdin if no
120 * tty is or askpass program is available
121 */
122char *
123read_passphrase(const char *prompt, int flags)
124{
125	char cr = '\r', *askpass = NULL, *ret, buf[1024];
126	int rppflags, ttyfd, use_askpass = 0, allow_askpass = 0;
127	const char *askpass_hint = NULL;
128	const char *s;
129
130	if ((s = getenv("DISPLAY")) != NULL)
131		allow_askpass = *s != '\0';
132	if ((s = getenv(SSH_ASKPASS_REQUIRE_ENV)) != NULL) {
133		if (strcasecmp(s, "force") == 0) {
134			use_askpass = 1;
135			allow_askpass = 1;
136		} else if (strcasecmp(s, "prefer") == 0)
137			use_askpass = allow_askpass;
138		else if (strcasecmp(s, "never") == 0)
139			allow_askpass = 0;
140	}
141
142	rppflags = (flags & RP_ECHO) ? RPP_ECHO_ON : RPP_ECHO_OFF;
143	if (use_askpass)
144		debug_f("requested to askpass");
145	else if (flags & RP_USE_ASKPASS)
146		use_askpass = 1;
147	else if (flags & RP_ALLOW_STDIN) {
148		if (!isatty(STDIN_FILENO)) {
149			debug_f("stdin is not a tty");
150			use_askpass = 1;
151		}
152	} else {
153		rppflags |= RPP_REQUIRE_TTY;
154		ttyfd = open(_PATH_TTY, O_RDWR);
155		if (ttyfd >= 0) {
156			/*
157			 * If we're on a tty, ensure that show the prompt at
158			 * the beginning of the line. This will hopefully
159			 * clobber any password characters the user has
160			 * optimistically typed before echo is disabled.
161			 */
162			(void)write(ttyfd, &cr, 1);
163			close(ttyfd);
164		} else {
165			debug_f("can't open %s: %s", _PATH_TTY,
166			    strerror(errno));
167			use_askpass = 1;
168		}
169	}
170
171	if ((flags & RP_USE_ASKPASS) && !allow_askpass)
172		return (flags & RP_ALLOW_EOF) ? NULL : xstrdup("");
173
174	if (use_askpass && allow_askpass) {
175		if (getenv(SSH_ASKPASS_ENV))
176			askpass = getenv(SSH_ASKPASS_ENV);
177		else
178			askpass = _PATH_SSH_ASKPASS_DEFAULT;
179		if ((flags & RP_ASK_PERMISSION) != 0)
180			askpass_hint = "confirm";
181		if ((ret = ssh_askpass(askpass, prompt, askpass_hint)) == NULL)
182			if (!(flags & RP_ALLOW_EOF))
183				return xstrdup("");
184		return ret;
185	}
186
187	if (readpassphrase(prompt, buf, sizeof buf, rppflags) == NULL) {
188		if (flags & RP_ALLOW_EOF)
189			return NULL;
190		return xstrdup("");
191	}
192
193	ret = xstrdup(buf);
194	explicit_bzero(buf, sizeof(buf));
195	return ret;
196}
197
198int
199ask_permission(const char *fmt, ...)
200{
201	va_list args;
202	char *p, prompt[1024];
203	int allowed = 0;
204
205	va_start(args, fmt);
206	vsnprintf(prompt, sizeof(prompt), fmt, args);
207	va_end(args);
208
209	p = read_passphrase(prompt,
210	    RP_USE_ASKPASS|RP_ALLOW_EOF|RP_ASK_PERMISSION);
211	if (p != NULL) {
212		/*
213		 * Accept empty responses and responses consisting
214		 * of the word "yes" as affirmative.
215		 */
216		if (*p == '\0' || *p == '\n' ||
217		    strcasecmp(p, "yes") == 0)
218			allowed = 1;
219		free(p);
220	}
221
222	return (allowed);
223}
224
225static void
226writemsg(const char *msg)
227{
228	(void)write(STDERR_FILENO, "\r", 1);
229	(void)write(STDERR_FILENO, msg, strlen(msg));
230	(void)write(STDERR_FILENO, "\r\n", 2);
231}
232
233struct notifier_ctx {
234	pid_t pid;
235	void (*osigchld)(int);
236};
237
238struct notifier_ctx *
239notify_start(int force_askpass, const char *fmt, ...)
240{
241	va_list args;
242	char *prompt = NULL;
243	pid_t pid = -1;
244	void (*osigchld)(int) = NULL;
245	const char *askpass, *s;
246	struct notifier_ctx *ret = NULL;
247
248	va_start(args, fmt);
249	xvasprintf(&prompt, fmt, args);
250	va_end(args);
251
252	if (fflush(NULL) != 0)
253		error_f("fflush: %s", strerror(errno));
254	if (!force_askpass && isatty(STDERR_FILENO)) {
255		writemsg(prompt);
256		goto out_ctx;
257	}
258	if ((askpass = getenv("SSH_ASKPASS")) == NULL)
259		askpass = _PATH_SSH_ASKPASS_DEFAULT;
260	if (*askpass == '\0') {
261		debug3_f("cannot notify: no askpass");
262		goto out;
263	}
264	if (getenv("DISPLAY") == NULL &&
265	    ((s = getenv(SSH_ASKPASS_REQUIRE_ENV)) == NULL ||
266	    strcmp(s, "force") != 0)) {
267		debug3_f("cannot notify: no display");
268		goto out;
269	}
270	osigchld = ssh_signal(SIGCHLD, SIG_DFL);
271	if ((pid = fork()) == -1) {
272		error_f("fork: %s", strerror(errno));
273		ssh_signal(SIGCHLD, osigchld);
274		free(prompt);
275		return NULL;
276	}
277	if (pid == 0) {
278		if (stdfd_devnull(1, 1, 0) == -1)
279			fatal_f("stdfd_devnull failed");
280		closefrom(STDERR_FILENO + 1);
281		setenv("SSH_ASKPASS_PROMPT", "none", 1); /* hint to UI */
282		execlp(askpass, askpass, prompt, (char *)NULL);
283		error_f("exec(%s): %s", askpass, strerror(errno));
284		_exit(1);
285		/* NOTREACHED */
286	}
287 out_ctx:
288	if ((ret = calloc(1, sizeof(*ret))) == NULL) {
289		if (pid != -1)
290			kill(pid, SIGTERM);
291		fatal_f("calloc failed");
292	}
293	ret->pid = pid;
294	ret->osigchld = osigchld;
295 out:
296	free(prompt);
297	return ret;
298}
299
300void
301notify_complete(struct notifier_ctx *ctx, const char *fmt, ...)
302{
303	int ret;
304	char *msg = NULL;
305	va_list args;
306
307	if (ctx != NULL && fmt != NULL && ctx->pid == -1) {
308		/*
309		 * notify_start wrote to stderr, so send conclusion message
310		 * there too
311		*/
312		va_start(args, fmt);
313		xvasprintf(&msg, fmt, args);
314		va_end(args);
315		writemsg(msg);
316		free(msg);
317	}
318
319	if (ctx == NULL || ctx->pid <= 0) {
320		free(ctx);
321		return;
322	}
323	kill(ctx->pid, SIGTERM);
324	while ((ret = waitpid(ctx->pid, NULL, 0)) == -1) {
325		if (errno != EINTR)
326			break;
327	}
328	if (ret == -1)
329		fatal_f("waitpid: %s", strerror(errno));
330	ssh_signal(SIGCHLD, ctx->osigchld);
331	free(ctx);
332}
333