1/*-
2 * Copyright (c) 2014 Michihiro NAKAJIMA
3 * 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 *    in this position and unchanged.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 *    notice, this list of conditions and the following disclaimer in the
13 *    documentation and/or other materials provided with the distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
16 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18 * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
19 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25 */
26/*	$OpenBSD: readpassphrase.c,v 1.27 2019/01/25 00:19:25 millert Exp $	*/
27
28/*
29 * Copyright (c) 2000-2002, 2007, 2010
30 * 	Todd C. Miller <millert@openbsd.org>
31 *
32 * Permission to use, copy, modify, and distribute this software for any
33 * purpose with or without fee is hereby granted, provided that the above
34 * copyright notice and this permission notice appear in all copies.
35 *
36 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
37 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
38 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
39 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
40 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
41 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
42 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
43 *
44 * Sponsored in part by the Defense Advanced Research Projects
45 * Agency (DARPA) and Air Force Research Laboratory, Air Force
46 * Materiel Command, USAF, under agreement number F39502-99-1-0512.
47 */
48
49/* OPENBSD ORIGINAL: lib/libc/gen/readpassphrase.c */
50
51
52#include "lafe_platform.h"
53#include <errno.h>
54#ifdef HAVE_STDLIB_H
55#include <stdlib.h>
56#endif
57#ifdef HAVE_UNISTD_H
58#include <unistd.h>
59#endif
60#ifdef HAVE_READPASSPHRASE_H
61#include <readpassphrase.h>
62#endif
63
64#include "err.h"
65#include "passphrase.h"
66
67#ifndef HAVE_READPASSPHRASE
68
69#define RPP_ECHO_OFF    0x00		/* Turn off echo (default). */
70#define RPP_ECHO_ON     0x01		/* Leave echo on. */
71#define RPP_REQUIRE_TTY 0x02		/* Fail if there is no tty. */
72#define RPP_FORCELOWER  0x04		/* Force input to lower case. */
73#define RPP_FORCEUPPER  0x08		/* Force input to upper case. */
74#define RPP_SEVENBIT    0x10		/* Strip the high bit from input. */
75#define RPP_STDIN       0x20		/* Read from stdin, not /dev/tty */
76
77
78#if defined(_WIN32) && !defined(__CYGWIN__)
79#include <string.h>
80#include <windows.h>
81
82static char *
83readpassphrase(const char *prompt, char *buf, size_t bufsiz, int flags)
84{
85	HANDLE hStdin, hStdout;
86	DWORD mode, rbytes;
87	BOOL success;
88
89	(void)flags;
90
91	hStdin = GetStdHandle(STD_INPUT_HANDLE);
92	if (hStdin == INVALID_HANDLE_VALUE)
93		return (NULL);
94	hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
95	if (hStdout == INVALID_HANDLE_VALUE)
96		return (NULL);
97
98	success = GetConsoleMode(hStdin, &mode);
99	if (!success)
100		return (NULL);
101	mode &= ~ENABLE_ECHO_INPUT;
102	mode |= ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT;
103	success = SetConsoleMode(hStdin, mode);
104	if (!success)
105		return (NULL);
106
107	success = WriteFile(hStdout, prompt, (DWORD)strlen(prompt),
108		NULL, NULL);
109	if (!success)
110		return (NULL);
111	success = ReadFile(hStdin, buf, (DWORD)bufsiz - 1, &rbytes, NULL);
112	if (!success)
113		return (NULL);
114	WriteFile(hStdout, "\r\n", 2, NULL, NULL);
115	buf[rbytes] = '\0';
116	/* Remove trailing carriage return(s). */
117	buf[strcspn(buf, "\r\n")] = '\0';
118
119	return (buf);
120}
121
122#else /* _WIN32 && !__CYGWIN__ */
123
124#include <assert.h>
125#include <ctype.h>
126#include <fcntl.h>
127#ifdef HAVE_PATHS_H
128#include <paths.h>
129#endif
130#include <signal.h>
131#include <string.h>
132#include <termios.h>
133#include <unistd.h>
134
135#ifndef _PATH_TTY
136#define _PATH_TTY "/dev/tty"
137#endif
138
139#ifdef TCSASOFT
140# define _T_FLUSH	(TCSAFLUSH|TCSASOFT)
141#else
142# define _T_FLUSH	(TCSAFLUSH)
143#endif
144
145/* SunOS 4.x which lacks _POSIX_VDISABLE, but has VDISABLE */
146#if !defined(_POSIX_VDISABLE) && defined(VDISABLE)
147#  define _POSIX_VDISABLE       VDISABLE
148#endif
149
150#define M(a,b) (a > b ? a : b)
151#define MAX_SIGNO M(M(M(SIGALRM, SIGHUP), \
152                      M(SIGINT, SIGPIPE)), \
153                    M(M(SIGQUIT, SIGTERM), \
154                      M(M(SIGTSTP, SIGTTIN), SIGTTOU)))
155
156static volatile sig_atomic_t signo[MAX_SIGNO + 1];
157
158static void
159handler(int s)
160{
161	assert(s <= MAX_SIGNO);
162	signo[s] = 1;
163}
164
165static char *
166readpassphrase(const char *prompt, char *buf, size_t bufsiz, int flags)
167{
168	ssize_t nr;
169	int input, output, save_errno, i, need_restart;
170	char ch, *p, *end;
171	struct termios term, oterm;
172#ifdef HAVE_SIGACTION
173	struct sigaction sa, savealrm, saveint, savehup, savequit, saveterm;
174	struct sigaction savetstp, savettin, savettou, savepipe;
175#endif
176
177	/* I suppose we could alloc on demand in this case (XXX). */
178	if (bufsiz == 0) {
179		errno = EINVAL;
180		return(NULL);
181	}
182
183restart:
184	for (i = 0; i <= MAX_SIGNO; i++)
185		signo[i] = 0;
186	nr = -1;
187	save_errno = 0;
188	need_restart = 0;
189	/*
190	 * Read and write to /dev/tty if available.  If not, read from
191	 * stdin and write to stderr unless a tty is required.
192	 */
193	if ((flags & RPP_STDIN) ||
194	    (input = output = open(_PATH_TTY, O_RDWR)) == -1) {
195		if (flags & RPP_REQUIRE_TTY) {
196			errno = ENOTTY;
197			return(NULL);
198		}
199		input = STDIN_FILENO;
200		output = STDERR_FILENO;
201	}
202
203	/*
204	 * Turn off echo if possible.
205	 * If we are using a tty but are not the foreground pgrp this will
206	 * generate SIGTTOU, so do it *before* installing the signal handlers.
207	 */
208	if (input != STDIN_FILENO && tcgetattr(input, &oterm) == 0) {
209		memcpy(&term, &oterm, sizeof(term));
210		if (!(flags & RPP_ECHO_ON))
211			term.c_lflag &= ~(ECHO | ECHONL);
212#ifdef VSTATUS
213		if (term.c_cc[VSTATUS] != _POSIX_VDISABLE)
214			term.c_cc[VSTATUS] = _POSIX_VDISABLE;
215#endif
216		(void)tcsetattr(input, _T_FLUSH, &term);
217	} else {
218		memset(&term, 0, sizeof(term));
219		term.c_lflag |= ECHO;
220		memset(&oterm, 0, sizeof(oterm));
221		oterm.c_lflag |= ECHO;
222	}
223
224#ifdef HAVE_SIGACTION
225	/*
226	 * Catch signals that would otherwise cause the user to end
227	 * up with echo turned off in the shell.  Don't worry about
228	 * things like SIGXCPU and SIGVTALRM for now.
229	 */
230	sigemptyset(&sa.sa_mask);
231	sa.sa_flags = 0;		/* don't restart system calls */
232	sa.sa_handler = handler;
233	/* Keep this list in sync with MAX_SIGNO! */
234	(void)sigaction(SIGALRM, &sa, &savealrm);
235	(void)sigaction(SIGHUP, &sa, &savehup);
236	(void)sigaction(SIGINT, &sa, &saveint);
237	(void)sigaction(SIGPIPE, &sa, &savepipe);
238	(void)sigaction(SIGQUIT, &sa, &savequit);
239	(void)sigaction(SIGTERM, &sa, &saveterm);
240	(void)sigaction(SIGTSTP, &sa, &savetstp);
241	(void)sigaction(SIGTTIN, &sa, &savettin);
242	(void)sigaction(SIGTTOU, &sa, &savettou);
243#endif
244
245	if (!(flags & RPP_STDIN)) {
246		int r = write(output, prompt, strlen(prompt));
247		(void)r;
248	}
249	end = buf + bufsiz - 1;
250	p = buf;
251	while ((nr = read(input, &ch, 1)) == 1 && ch != '\n' && ch != '\r') {
252		if (p < end) {
253			if ((flags & RPP_SEVENBIT))
254				ch &= 0x7f;
255			if (isalpha((unsigned char)ch)) {
256				if ((flags & RPP_FORCELOWER))
257					ch = (char)tolower((unsigned char)ch);
258				if ((flags & RPP_FORCEUPPER))
259					ch = (char)toupper((unsigned char)ch);
260			}
261			*p++ = ch;
262		}
263	}
264	*p = '\0';
265	save_errno = errno;
266	if (!(term.c_lflag & ECHO)) {
267		int r = write(output, "\n", 1);
268		(void)r;
269	}
270
271	/* Restore old terminal settings and signals. */
272	if (memcmp(&term, &oterm, sizeof(term)) != 0) {
273		const int sigttou = signo[SIGTTOU];
274
275		/* Ignore SIGTTOU generated when we are not the fg pgrp. */
276		while (tcsetattr(input, _T_FLUSH, &oterm) == -1 &&
277		    errno == EINTR && !signo[SIGTTOU])
278			continue;
279		signo[SIGTTOU] = sigttou;
280	}
281#ifdef HAVE_SIGACTION
282	(void)sigaction(SIGALRM, &savealrm, NULL);
283	(void)sigaction(SIGHUP, &savehup, NULL);
284	(void)sigaction(SIGINT, &saveint, NULL);
285	(void)sigaction(SIGQUIT, &savequit, NULL);
286	(void)sigaction(SIGPIPE, &savepipe, NULL);
287	(void)sigaction(SIGTERM, &saveterm, NULL);
288	(void)sigaction(SIGTSTP, &savetstp, NULL);
289	(void)sigaction(SIGTTIN, &savettin, NULL);
290	(void)sigaction(SIGTTOU, &savettou, NULL);
291#endif
292	if (input != STDIN_FILENO)
293		(void)close(input);
294
295	/*
296	 * If we were interrupted by a signal, resend it to ourselves
297	 * now that we have restored the signal handlers.
298	 */
299	for (i = 0; i <= MAX_SIGNO; i++) {
300		if (signo[i]) {
301			kill(getpid(), i);
302			switch (i) {
303			case SIGTSTP:
304			case SIGTTIN:
305			case SIGTTOU:
306				need_restart = 1;
307			}
308		}
309	}
310	if (need_restart)
311		goto restart;
312
313	if (save_errno)
314		errno = save_errno;
315	return(nr == -1 ? NULL : buf);
316}
317#endif /* _WIN32 && !__CYGWIN__ */
318#endif /* HAVE_READPASSPHRASE */
319
320char *
321lafe_readpassphrase(const char *prompt, char *buf, size_t bufsiz)
322{
323	char *p;
324
325	p = readpassphrase(prompt, buf, bufsiz, RPP_ECHO_OFF);
326	if (p == NULL) {
327		switch (errno) {
328		case EINTR:
329			break;
330		default:
331			lafe_errc(1, errno, "Couldn't read passphrase");
332			/* NOTREACHED */
333		}
334	}
335	return (p);
336}
337
338