xref: /freebsd/contrib/libarchive/libarchive_fe/passphrase.c (revision 282e23f07bf49b4e37aabdcc1c513a788db36d10)
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.22 2010/01/13 10:20:54 dtucker Exp $	*/
27 /*
28  * Copyright (c) 2000-2002, 2007 Todd C. Miller <Todd.Miller@courtesan.com>
29  *
30  * Permission to use, copy, modify, and distribute this software for any
31  * purpose with or without fee is hereby granted, provided that the above
32  * copyright notice and this permission notice appear in all copies.
33  *
34  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
35  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
36  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
37  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
38  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
39  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
40  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
41  *
42  * Sponsored in part by the Defense Advanced Research Projects
43  * Agency (DARPA) and Air Force Research Laboratory, Air Force
44  * Materiel Command, USAF, under agreement number F39502-99-1-0512.
45  */
46 
47 /* OPENBSD ORIGINAL: lib/libc/gen/readpassphrase.c */
48 
49 
50 #include "lafe_platform.h"
51 __FBSDID("$FreeBSD$");
52 
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 <windows.h>
80 
81 static char *
82 readpassphrase(const char *prompt, char *buf, size_t bufsiz, int flags)
83 {
84 	HANDLE hStdin, hStdout;
85 	DWORD mode, rbytes;
86 	BOOL success;
87 
88 	(void)flags;
89 
90 	hStdin = GetStdHandle(STD_INPUT_HANDLE);
91 	if (hStdin == INVALID_HANDLE_VALUE)
92 		return (NULL);
93 	hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
94 	if (hStdout == INVALID_HANDLE_VALUE)
95 		return (NULL);
96 
97 	success = GetConsoleMode(hStdin, &mode);
98 	if (!success)
99 		return (NULL);
100 	mode &= ~ENABLE_ECHO_INPUT;
101 	mode |= ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT;
102 	success = SetConsoleMode(hStdin, mode);
103 	if (!success)
104 		return (NULL);
105 
106 	success = WriteFile(hStdout, prompt, (DWORD)strlen(prompt),
107 		NULL, NULL);
108 	if (!success)
109 		return (NULL);
110 	success = ReadFile(hStdin, buf, (DWORD)bufsiz - 1, &rbytes, NULL);
111 	if (!success)
112 		return (NULL);
113 	WriteFile(hStdout, "\r\n", 2, NULL, NULL);
114 	buf[rbytes] = '\0';
115 	/* Remove trailing carriage return(s). */
116 	if (rbytes > 2 && buf[rbytes - 2] == '\r' && buf[rbytes - 1] == '\n')
117 		buf[rbytes - 2] = '\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 #ifdef TCSASOFT
136 # define _T_FLUSH	(TCSAFLUSH|TCSASOFT)
137 #else
138 # define _T_FLUSH	(TCSAFLUSH)
139 #endif
140 
141 /* SunOS 4.x which lacks _POSIX_VDISABLE, but has VDISABLE */
142 #if !defined(_POSIX_VDISABLE) && defined(VDISABLE)
143 #  define _POSIX_VDISABLE       VDISABLE
144 #endif
145 
146 #define M(a,b) (a > b ? a : b)
147 #define MAX_SIGNO M(M(M(SIGALRM, SIGHUP), \
148                       M(SIGINT, SIGPIPE)), \
149                     M(M(SIGQUIT, SIGTERM), \
150                       M(M(SIGTSTP, SIGTTIN), SIGTTOU)))
151 
152 static volatile sig_atomic_t signo[MAX_SIGNO + 1];
153 
154 static void
155 handler(int s)
156 {
157 	assert(s <= MAX_SIGNO);
158 	signo[s] = 1;
159 }
160 
161 static char *
162 readpassphrase(const char *prompt, char *buf, size_t bufsiz, int flags)
163 {
164 	ssize_t nr;
165 	int input, output, save_errno, i, need_restart;
166 	char ch, *p, *end;
167 	struct termios term, oterm;
168 	struct sigaction sa, savealrm, saveint, savehup, savequit, saveterm;
169 	struct sigaction savetstp, savettin, savettou, savepipe;
170 
171 	/* I suppose we could alloc on demand in this case (XXX). */
172 	if (bufsiz == 0) {
173 		errno = EINVAL;
174 		return(NULL);
175 	}
176 
177 restart:
178 	for (i = 0; i <= MAX_SIGNO; i++)
179 		signo[i] = 0;
180 	nr = -1;
181 	save_errno = 0;
182 	need_restart = 0;
183 	/*
184 	 * Read and write to /dev/tty if available.  If not, read from
185 	 * stdin and write to stderr unless a tty is required.
186 	 */
187 	if ((flags & RPP_STDIN) ||
188 	    (input = output = open(_PATH_TTY, O_RDWR)) == -1) {
189 		if (flags & RPP_REQUIRE_TTY) {
190 			errno = ENOTTY;
191 			return(NULL);
192 		}
193 		input = STDIN_FILENO;
194 		output = STDERR_FILENO;
195 	}
196 
197 	/*
198 	 * Catch signals that would otherwise cause the user to end
199 	 * up with echo turned off in the shell.  Don't worry about
200 	 * things like SIGXCPU and SIGVTALRM for now.
201 	 */
202 	sigemptyset(&sa.sa_mask);
203 	sa.sa_flags = 0;		/* don't restart system calls */
204 	sa.sa_handler = handler;
205 	/* Keep this list in sync with MAX_SIGNO! */
206 	(void)sigaction(SIGALRM, &sa, &savealrm);
207 	(void)sigaction(SIGHUP, &sa, &savehup);
208 	(void)sigaction(SIGINT, &sa, &saveint);
209 	(void)sigaction(SIGPIPE, &sa, &savepipe);
210 	(void)sigaction(SIGQUIT, &sa, &savequit);
211 	(void)sigaction(SIGTERM, &sa, &saveterm);
212 	(void)sigaction(SIGTSTP, &sa, &savetstp);
213 	(void)sigaction(SIGTTIN, &sa, &savettin);
214 	(void)sigaction(SIGTTOU, &sa, &savettou);
215 
216 	/* Turn off echo if possible. */
217 	if (input != STDIN_FILENO && tcgetattr(input, &oterm) == 0) {
218 		memcpy(&term, &oterm, sizeof(term));
219 		if (!(flags & RPP_ECHO_ON))
220 			term.c_lflag &= ~(ECHO | ECHONL);
221 #ifdef VSTATUS
222 		if (term.c_cc[VSTATUS] != _POSIX_VDISABLE)
223 			term.c_cc[VSTATUS] = _POSIX_VDISABLE;
224 #endif
225 		(void)tcsetattr(input, _T_FLUSH, &term);
226 	} else {
227 		memset(&term, 0, sizeof(term));
228 		term.c_lflag |= ECHO;
229 		memset(&oterm, 0, sizeof(oterm));
230 		oterm.c_lflag |= ECHO;
231 	}
232 
233 	/* No I/O if we are already backgrounded. */
234 	if (signo[SIGTTOU] != 1 && signo[SIGTTIN] != 1) {
235 		if (!(flags & RPP_STDIN)) {
236 			int r = write(output, prompt, strlen(prompt));
237 			(void)r;
238 		}
239 		end = buf + bufsiz - 1;
240 		p = buf;
241 		while ((nr = read(input, &ch, 1)) == 1 && ch != '\n' && ch != '\r') {
242 			if (p < end) {
243 				if ((flags & RPP_SEVENBIT))
244 					ch &= 0x7f;
245 				if (isalpha((unsigned char)ch)) {
246 					if ((flags & RPP_FORCELOWER))
247 						ch = (char)tolower((unsigned char)ch);
248 					if ((flags & RPP_FORCEUPPER))
249 						ch = (char)toupper((unsigned char)ch);
250 				}
251 				*p++ = ch;
252 			}
253 		}
254 		*p = '\0';
255 		save_errno = errno;
256 		if (!(term.c_lflag & ECHO)) {
257 			int r = write(output, "\n", 1);
258 			(void)r;
259 		}
260 	}
261 
262 	/* Restore old terminal settings and signals. */
263 	if (memcmp(&term, &oterm, sizeof(term)) != 0) {
264 		while (tcsetattr(input, _T_FLUSH, &oterm) == -1 &&
265 		    errno == EINTR)
266 			continue;
267 	}
268 	(void)sigaction(SIGALRM, &savealrm, NULL);
269 	(void)sigaction(SIGHUP, &savehup, NULL);
270 	(void)sigaction(SIGINT, &saveint, NULL);
271 	(void)sigaction(SIGQUIT, &savequit, NULL);
272 	(void)sigaction(SIGPIPE, &savepipe, NULL);
273 	(void)sigaction(SIGTERM, &saveterm, NULL);
274 	(void)sigaction(SIGTSTP, &savetstp, NULL);
275 	(void)sigaction(SIGTTIN, &savettin, NULL);
276 	(void)sigaction(SIGTTOU, &savettou, NULL);
277 	if (input != STDIN_FILENO)
278 		(void)close(input);
279 
280 	/*
281 	 * If we were interrupted by a signal, resend it to ourselves
282 	 * now that we have restored the signal handlers.
283 	 */
284 	for (i = 0; i <= MAX_SIGNO; i++) {
285 		if (signo[i]) {
286 			kill(getpid(), i);
287 			switch (i) {
288 			case SIGTSTP:
289 			case SIGTTIN:
290 			case SIGTTOU:
291 				need_restart = 1;
292 			}
293 		}
294 	}
295 	if (need_restart)
296 		goto restart;
297 
298 	if (save_errno)
299 		errno = save_errno;
300 	return(nr == -1 ? NULL : buf);
301 }
302 #endif /* _WIN32 && !__CYGWIN__ */
303 #endif /* HAVE_READPASSPHRASE */
304 
305 char *
306 lafe_readpassphrase(const char *prompt, char *buf, size_t bufsiz)
307 {
308 	char *p;
309 
310 	p = readpassphrase(prompt, buf, bufsiz, RPP_ECHO_OFF);
311 	if (p == NULL) {
312 		switch (errno) {
313 		case EINTR:
314 			break;
315 		default:
316 			lafe_errc(1, errno, "Couldn't read passphrase");
317 			break;
318 		}
319 	}
320 	return (p);
321 }
322 
323