f8a9d3e323b284612629f77ad81a3cdb3f8ec87a
[debian/sudo] / src / tgetpass.c
1 /*
2  * Copyright (c) 1996, 1998-2005, 2007-2011
3  *      Todd C. Miller <Todd.Miller@courtesan.com>
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 #ifdef __TANDEM
23 # include <floss.h>
24 #endif
25
26 #include <config.h>
27
28 #include <sys/types.h>
29 #include <sys/param.h>
30 #include <stdio.h>
31 #ifdef STDC_HEADERS
32 # include <stdlib.h>
33 # include <stddef.h>
34 #else
35 # ifdef HAVE_STDLIB_H
36 #  include <stdlib.h>
37 # endif
38 #endif /* STDC_HEADERS */
39 #ifdef HAVE_STRING_H
40 # if defined(HAVE_MEMORY_H) && !defined(STDC_HEADERS)
41 #  include <memory.h>
42 # endif
43 # include <string.h>
44 #endif /* HAVE_STRING_H */
45 #ifdef HAVE_STRINGS_H
46 # include <strings.h>
47 #endif /* HAVE_STRINGS_H */
48 #ifdef HAVE_UNISTD_H
49 # include <unistd.h>
50 #endif /* HAVE_UNISTD_H */
51 #include <pwd.h>
52 #include <errno.h>
53 #include <signal.h>
54 #include <fcntl.h>
55
56 #include "sudo.h"
57
58 static volatile sig_atomic_t signo[NSIG];
59
60 static void handler(int);
61 static char *getln(int, char *, size_t, int);
62 static char *sudo_askpass(const char *, const char *);
63
64 #ifdef _PATH_SUDO_ASKPASS
65 const char *askpass_path = _PATH_SUDO_ASKPASS;
66 #else
67 const char *askpass_path;
68 #endif
69
70 /*
71  * Like getpass(3) but with timeout and echo flags.
72  */
73 char *
74 tgetpass(const char *prompt, int timeout, int flags)
75 {
76     sigaction_t sa, savealrm, saveint, savehup, savequit, saveterm;
77     sigaction_t savetstp, savettin, savettou, savepipe;
78     char *pass;
79     static const char *askpass;
80     static char buf[SUDO_PASS_MAX + 1];
81     int i, input, output, save_errno, neednl = 0, need_restart;
82     debug_decl(tgetpass, SUDO_DEBUG_CONV)
83
84     (void) fflush(stdout);
85
86     if (askpass == NULL) {
87         askpass = getenv("SUDO_ASKPASS");
88         if (askpass == NULL || *askpass == '\0')
89             askpass = askpass_path;
90     }
91
92     /* If no tty present and we need to disable echo, try askpass. */
93     if (!ISSET(flags, TGP_STDIN|TGP_ECHO|TGP_ASKPASS|TGP_NOECHO_TRY) &&
94         !tty_present()) {
95         if (askpass == NULL || getenv("DISPLAY") == NULL) {
96             warningx(_("no tty present and no askpass program specified"));
97             debug_return_str(NULL);
98         }
99         SET(flags, TGP_ASKPASS);
100     }
101
102     /* If using a helper program to get the password, run it instead. */
103     if (ISSET(flags, TGP_ASKPASS)) {
104         if (askpass == NULL || *askpass == '\0')
105             errorx(1, _("no askpass program specified, try setting SUDO_ASKPASS"));
106         debug_return_str_masked(sudo_askpass(askpass, prompt));
107     }
108
109 restart:
110     for (i = 0; i < NSIG; i++)
111         signo[i] = 0;
112     pass = NULL;
113     save_errno = 0;
114     need_restart = 0;
115     /* Open /dev/tty for reading/writing if possible else use stdin/stderr. */
116     if (ISSET(flags, TGP_STDIN) ||
117         (input = output = open(_PATH_TTY, O_RDWR|O_NOCTTY)) == -1) {
118         input = STDIN_FILENO;
119         output = STDERR_FILENO;
120     }
121
122     /*
123      * If we are using a tty but are not the foreground pgrp this will
124      * generate SIGTTOU, so do it *before* installing the signal handlers.
125      */
126     if (!ISSET(flags, TGP_ECHO)) {
127         if (ISSET(flags, TGP_MASK))
128             neednl = term_cbreak(input);
129         else
130             neednl = term_noecho(input);
131     }
132
133     /*
134      * Catch signals that would otherwise cause the user to end
135      * up with echo turned off in the shell.
136      */
137     zero_bytes(&sa, sizeof(sa));
138     sigemptyset(&sa.sa_mask);
139     sa.sa_flags = SA_INTERRUPT; /* don't restart system calls */
140     sa.sa_handler = handler;
141     (void) sigaction(SIGALRM, &sa, &savealrm);
142     (void) sigaction(SIGINT, &sa, &saveint);
143     (void) sigaction(SIGHUP, &sa, &savehup);
144     (void) sigaction(SIGQUIT, &sa, &savequit);
145     (void) sigaction(SIGTERM, &sa, &saveterm);
146     (void) sigaction(SIGTSTP, &sa, &savetstp);
147     (void) sigaction(SIGTTIN, &sa, &savettin);
148     (void) sigaction(SIGTTOU, &sa, &savettou);
149
150     /* Ignore SIGPIPE in case stdin is a pipe and TGP_STDIN is set */
151     sa.sa_handler = SIG_IGN;
152     (void) sigaction(SIGPIPE, &sa, &savepipe);
153
154     if (prompt) {
155         if (write(output, prompt, strlen(prompt)) == -1)
156             goto restore;
157     }
158
159     if (timeout > 0)
160         alarm(timeout);
161     pass = getln(input, buf, sizeof(buf), ISSET(flags, TGP_MASK));
162     alarm(0);
163     save_errno = errno;
164
165     if (neednl || pass == NULL) {
166         if (write(output, "\n", 1) == -1)
167             goto restore;
168     }
169
170 restore:
171     /* Restore old tty settings and signals. */
172     if (!ISSET(flags, TGP_ECHO))
173         term_restore(input, 1);
174     (void) sigaction(SIGALRM, &savealrm, NULL);
175     (void) sigaction(SIGINT, &saveint, NULL);
176     (void) sigaction(SIGHUP, &savehup, NULL);
177     (void) sigaction(SIGQUIT, &savequit, NULL);
178     (void) sigaction(SIGTERM, &saveterm, NULL);
179     (void) sigaction(SIGTSTP, &savetstp, NULL);
180     (void) sigaction(SIGTTIN, &savettin, NULL);
181     (void) sigaction(SIGTTOU, &savettou, NULL);
182     (void) sigaction(SIGTTOU, &savepipe, NULL);
183     if (input != STDIN_FILENO)
184         (void) close(input);
185
186     /*
187      * If we were interrupted by a signal, resend it to ourselves
188      * now that we have restored the signal handlers.
189      */
190     for (i = 0; i < NSIG; i++) {
191         if (signo[i]) {
192             kill(getpid(), i);
193             switch (i) {
194                 case SIGTSTP:
195                 case SIGTTIN:
196                 case SIGTTOU:
197                     need_restart = 1;
198                     break;
199             }
200         }
201     }
202     if (need_restart)
203         goto restart;
204
205     if (save_errno)
206         errno = save_errno;
207
208     debug_return_str_masked(pass);
209 }
210
211 /*
212  * Fork a child and exec sudo-askpass to get the password from the user.
213  */
214 static char *
215 sudo_askpass(const char *askpass, const char *prompt)
216 {
217     static char buf[SUDO_PASS_MAX + 1], *pass;
218     sigaction_t sa, saved_sa_pipe;
219     int pfd[2];
220     pid_t pid;
221     debug_decl(sudo_askpass, SUDO_DEBUG_CONV)
222
223     if (pipe(pfd) == -1)
224         error(1, _("unable to create pipe"));
225
226     if ((pid = fork()) == -1)
227         error(1, _("unable to fork"));
228
229     if (pid == 0) {
230         /* child, point stdout to output side of the pipe and exec askpass */
231         if (dup2(pfd[1], STDOUT_FILENO) == -1) {
232             warning("dup2");
233             _exit(255);
234         }
235         (void) setuid(ROOT_UID);
236         if (setgid(user_details.gid)) {
237             warning(_("unable to set gid to %u"), (unsigned int)user_details.gid);
238             _exit(255);
239         }
240         if (setuid(user_details.uid)) {
241             warning(_("unable to set uid to %u"), (unsigned int)user_details.uid);
242             _exit(255);
243         }
244         closefrom(STDERR_FILENO + 1);
245         execl(askpass, askpass, prompt, (char *)NULL);
246         warning(_("unable to run %s"), askpass);
247         _exit(255);
248     }
249
250     /* Ignore SIGPIPE in case child exits prematurely */
251     zero_bytes(&sa, sizeof(sa));
252     sigemptyset(&sa.sa_mask);
253     sa.sa_flags = SA_INTERRUPT;
254     sa.sa_handler = SIG_IGN;
255     (void) sigaction(SIGPIPE, &sa, &saved_sa_pipe);
256
257     /* Get response from child (askpass) and restore SIGPIPE handler */
258     (void) close(pfd[1]);
259     pass = getln(pfd[0], buf, sizeof(buf), 0);
260     (void) close(pfd[0]);
261     (void) sigaction(SIGPIPE, &saved_sa_pipe, NULL);
262
263     debug_return_str_masked(pass);
264 }
265
266 extern int term_erase, term_kill;
267
268 static char *
269 getln(int fd, char *buf, size_t bufsiz, int feedback)
270 {
271     size_t left = bufsiz;
272     ssize_t nr = -1;
273     char *cp = buf;
274     char c = '\0';
275     debug_decl(getln, SUDO_DEBUG_CONV)
276
277     if (left == 0) {
278         errno = EINVAL;
279         debug_return_str(NULL);         /* sanity */
280     }
281
282     while (--left) {
283         nr = read(fd, &c, 1);
284         if (nr != 1 || c == '\n' || c == '\r')
285             break;
286         if (feedback) {
287             if (c == term_kill) {
288                 while (cp > buf) {
289                     if (write(fd, "\b \b", 3) == -1)
290                         break;
291                     --cp;
292                 }
293                 left = bufsiz;
294                 continue;
295             } else if (c == term_erase) {
296                 if (cp > buf) {
297                     if (write(fd, "\b \b", 3) == -1)
298                         break;
299                     --cp;
300                     left++;
301                 }
302                 continue;
303             }
304             if (write(fd, "*", 1) == -1)
305                 /* shut up glibc */;
306         }
307         *cp++ = c;
308     }
309     *cp = '\0';
310     if (feedback) {
311         /* erase stars */
312         while (cp > buf) {
313             if (write(fd, "\b \b", 3) == -1)
314                 break;
315             --cp;
316         }
317     }
318
319     debug_return_str_masked(nr == 1 ? buf : NULL);
320 }
321
322 static void
323 handler(int s)
324 {
325     if (s != SIGALRM)
326         signo[s] = 1;
327 }
328
329 int
330 tty_present(void)
331 {
332     int fd;
333     debug_decl(tty_present, SUDO_DEBUG_UTIL)
334
335     if ((fd = open(_PATH_TTY, O_RDWR|O_NOCTTY)) != -1)
336         close(fd);
337     debug_return_bool(fd != -1);
338 }