]> granicus.if.org Git - sudo/blob - src/tgetpass.c
76b0c8bae87578e3e2ee9e1754db38e377774799
[sudo] / src / tgetpass.c
1 /*
2  * Copyright (c) 1996, 1998-2005, 2007-2018
3  *      Todd C. Miller <Todd.Miller@sudo.ws>
4  *
5  * Permission to use, copy, modify, and distribute this software for any
6  * purpose with or without fee is hereby granted, provided that the above
7  * copyright notice and this permission notice appear in all copies.
8  *
9  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16  *
17  * Sponsored in part by the Defense Advanced Research Projects
18  * Agency (DARPA) and Air Force Research Laboratory, Air Force
19  * Materiel Command, USAF, under agreement number F39502-99-1-0512.
20  */
21
22 /*
23  * This is an open source non-commercial project. Dear PVS-Studio, please check it.
24  * PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
25  */
26
27 #ifdef __TANDEM
28 # include <floss.h>
29 #endif
30
31 #include <config.h>
32
33 #include <sys/types.h>
34 #include <sys/wait.h>
35 #include <stdio.h>
36 #include <stdlib.h>
37 #ifdef HAVE_STRING_H
38 # include <string.h>
39 #endif /* HAVE_STRING_H */
40 #ifdef HAVE_STRINGS_H
41 # include <strings.h>
42 #endif /* HAVE_STRINGS_H */
43 #include <unistd.h>
44 #include <pwd.h>
45 #include <errno.h>
46 #include <signal.h>
47 #include <fcntl.h>
48
49 #include "sudo.h"
50 #include "sudo_plugin.h"
51
52 enum tgetpass_errval {
53     TGP_ERRVAL_NOERROR,
54     TGP_ERRVAL_TIMEOUT,
55     TGP_ERRVAL_NOPASSWORD,
56     TGP_ERRVAL_READERROR
57 };
58
59 static volatile sig_atomic_t signo[NSIG];
60
61 static bool tty_present(void);
62 static void tgetpass_handler(int);
63 static char *getln(int, char *, size_t, int, enum tgetpass_errval *);
64 static char *sudo_askpass(const char *, const char *);
65
66 static int
67 suspend(int signo, struct sudo_conv_callback *callback)
68 {
69     int ret = 0;
70     debug_decl(suspend, SUDO_DEBUG_CONV)
71
72     if (callback != NULL && SUDO_API_VERSION_GET_MAJOR(callback->version) != SUDO_CONV_CALLBACK_VERSION_MAJOR) {
73         sudo_debug_printf(SUDO_DEBUG_WARN|SUDO_DEBUG_LINENO,
74             "callback major version mismatch, expected %u, got %u",
75             SUDO_CONV_CALLBACK_VERSION_MAJOR,
76             SUDO_API_VERSION_GET_MAJOR(callback->version));
77         callback = NULL;
78     }
79
80     if (callback != NULL && callback->on_suspend != NULL) {
81         if (callback->on_suspend(signo, callback->closure) == -1)
82             ret = -1;
83     }
84     kill(getpid(), signo);
85     if (callback != NULL && callback->on_resume != NULL) {
86         if (callback->on_resume(signo, callback->closure) == -1)
87             ret = -1;
88     }
89     debug_return_int(ret);
90 }
91
92 static void
93 tgetpass_display_error(enum tgetpass_errval errval)
94 {
95     debug_decl(tgetpass_display_error, SUDO_DEBUG_CONV)
96
97     switch (errval) {
98     case TGP_ERRVAL_NOERROR:
99         break;
100     case TGP_ERRVAL_TIMEOUT:
101         sudo_warnx(U_("timed out reading password"));
102         break;
103     case TGP_ERRVAL_NOPASSWORD:
104         sudo_warnx(U_("no password was provided"));
105         break;
106     case TGP_ERRVAL_READERROR:
107         sudo_warn(U_("unable to read password"));
108         break;
109     }
110     debug_return;
111 }
112
113 /*
114  * Like getpass(3) but with timeout and echo flags.
115  */
116 char *
117 tgetpass(const char *prompt, int timeout, int flags,
118     struct sudo_conv_callback *callback)
119 {
120     struct sigaction sa, savealrm, saveint, savehup, savequit, saveterm;
121     struct sigaction savetstp, savettin, savettou;
122     char *pass;
123     static const char *askpass;
124     static char buf[SUDO_CONV_REPL_MAX + 1];
125     int i, input, output, save_errno, neednl = 0, need_restart;
126     enum tgetpass_errval errval;
127     debug_decl(tgetpass, SUDO_DEBUG_CONV)
128
129     (void) fflush(stdout);
130
131     if (askpass == NULL) {
132         askpass = getenv_unhooked("SUDO_ASKPASS");
133         if (askpass == NULL || *askpass == '\0')
134             askpass = sudo_conf_askpass_path();
135     }
136
137     /* If no tty present and we need to disable echo, try askpass. */
138     if (!ISSET(flags, TGP_STDIN|TGP_ECHO|TGP_ASKPASS|TGP_NOECHO_TRY) &&
139         !tty_present()) {
140         if (askpass == NULL || getenv_unhooked("DISPLAY") == NULL) {
141             sudo_warnx(U_("no tty present and no askpass program specified"));
142             debug_return_str(NULL);
143         }
144         SET(flags, TGP_ASKPASS);
145     }
146
147     /* If using a helper program to get the password, run it instead. */
148     if (ISSET(flags, TGP_ASKPASS)) {
149         if (askpass == NULL || *askpass == '\0')
150             sudo_fatalx(U_("no askpass program specified, try setting SUDO_ASKPASS"));
151         debug_return_str_masked(sudo_askpass(askpass, prompt));
152     }
153
154 restart:
155     for (i = 0; i < NSIG; i++)
156         signo[i] = 0;
157     pass = NULL;
158     save_errno = 0;
159     need_restart = 0;
160     /* Open /dev/tty for reading/writing if possible else use stdin/stderr. */
161     if (ISSET(flags, TGP_STDIN) ||
162         (input = output = open(_PATH_TTY, O_RDWR)) == -1) {
163         input = STDIN_FILENO;
164         output = STDERR_FILENO;
165     }
166
167     /*
168      * If we are using a tty but are not the foreground pgrp this will
169      * return EINTR.  We send ourself SIGTTOU bracketed by callbacks.
170      */
171     if (!ISSET(flags, TGP_ECHO)) {
172         for (;;) {
173             if (ISSET(flags, TGP_MASK))
174                 neednl = sudo_term_cbreak(input);
175             else
176                 neednl = sudo_term_noecho(input);
177             if (neednl || errno != EINTR)
178                 break;
179             /* Received SIGTTOU, suspend the process. */
180             if (suspend(SIGTTOU, callback) == -1) {
181                 if (input != STDIN_FILENO)
182                     (void) close(input);
183                 debug_return_ptr(NULL);
184             }
185         }
186     }
187
188     /*
189      * Catch signals that would otherwise cause the user to end
190      * up with echo turned off in the shell.
191      */
192     memset(&sa, 0, sizeof(sa));
193     sigemptyset(&sa.sa_mask);
194     sa.sa_flags = 0;    /* don't restart system calls */
195     sa.sa_handler = tgetpass_handler;
196     (void) sigaction(SIGALRM, &sa, &savealrm);
197     (void) sigaction(SIGINT, &sa, &saveint);
198     (void) sigaction(SIGHUP, &sa, &savehup);
199     (void) sigaction(SIGQUIT, &sa, &savequit);
200     (void) sigaction(SIGTERM, &sa, &saveterm);
201     (void) sigaction(SIGTSTP, &sa, &savetstp);
202     (void) sigaction(SIGTTIN, &sa, &savettin);
203     (void) sigaction(SIGTTOU, &sa, &savettou);
204
205     if (prompt) {
206         if (write(output, prompt, strlen(prompt)) == -1)
207             goto restore;
208     }
209
210     if (timeout > 0)
211         alarm(timeout);
212     pass = getln(input, buf, sizeof(buf), ISSET(flags, TGP_MASK), &errval);
213     alarm(0);
214     save_errno = errno;
215
216     if (neednl || pass == NULL) {
217         if (write(output, "\n", 1) == -1)
218             goto restore;
219     }
220     tgetpass_display_error(errval);
221
222 restore:
223     /* Restore old signal handlers. */
224     (void) sigaction(SIGALRM, &savealrm, NULL);
225     (void) sigaction(SIGINT, &saveint, NULL);
226     (void) sigaction(SIGHUP, &savehup, NULL);
227     (void) sigaction(SIGQUIT, &savequit, NULL);
228     (void) sigaction(SIGTERM, &saveterm, NULL);
229     (void) sigaction(SIGTSTP, &savetstp, NULL);
230     (void) sigaction(SIGTTIN, &savettin, NULL);
231     (void) sigaction(SIGTTOU, &savettou, NULL);
232
233     /* Restore old tty settings. */
234     if (!ISSET(flags, TGP_ECHO)) {
235         /* Restore old tty settings if possible. */
236         (void) sudo_term_restore(input, true);
237     }
238     if (input != STDIN_FILENO)
239         (void) close(input);
240
241     /*
242      * If we were interrupted by a signal, resend it to ourselves
243      * now that we have restored the signal handlers.
244      */
245     for (i = 0; i < NSIG; i++) {
246         if (signo[i]) {
247             switch (i) {
248                 case SIGALRM:
249                     break;
250                 case SIGTSTP:
251                 case SIGTTIN:
252                 case SIGTTOU:
253                     if (suspend(i, callback) == 0)
254                         need_restart = 1;
255                     break;
256                 default:
257                     kill(getpid(), i);
258                     break;
259             }
260         }
261     }
262     if (need_restart)
263         goto restart;
264
265     if (save_errno)
266         errno = save_errno;
267
268     debug_return_str_masked(pass);
269 }
270
271 /*
272  * Fork a child and exec sudo-askpass to get the password from the user.
273  */
274 static char *
275 sudo_askpass(const char *askpass, const char *prompt)
276 {
277     static char buf[SUDO_CONV_REPL_MAX + 1], *pass;
278     struct sigaction sa, savechld;
279     enum tgetpass_errval errval;
280     int pfd[2], status;
281     pid_t child;
282     debug_decl(sudo_askpass, SUDO_DEBUG_CONV)
283
284     /* Set SIGCHLD handler to default since we call waitpid() below. */
285     memset(&sa, 0, sizeof(sa));
286     sigemptyset(&sa.sa_mask);
287     sa.sa_flags = SA_RESTART;
288     sa.sa_handler = SIG_DFL;
289     (void) sigaction(SIGCHLD, &sa, &savechld);
290
291     if (pipe(pfd) == -1)
292         sudo_fatal(U_("unable to create pipe"));
293
294     child = sudo_debug_fork();
295     if (child == -1)
296         sudo_fatal(U_("unable to fork"));
297
298     if (child == 0) {
299         /* child, point stdout to output side of the pipe and exec askpass */
300         if (dup2(pfd[1], STDOUT_FILENO) == -1) {
301             sudo_warn("dup2");
302             _exit(255);
303         }
304         if (setuid(ROOT_UID) == -1)
305             sudo_warn("setuid(%d)", ROOT_UID);
306         if (setgid(user_details.gid)) {
307             sudo_warn(U_("unable to set gid to %u"), (unsigned int)user_details.gid);
308             _exit(255);
309         }
310         if (setuid(user_details.uid)) {
311             sudo_warn(U_("unable to set uid to %u"), (unsigned int)user_details.uid);
312             _exit(255);
313         }
314         closefrom(STDERR_FILENO + 1);
315         execl(askpass, askpass, prompt, (char *)NULL);
316         sudo_warn(U_("unable to run %s"), askpass);
317         _exit(255);
318     }
319
320     /* Get response from child (askpass). */
321     (void) close(pfd[1]);
322     pass = getln(pfd[0], buf, sizeof(buf), 0, &errval);
323     (void) close(pfd[0]);
324
325     tgetpass_display_error(errval);
326
327     /* Wait for child to exit. */
328     for (;;) {
329         pid_t rv = waitpid(child, &status, 0);
330         if (rv == -1 && errno != EINTR)
331             break;
332         if (rv != -1 && !WIFSTOPPED(status))
333             break;
334     }
335
336     if (pass == NULL)
337         errno = EINTR;  /* make cancel button simulate ^C */
338
339     /* Restore saved SIGCHLD handler. */
340     (void) sigaction(SIGCHLD, &savechld, NULL);
341
342     debug_return_str_masked(pass);
343 }
344
345 extern int sudo_term_eof, sudo_term_erase, sudo_term_kill;
346
347 static char *
348 getln(int fd, char *buf, size_t bufsiz, int feedback,
349     enum tgetpass_errval *errval)
350 {
351     size_t left = bufsiz;
352     ssize_t nr = -1;
353     char *cp = buf;
354     char c = '\0';
355     debug_decl(getln, SUDO_DEBUG_CONV)
356
357     *errval = TGP_ERRVAL_NOERROR;
358
359     if (left == 0) {
360         *errval = TGP_ERRVAL_READERROR;
361         errno = EINVAL;
362         debug_return_str(NULL);         /* sanity */
363     }
364
365     while (--left) {
366         nr = read(fd, &c, 1);
367         if (nr != 1 || c == '\n' || c == '\r')
368             break;
369         if (feedback) {
370             if (c == sudo_term_eof) {
371                 nr = 0;
372                 break;
373             } else if (c == sudo_term_kill) {
374                 while (cp > buf) {
375                     if (write(fd, "\b \b", 3) == -1)
376                         break;
377                     --cp;
378                 }
379                 left = bufsiz;
380                 continue;
381             } else if (c == sudo_term_erase) {
382                 if (cp > buf) {
383                     if (write(fd, "\b \b", 3) == -1)
384                         break;
385                     --cp;
386                     left++;
387                 }
388                 continue;
389             }
390             ignore_result(write(fd, "*", 1));
391         }
392         *cp++ = c;
393     }
394     *cp = '\0';
395     if (feedback) {
396         /* erase stars */
397         while (cp > buf) {
398             if (write(fd, "\b \b", 3) == -1)
399                 break;
400             --cp;
401         }
402     }
403
404     switch (nr) {
405     case -1:
406         /* Read error */
407         if (errno == EINTR) {
408             if (signo[SIGALRM] == 1)
409                 *errval = TGP_ERRVAL_TIMEOUT;
410         } else {
411             *errval = TGP_ERRVAL_READERROR;
412         }
413         debug_return_str(NULL);
414     case 0:
415         /* EOF is only an error if no bytes were read. */
416         if (left == bufsiz - 1) {
417             *errval = TGP_ERRVAL_NOPASSWORD;
418             debug_return_str(NULL);
419         }
420         /* FALLTHROUGH */
421     default:
422         debug_return_str_masked(buf);
423     }
424 }
425
426 static void
427 tgetpass_handler(int s)
428 {
429     signo[s] = 1;
430 }
431
432 static bool
433 tty_present(void)
434 {
435 #if defined(HAVE_KINFO_PROC2_NETBSD) || defined(HAVE_KINFO_PROC_OPENBSD) || defined(HAVE_KINFO_PROC_FREEBSD) || defined(HAVE_KINFO_PROC_44BSD) || defined(HAVE_STRUCT_PSINFO_PR_TTYDEV) || defined(HAVE_PSTAT_GETPROC) || defined(__linux__)
436     debug_decl(tty_present, SUDO_DEBUG_UTIL)
437     debug_return_bool(user_details.tty != NULL);
438 #else
439     int fd;
440     debug_decl(tty_present, SUDO_DEBUG_UTIL)
441
442     if ((fd = open(_PATH_TTY, O_RDWR)) != -1)
443         close(fd);
444     debug_return_bool(fd != -1);
445 #endif
446 }