xref: /netbsd-src/crypto/external/bsd/openssh/dist/readpass.c (revision 1c7715dda22cf2bd169e2f84953c050393e8fe9c)
1 /*	$NetBSD: readpass.c,v 1.19 2024/07/08 22:33:44 christos Exp $	*/
2 /* $OpenBSD: readpass.c,v 1.71 2024/03/30 04:27:44 djm 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.19 2024/07/08 22:33:44 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 
51 static char *
ssh_askpass(const char * askpass,const char * msg,const char * env_hint)52 ssh_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  */
123 char *
read_passphrase(const char * prompt,int flags)124 read_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 && *s != '\0') ||
132 	    ((s = getenv("WAYLAND_DISPLAY")) != NULL && *s != '\0'))
133 		allow_askpass = 1;
134 	if ((s = getenv(SSH_ASKPASS_REQUIRE_ENV)) != NULL) {
135 		if (strcasecmp(s, "force") == 0) {
136 			use_askpass = 1;
137 			allow_askpass = 1;
138 		} else if (strcasecmp(s, "prefer") == 0)
139 			use_askpass = allow_askpass;
140 		else if (strcasecmp(s, "never") == 0)
141 			allow_askpass = 0;
142 	}
143 
144 	rppflags = (flags & RP_ECHO) ? RPP_ECHO_ON : RPP_ECHO_OFF;
145 	if (use_askpass)
146 		debug_f("requested to askpass");
147 	else if (flags & RP_USE_ASKPASS)
148 		use_askpass = 1;
149 	else if (flags & RP_ALLOW_STDIN) {
150 		if (!isatty(STDIN_FILENO)) {
151 			debug_f("stdin is not a tty");
152 			use_askpass = 1;
153 		}
154 	} else {
155 		rppflags |= RPP_REQUIRE_TTY;
156 		ttyfd = open(_PATH_TTY, O_RDWR);
157 		if (ttyfd >= 0) {
158 			/*
159 			 * If we're on a tty, ensure that show the prompt at
160 			 * the beginning of the line. This will hopefully
161 			 * clobber any password characters the user has
162 			 * optimistically typed before echo is disabled.
163 			 */
164 			(void)write(ttyfd, &cr, 1);
165 			close(ttyfd);
166 		} else {
167 			debug_f("can't open %s: %s", _PATH_TTY,
168 			    strerror(errno));
169 			use_askpass = 1;
170 		}
171 	}
172 
173 	if ((flags & RP_USE_ASKPASS) && !allow_askpass)
174 		return (flags & RP_ALLOW_EOF) ? NULL : xstrdup("");
175 
176 	if (use_askpass && allow_askpass) {
177 		if (getenv(SSH_ASKPASS_ENV))
178 			askpass = getenv(SSH_ASKPASS_ENV);
179 		else
180 			askpass = _PATH_SSH_ASKPASS_DEFAULT;
181 		if ((flags & RP_ASK_PERMISSION) != 0)
182 			askpass_hint = "confirm";
183 		if ((ret = ssh_askpass(askpass, prompt, askpass_hint)) == NULL)
184 			if (!(flags & RP_ALLOW_EOF))
185 				return xstrdup("");
186 		return ret;
187 	}
188 
189 	if (readpassphrase(prompt, buf, sizeof buf, rppflags) == NULL) {
190 		if (flags & RP_ALLOW_EOF)
191 			return NULL;
192 		return xstrdup("");
193 	}
194 
195 	ret = xstrdup(buf);
196 	explicit_bzero(buf, sizeof(buf));
197 	return ret;
198 }
199 
200 int
ask_permission(const char * fmt,...)201 ask_permission(const char *fmt, ...)
202 {
203 	va_list args;
204 	char *p, prompt[1024];
205 	int allowed = 0;
206 
207 	va_start(args, fmt);
208 	vsnprintf(prompt, sizeof(prompt), fmt, args);
209 	va_end(args);
210 
211 	p = read_passphrase(prompt,
212 	    RP_USE_ASKPASS|RP_ALLOW_EOF|RP_ASK_PERMISSION);
213 	if (p != NULL) {
214 		/*
215 		 * Accept empty responses and responses consisting
216 		 * of the word "yes" as affirmative.
217 		 */
218 		if (*p == '\0' || *p == '\n' ||
219 		    strcasecmp(p, "yes") == 0)
220 			allowed = 1;
221 		free(p);
222 	}
223 
224 	return (allowed);
225 }
226 
227 static void
writemsg(const char * msg)228 writemsg(const char *msg)
229 {
230 	(void)write(STDERR_FILENO, "\r", 1);
231 	(void)write(STDERR_FILENO, msg, strlen(msg));
232 	(void)write(STDERR_FILENO, "\r\n", 2);
233 }
234 
235 struct notifier_ctx {
236 	pid_t pid;
237 	void (*osigchld)(int);
238 };
239 
240 struct notifier_ctx *
notify_start(int force_askpass,const char * fmt,...)241 notify_start(int force_askpass, const char *fmt, ...)
242 {
243 	va_list args;
244 	char *prompt = NULL;
245 	pid_t pid = -1;
246 	void (*osigchld)(int) = NULL;
247 	const char *askpass, *s;
248 	struct notifier_ctx *ret = NULL;
249 
250 	va_start(args, fmt);
251 	xvasprintf(&prompt, fmt, args);
252 	va_end(args);
253 
254 	if (fflush(NULL) != 0)
255 		error_f("fflush: %s", strerror(errno));
256 	if (!force_askpass && isatty(STDERR_FILENO)) {
257 		writemsg(prompt);
258 		goto out_ctx;
259 	}
260 	if ((askpass = getenv("SSH_ASKPASS")) == NULL)
261 		askpass = _PATH_SSH_ASKPASS_DEFAULT;
262 	if (*askpass == '\0') {
263 		debug3_f("cannot notify: no askpass");
264 		goto out;
265 	}
266 	if (getenv("DISPLAY") == NULL && getenv("WAYLAND_DISPLAY") == NULL &&
267 	    ((s = getenv(SSH_ASKPASS_REQUIRE_ENV)) == NULL ||
268 	    strcmp(s, "force") != 0)) {
269 		debug3_f("cannot notify: no display");
270 		goto out;
271 	}
272 	osigchld = ssh_signal(SIGCHLD, SIG_DFL);
273 	if ((pid = fork()) == -1) {
274 		error_f("fork: %s", strerror(errno));
275 		ssh_signal(SIGCHLD, osigchld);
276 		free(prompt);
277 		return NULL;
278 	}
279 	if (pid == 0) {
280 		if (stdfd_devnull(1, 1, 0) == -1)
281 			fatal_f("stdfd_devnull failed");
282 		closefrom(STDERR_FILENO + 1);
283 		setenv("SSH_ASKPASS_PROMPT", "none", 1); /* hint to UI */
284 		execlp(askpass, askpass, prompt, (char *)NULL);
285 		error_f("exec(%s): %s", askpass, strerror(errno));
286 		_exit(1);
287 		/* NOTREACHED */
288 	}
289  out_ctx:
290 	if ((ret = calloc(1, sizeof(*ret))) == NULL) {
291 		if (pid != -1)
292 			kill(pid, SIGTERM);
293 		fatal_f("calloc failed");
294 	}
295 	ret->pid = pid;
296 	ret->osigchld = osigchld;
297  out:
298 	free(prompt);
299 	return ret;
300 }
301 
302 void
notify_complete(struct notifier_ctx * ctx,const char * fmt,...)303 notify_complete(struct notifier_ctx *ctx, const char *fmt, ...)
304 {
305 	int ret;
306 	char *msg = NULL;
307 	va_list args;
308 
309 	if (ctx != NULL && fmt != NULL && ctx->pid == -1) {
310 		/*
311 		 * notify_start wrote to stderr, so send conclusion message
312 		 * there too
313 		*/
314 		va_start(args, fmt);
315 		xvasprintf(&msg, fmt, args);
316 		va_end(args);
317 		writemsg(msg);
318 		free(msg);
319 	}
320 
321 	if (ctx == NULL || ctx->pid <= 0) {
322 		free(ctx);
323 		return;
324 	}
325 	kill(ctx->pid, SIGTERM);
326 	while ((ret = waitpid(ctx->pid, NULL, 0)) == -1) {
327 		if (errno != EINTR)
328 			break;
329 	}
330 	if (ret == -1)
331 		fatal_f("waitpid: %s", strerror(errno));
332 	ssh_signal(SIGCHLD, ctx->osigchld);
333 	free(ctx);
334 }
335