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