go back to using explicit install calls in rules due to renaming required
[debian/sudo] / sudo.c
1 /*
2  * Copyright (c) 1993-1996, 1998-2010 Todd C. Miller <Todd.Miller@courtesan.com>
3  *
4  * Permission to use, copy, modify, and distribute this software for any
5  * purpose with or without fee is hereby granted, provided that the above
6  * copyright notice and this permission notice appear in all copies.
7  *
8  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15  *
16  * Sponsored in part by the Defense Advanced Research Projects
17  * Agency (DARPA) and Air Force Research Laboratory, Air Force
18  * Materiel Command, USAF, under agreement number F39502-99-1-0512.
19  *
20  * For a brief history of sudo, please see the HISTORY file included
21  * with this distribution.
22  */
23
24 #define _SUDO_MAIN
25
26 #ifdef __TANDEM
27 # include <floss.h>
28 #endif
29
30 #include <config.h>
31
32 #include <sys/types.h>
33 #include <sys/stat.h>
34 #include <sys/wait.h>
35 #include <sys/param.h>
36 #include <sys/socket.h>
37 #ifdef HAVE_SETRLIMIT
38 # include <sys/time.h>
39 # include <sys/resource.h>
40 #endif
41 #include <stdio.h>
42 #ifdef STDC_HEADERS
43 # include <stdlib.h>
44 # include <stddef.h>
45 #else
46 # ifdef HAVE_STDLIB_H
47 #  include <stdlib.h>
48 # endif
49 #endif /* STDC_HEADERS */
50 #ifdef HAVE_STRING_H
51 # if defined(HAVE_MEMORY_H) && !defined(STDC_HEADERS)
52 #  include <memory.h>
53 # endif
54 # include <string.h>
55 #endif /* HAVE_STRING_H */
56 #ifdef HAVE_STRINGS_H
57 # include <strings.h>
58 #endif /* HAVE_STRINGS_H */
59 #ifdef HAVE_UNISTD_H
60 # include <unistd.h>
61 #endif /* HAVE_UNISTD_H */
62 #include <pwd.h>
63 #include <ctype.h>
64 #include <errno.h>
65 #include <fcntl.h>
66 #include <signal.h>
67 #include <grp.h>
68 #if TIME_WITH_SYS_TIME
69 # include <time.h>
70 #endif
71 #ifdef HAVE_SETLOCALE
72 # include <locale.h>
73 #endif
74 #include <netinet/in.h>
75 #include <netdb.h>
76 #if defined(HAVE_GETPRPWNAM) && defined(HAVE_SET_AUTH_PARAMETERS)
77 # ifdef __hpux
78 #  undef MAXINT
79 #  include <hpsecurity.h>
80 # else
81 #  include <sys/security.h>
82 # endif /* __hpux */
83 # include <prot.h>
84 #endif /* HAVE_GETPRPWNAM && HAVE_SET_AUTH_PARAMETERS */
85 #ifdef HAVE_LOGIN_CAP_H
86 # include <login_cap.h>
87 # ifndef LOGIN_DEFROOTCLASS
88 #  define LOGIN_DEFROOTCLASS    "daemon"
89 # endif
90 #endif
91 #ifdef HAVE_PROJECT_H
92 # include <project.h>
93 # include <sys/task.h>
94 #endif
95 #ifdef HAVE_MBR_CHECK_MEMBERSHIP
96 # include <membership.h>
97 #endif
98
99 #include "sudo.h"
100 #include "lbuf.h"
101 #include "interfaces.h"
102 #include <sudo_usage.h>
103
104 #ifdef USING_NONUNIX_GROUPS
105 # include "nonunix.h"
106 #endif
107
108 #if defined(HAVE_PAM) && !defined(NO_PAM_SESSION)
109 # define CMND_WAIT      TRUE
110 #else
111 # define CMND_WAIT      FALSE
112 #endif
113
114 /*
115  * Prototypes
116  */
117 static void init_vars                   __P((char **));
118 static int set_cmnd                     __P((int));
119 static void initial_setup               __P((void));
120 static void set_loginclass              __P((struct passwd *));
121 static void set_project                 __P((struct passwd *));
122 static void set_runasgr                 __P((char *));
123 static void set_runaspw                 __P((char *));
124 static void show_version                __P((void));
125 static struct passwd *get_authpw        __P((void));
126 static void create_admin_success_flag   __P((void));
127 extern int sudo_edit                    __P((int, char **, char **));
128 int run_command __P((const char *path, char *argv[], char *envp[], uid_t uid, int dowait)); /* XXX should be in sudo.h */
129
130 /*
131  * Globals
132  */
133 int Argc, NewArgc;
134 char **Argv, **NewArgv;
135 char *prev_user;
136 int user_closefrom = -1;
137 struct sudo_user sudo_user;
138 struct passwd *auth_pw, *list_pw;
139 struct interface *interfaces;
140 int num_interfaces;
141 int tgetpass_flags;
142 int long_list;
143 uid_t timestamp_uid;
144 extern int errorlineno;
145 extern int parse_error;
146 extern char *errorfile;
147 #if defined(RLIMIT_CORE) && !defined(SUDO_DEVEL)
148 static struct rlimit corelimit;
149 #endif /* RLIMIT_CORE && !SUDO_DEVEL */
150 #if defined(__linux__)
151 static struct rlimit nproclimit;
152 #endif
153 #ifdef HAVE_LOGIN_CAP_H
154 login_cap_t *lc;
155 #endif /* HAVE_LOGIN_CAP_H */
156 sigaction_t saved_sa_int, saved_sa_quit, saved_sa_tstp;
157 char *runas_user;
158 char *runas_group;
159 static struct sudo_nss_list *snl;
160 int sudo_mode;
161
162 /* For getopt(3) */
163 extern char *optarg;
164 extern int optind;
165
166 int
167 main(argc, argv, envp)
168     int argc;
169     char *argv[];
170     char *envp[];
171 {
172     int sources = 0, validated;
173     int fd, cmnd_status, pwflag, rc = 0;
174     sigaction_t sa;
175     struct sudo_nss *nss;
176 #if defined(SUDO_DEVEL) && defined(__OpenBSD__)
177     extern char *malloc_options;
178     malloc_options = "AFGJPR";
179 #endif
180
181 #ifdef HAVE_SETLOCALE
182     setlocale(LC_ALL, "");
183 #endif
184
185     Argv = argv;
186     if ((Argc = argc) < 1)
187         usage(1);
188
189     /* Must be done as the first thing... */
190 #if defined(HAVE_GETPRPWNAM) && defined(HAVE_SET_AUTH_PARAMETERS)
191     (void) set_auth_parameters(Argc, Argv);
192 # ifdef HAVE_INITPRIVS
193     initprivs();
194 # endif
195 #endif /* HAVE_GETPRPWNAM && HAVE_SET_AUTH_PARAMETERS */
196
197     if (geteuid() != 0)
198         errorx(1, "must be setuid root");
199
200     /*
201      * Signal setup:
202      *  Ignore keyboard-generated signals so the user cannot interrupt
203      *  us at some point and avoid the logging.
204      *  Install handler to wait for children when they exit.
205      */
206     zero_bytes(&sa, sizeof(sa));
207     sigemptyset(&sa.sa_mask);
208     sa.sa_flags = SA_RESTART;
209     sa.sa_handler = SIG_IGN;
210     (void) sigaction(SIGINT, &sa, &saved_sa_int);
211     (void) sigaction(SIGQUIT, &sa, &saved_sa_quit);
212     (void) sigaction(SIGTSTP, &sa, &saved_sa_tstp);
213
214     /* Initialize environment functions (including replacements). */
215     env_init(FALSE);
216
217     /*
218      * Turn off core dumps and make sure fds 0-2 are open.
219      */
220     initial_setup();
221     sudo_setpwent();
222     sudo_setgrent();
223
224     /* Parse our arguments. */
225     sudo_mode = parse_args(Argc, Argv);
226
227     /* Setup defaults data structures. */
228     init_defaults();
229
230     /* Load the list of local ip addresses and netmasks.  */
231     load_interfaces();
232
233     pwflag = 0;
234     if (ISSET(sudo_mode, MODE_SHELL))
235         user_cmnd = "shell";
236     else if (ISSET(sudo_mode, MODE_EDIT))
237         user_cmnd = "sudoedit";
238     else {
239         switch (sudo_mode) {
240             case MODE_VERSION:
241                 show_version();
242                 break;
243             case MODE_HELP:
244                 usage(0);
245                 break;
246             case MODE_VALIDATE:
247             case MODE_VALIDATE|MODE_INVALIDATE:
248                 user_cmnd = "validate";
249                 pwflag = I_VERIFYPW;
250                 break;
251             case MODE_KILL:
252             case MODE_INVALIDATE:
253                 user_cmnd = "kill";
254                 pwflag = -1;
255                 break;
256             case MODE_LISTDEFS:
257                 list_options();
258                 exit(0);
259                 break;
260             case MODE_LIST:
261             case MODE_LIST|MODE_INVALIDATE:
262                 user_cmnd = "list";
263                 pwflag = I_LISTPW;
264                 break;
265             case MODE_CHECK:
266             case MODE_CHECK|MODE_INVALIDATE:
267                 pwflag = I_LISTPW;
268                 break;
269         }
270     }
271
272     /* Must have a command to run... */
273     if (user_cmnd == NULL && NewArgc == 0)
274         usage(1);
275
276     init_vars(envp);                    /* XXX - move this later? */
277
278 #ifdef USING_NONUNIX_GROUPS
279     sudo_nonunix_groupcheck_init();     /* initialise nonunix groups impl */
280 #endif /* USING_NONUNIX_GROUPS */
281
282     /* Parse nsswitch.conf for sudoers order. */
283     snl = sudo_read_nss();
284
285     /* Open and parse sudoers, set global defaults */
286     tq_foreach_fwd(snl, nss) {
287         if (nss->open(nss) == 0 && nss->parse(nss) == 0) {
288             sources++;
289             if (nss->setdefs(nss) != 0)
290                 log_error(NO_STDERR|NO_EXIT, "problem with defaults entries");
291         }
292     }
293     if (sources == 0)
294         log_error(0, "no valid sudoers sources found, quitting");
295
296     /* XXX - collect post-sudoers parse settings into a function */
297
298     /*
299      * Set runas passwd/group entries based on command line or sudoers.
300      * Note that if runas_group was specified without runas_user we
301      * defer setting runas_pw so the match routines know to ignore it.
302      */
303     if (runas_group != NULL) {
304         set_runasgr(runas_group);
305         if (runas_user != NULL)
306             set_runaspw(runas_user);
307     } else
308         set_runaspw(runas_user ? runas_user : def_runas_default);
309
310     if (!update_defaults(SETDEF_RUNAS))
311         log_error(NO_STDERR|NO_EXIT, "problem with defaults entries");
312
313     if (def_fqdn)
314         set_fqdn();     /* deferred until after sudoers is parsed */
315
316     /* Set login class if applicable. */
317     set_loginclass(sudo_user.pw);
318
319     /* Update initial shell now that runas is set. */
320     if (ISSET(sudo_mode, MODE_LOGIN_SHELL))
321         NewArgv[0] = runas_pw->pw_shell;
322
323     /* This goes after sudoers is parsed since it may have timestamp options. */
324     if (sudo_mode == MODE_KILL || sudo_mode == MODE_INVALIDATE) {
325         remove_timestamp((sudo_mode == MODE_KILL));
326         cleanup(0);
327         exit(0);
328     }
329
330     /* Is root even allowed to run sudo? */
331     if (user_uid == 0 && !def_root_sudo) {
332         (void) fprintf(stderr,
333             "Sorry, %s has been configured to not allow root to run it.\n",
334             getprogname());
335         exit(1);
336     }
337
338     /* Check for -C overriding def_closefrom. */
339     if (user_closefrom >= 0 && user_closefrom != def_closefrom) {
340         if (!def_closefrom_override)
341             errorx(1, "you are not permitted to use the -C option");
342         else
343             def_closefrom = user_closefrom;
344     }
345
346     cmnd_status = set_cmnd(sudo_mode);
347
348 #ifdef HAVE_SETLOCALE
349     if (!setlocale(LC_ALL, def_sudoers_locale)) {
350         warningx("unable to set locale to \"%s\", using \"C\"",
351             def_sudoers_locale);
352         setlocale(LC_ALL, "C");
353     }
354 #endif
355
356     validated = FLAG_NO_USER | FLAG_NO_HOST;
357     tq_foreach_fwd(snl, nss) {
358         validated = nss->lookup(nss, validated, pwflag);
359
360         if (ISSET(validated, VALIDATE_OK)) {
361             /* Handle "= auth" in netsvc.conf */
362             if (nss->ret_if_found)
363                 break;
364         } else {
365             /* Handle [NOTFOUND=return] */
366             if (nss->ret_if_notfound)
367                 break;
368         }
369     }
370
371     if (safe_cmnd == NULL)
372         safe_cmnd = estrdup(user_cmnd);
373
374 #ifdef HAVE_SETLOCALE
375     setlocale(LC_ALL, "");
376 #endif
377
378     /* If only a group was specified, set runas_pw based on invoking user. */
379     if (runas_pw == NULL)
380         set_runaspw(user_name);
381
382     /*
383      * Look up the timestamp dir owner if one is specified.
384      */
385     if (def_timestampowner) {
386         struct passwd *pw;
387
388         if (*def_timestampowner == '#')
389             pw = sudo_getpwuid(atoi(def_timestampowner + 1));
390         else
391             pw = sudo_getpwnam(def_timestampowner);
392         if (!pw)
393             log_error(0, "timestamp owner (%s): No such user",
394                 def_timestampowner);
395         timestamp_uid = pw->pw_uid;
396     }
397
398     /* If given the -P option, set the "preserve_groups" flag. */
399     if (ISSET(sudo_mode, MODE_PRESERVE_GROUPS))
400         def_preserve_groups = TRUE;
401
402     /* If no command line args and "set_home" is not set, error out. */
403     if (ISSET(sudo_mode, MODE_IMPLIED_SHELL) && !def_shell_noargs)
404         usage(1);
405
406     /* Bail if a tty is required and we don't have one.  */
407     if (def_requiretty) {
408         if ((fd = open(_PATH_TTY, O_RDWR|O_NOCTTY)) == -1) {
409             audit_failure(NewArgv, "no tty");
410             log_error(NO_MAIL, "sorry, you must have a tty to run sudo");
411         } else
412             (void) close(fd);
413     }
414
415     /* Use askpass value from sudoers unless user specified their own. */
416     if (def_askpass && !user_askpass)
417         user_askpass = def_askpass;
418
419     /*
420      * We don't reset the environment for sudoedit or if the user
421      * specified the -E command line flag and they have setenv privs.
422      */
423     if (ISSET(sudo_mode, MODE_EDIT) ||
424         (ISSET(sudo_mode, MODE_PRESERVE_ENV) && def_setenv))
425         def_env_reset = FALSE;
426
427     /* Build a new environment that avoids any nasty bits. */
428     rebuild_env(def_noexec);
429
430     /* Fill in passwd struct based on user we are authenticating as.  */
431     auth_pw = get_authpw();
432
433     /* Require a password if sudoers says so.  */
434     if (def_authenticate)
435         check_user(validated, sudo_mode);
436
437     /* If run as root with SUDO_USER set, set sudo_user.pw to that user. */
438     /* XXX - causes confusion when root is not listed in sudoers */
439     if (sudo_mode & (MODE_RUN | MODE_EDIT) && prev_user != NULL) {
440         if (user_uid == 0 && strcmp(prev_user, "root") != 0) {
441             struct passwd *pw;
442
443             if ((pw = sudo_getpwnam(prev_user)) != NULL) {
444                     sudo_user.pw = pw;
445 #ifdef HAVE_MBR_CHECK_MEMBERSHIP
446                     mbr_uid_to_uuid(user_uid, user_uuid);
447 #endif
448             }
449         }
450     }
451
452     if (ISSET(validated, VALIDATE_OK)) {
453         /* Create Ubuntu-style dot file to indicate sudo was successful. */
454         create_admin_success_flag();
455
456         /* Finally tell the user if the command did not exist. */
457         if (cmnd_status == NOT_FOUND_DOT) {
458             audit_failure(NewArgv, "command in current directory");
459             errorx(1, "ignoring `%s' found in '.'\nUse `sudo ./%s' if this is the `%s' you wish to run.", user_cmnd, user_cmnd, user_cmnd);
460         } else if (cmnd_status == NOT_FOUND) {
461             audit_failure(NewArgv, "%s: command not found", user_cmnd);
462             errorx(1, "%s: command not found", user_cmnd);
463         }
464
465         /* If user specified env vars make sure sudoers allows it. */
466         if (ISSET(sudo_mode, MODE_RUN) && !def_setenv) {
467             if (ISSET(sudo_mode, MODE_PRESERVE_ENV))
468                 log_error(NO_MAIL,
469                     "sorry, you are not allowed to preserve the environment");
470             else
471                 validate_env_vars(sudo_user.env_vars);
472         }
473
474 #ifdef _PATH_SUDO_IO_LOGDIR
475         /* Get next session ID so we can log it. */
476         if (ISSET(sudo_mode, (MODE_RUN | MODE_EDIT)) && (def_log_input || def_log_output))
477             io_nextid();
478 #endif
479         log_allowed(validated);
480         if (ISSET(sudo_mode, MODE_CHECK))
481             rc = display_cmnd(snl, list_pw ? list_pw : sudo_user.pw);
482         else if (ISSET(sudo_mode, MODE_LIST))
483             display_privs(snl, list_pw ? list_pw : sudo_user.pw);
484
485         /* Cleanup sudoers sources */
486         tq_foreach_fwd(snl, nss)
487             nss->close(nss);
488
489 #ifdef USING_NONUNIX_GROUPS
490         /* Finished with the groupcheck code */
491         sudo_nonunix_groupcheck_cleanup();
492 #endif
493
494         /* Deferred exit due to sudo_ldap_close() */
495         if (ISSET(sudo_mode, (MODE_VALIDATE|MODE_CHECK|MODE_LIST)))
496             exit(rc);
497
498         /* Must audit before uid change. */
499         audit_success(NewArgv);
500
501         if (ISSET(sudo_mode, MODE_LOGIN_SHELL)) {
502             char *p;
503
504             /* Convert /bin/sh -> -sh so shell knows it is a login shell */
505             if ((p = strrchr(NewArgv[0], '/')) == NULL)
506                 p = NewArgv[0];
507             *p = '-';
508             NewArgv[0] = p;
509
510 #if defined(__linux__) || defined(_AIX)
511             /* Insert system-wide environment variables. */
512             read_env_file(_PATH_ENVIRONMENT, TRUE);
513 #endif
514         }
515
516         if (ISSET(sudo_mode, MODE_RUN)) {
517             /* Insert system-wide environment variables. */
518             if (def_env_file)
519                 read_env_file(def_env_file, FALSE);
520
521             /* Insert user-specified environment variables. */
522             insert_env_vars(sudo_user.env_vars);
523         }
524
525         /* Restore signal handlers before we exec. */
526         (void) sigaction(SIGINT, &saved_sa_int, NULL);
527         (void) sigaction(SIGQUIT, &saved_sa_quit, NULL);
528         (void) sigaction(SIGTSTP, &saved_sa_tstp, NULL);
529
530         if (ISSET(sudo_mode, MODE_EDIT)) {
531             exit(sudo_edit(NewArgc, NewArgv, envp));
532         } else {
533             exit(run_command(safe_cmnd, NewArgv, env_get(), runas_pw->pw_uid,
534                 CMND_WAIT));
535         }
536     } else if (ISSET(validated, FLAG_NO_USER | FLAG_NO_HOST)) {
537         audit_failure(NewArgv, "No user or host");
538         log_denial(validated, 1);
539         exit(1);
540     } else {
541         if (def_path_info) {
542             /*
543              * We'd like to not leak path info at all here, but that can
544              * *really* confuse the users.  To really close the leak we'd
545              * have to say "not allowed to run foo" even when the problem
546              * is just "no foo in path" since the user can trivially set
547              * their path to just contain a single dir.
548              */
549             log_denial(validated,
550                 !(cmnd_status == NOT_FOUND_DOT || cmnd_status == NOT_FOUND));
551             if (cmnd_status == NOT_FOUND)
552                 warningx("%s: command not found", user_cmnd);
553             else if (cmnd_status == NOT_FOUND_DOT)
554                 warningx("ignoring `%s' found in '.'\nUse `sudo ./%s' if this is the `%s' you wish to run.", user_cmnd, user_cmnd, user_cmnd);
555         } else {
556             /* Just tell the user they are not allowed to run foo. */
557             log_denial(validated, 1);
558         }
559         audit_failure(NewArgv, "validation failure");
560         exit(1);
561     }
562     exit(0);    /* not reached */
563 }
564
565 /*
566  * Initialize timezone, set umask, fill in ``sudo_user'' struct and
567  * load the ``interfaces'' array.
568  */
569 static void
570 init_vars(envp)
571     char **envp;
572 {
573     char *p, **ep, thost[MAXHOSTNAMELEN + 1];
574     int nohostname;
575
576     /* Sanity check command from user. */
577     if (user_cmnd == NULL && strlen(NewArgv[0]) >= PATH_MAX)
578         errorx(1, "%s: File name too long", NewArgv[0]);
579
580 #ifdef HAVE_TZSET
581     (void) tzset();             /* set the timezone if applicable */
582 #endif /* HAVE_TZSET */
583
584     /* Default value for cmnd and cwd, overridden later. */
585     if (user_cmnd == NULL)
586         user_cmnd = NewArgv[0];
587     (void) strlcpy(user_cwd, "unknown", sizeof(user_cwd));
588
589     /*
590      * We avoid gethostbyname() if possible since we don't want
591      * sudo to block if DNS or NIS is hosed.
592      * "host" is the (possibly fully-qualified) hostname and
593      * "shost" is the unqualified form of the hostname.
594      */
595     nohostname = gethostname(thost, sizeof(thost));
596     if (nohostname) {
597         user_host = user_shost = "localhost";
598     } else {
599         thost[sizeof(thost) - 1] = '\0';
600         user_host = estrdup(thost);
601         if ((p = strchr(user_host, '.'))) {
602             *p = '\0';
603             user_shost = estrdup(user_host);
604             *p = '.';
605         } else {
606             user_shost = user_host;
607         }
608     }
609
610     if ((p = ttyname(STDIN_FILENO)) || (p = ttyname(STDOUT_FILENO)) ||
611         (p = ttyname(STDERR_FILENO))) {
612         user_tty = user_ttypath = estrdup(p);
613         if (strncmp(user_tty, _PATH_DEV, sizeof(_PATH_DEV) - 1) == 0)
614             user_tty += sizeof(_PATH_DEV) - 1;
615     } else
616         user_tty = "unknown";
617
618     for (ep = envp; *ep; ep++) {
619         /* XXX - don't fill in if empty string */
620         switch (**ep) {
621             case 'D':
622                 if (strncmp("DISPLAY=", *ep, 8) == 0)
623                     user_display = *ep + 8;
624                 break;
625             case 'K':
626                 if (strncmp("KRB5CCNAME=", *ep, 11) == 0)
627                     user_ccname = *ep + 11;
628                 break;
629             case 'P':
630                 if (strncmp("PATH=", *ep, 5) == 0)
631                     user_path = *ep + 5;
632                 break;
633             case 'S':
634                 if (strncmp("SHELL=", *ep, 6) == 0)
635                     user_shell = *ep + 6;
636                 else if (!user_prompt && strncmp("SUDO_PROMPT=", *ep, 12) == 0)
637                     user_prompt = *ep + 12;
638                 else if (strncmp("SUDO_USER=", *ep, 10) == 0)
639                     prev_user = *ep + 10;
640                 else if (strncmp("SUDO_ASKPASS=", *ep, 13) == 0)
641                     user_askpass = *ep + 13;
642                 break;
643             }
644     }
645
646     /*
647      * Get a local copy of the user's struct passwd with the shadow password
648      * if necessary.  It is assumed that euid is 0 at this point so we
649      * can read the shadow passwd file if necessary.
650      */
651     if ((sudo_user.pw = sudo_getpwuid(getuid())) == NULL) {
652         /* Need to make a fake struct passwd for logging to work. */
653         struct passwd pw;
654         char pw_name[MAX_UID_T_LEN + 1];
655
656         pw.pw_uid = getuid();
657         (void) snprintf(pw_name, sizeof(pw_name), "%lu",
658             (unsigned long) pw.pw_uid);
659         pw.pw_name = pw_name;
660         sudo_user.pw = &pw;
661
662         /*
663          * If we are in -k/-K mode, just spew to stderr.  It is not unusual for
664          * users to place "sudo -k" in a .logout file which can cause sudo to
665          * be run during reboot after the YP/NIS/NIS+/LDAP/etc daemon has died.
666          */
667         if (sudo_mode == MODE_KILL || sudo_mode == MODE_INVALIDATE)
668             errorx(1, "unknown uid: %s", pw_name);
669         log_error(0, "unknown uid: %s", pw_name);
670     }
671 #ifdef HAVE_MBR_CHECK_MEMBERSHIP
672     mbr_uid_to_uuid(user_uid, user_uuid);
673 #endif
674     if (user_shell == NULL || *user_shell == '\0')
675         user_shell = estrdup(sudo_user.pw->pw_shell);
676
677     /* It is now safe to use log_error() and set_perms() */
678
679 #ifdef HAVE_GETGROUPS
680     if ((user_ngroups = getgroups(0, NULL)) > 0) {
681         user_groups = emalloc2(user_ngroups, sizeof(GETGROUPS_T));
682         if (getgroups(user_ngroups, user_groups) < 0)
683             log_error(USE_ERRNO|MSG_ONLY, "can't get group vector");
684     }
685 #endif
686
687     if (nohostname)
688         log_error(USE_ERRNO|MSG_ONLY, "can't get hostname");
689
690     /*
691      * Get current working directory.  Try as user, fall back to root.
692      */
693     set_perms(PERM_USER);
694     if (!getcwd(user_cwd, sizeof(user_cwd))) {
695         set_perms(PERM_ROOT);
696         if (!getcwd(user_cwd, sizeof(user_cwd))) {
697             warningx("cannot get working directory");
698             (void) strlcpy(user_cwd, "unknown", sizeof(user_cwd));
699         }
700     } else
701         set_perms(PERM_ROOT);
702
703     /*
704      * If we were given the '-e', '-i' or '-s' options we need to redo
705      * NewArgv and NewArgc.
706      */
707     if (ISSET(sudo_mode, MODE_EDIT)) {
708         NewArgv--;
709         NewArgc++;
710         NewArgv[0] = "sudoedit";
711     } else if (ISSET(sudo_mode, MODE_SHELL)) {
712         char **av;
713
714         /* Allocate an extra slot for execve() failure (ENOEXEC). */
715         av = (char **) emalloc2(5, sizeof(char *));
716         av++;
717
718         av[0] = user_shell;     /* may be updated later */
719         if (NewArgc > 0) {
720             size_t cmnd_size = 1024;
721             char *cmnd, *src, *dst, **ap;
722
723             cmnd = dst = emalloc(cmnd_size);
724             for (ap = NewArgv; *ap != NULL; ap++) {
725                 for (src = *ap; *src != '\0'; src++) {
726                     /* reserve room for an escaped char + space */
727                     if (cmnd_size < (dst - cmnd) + 3) {
728                         char *new_cmnd;
729                         cmnd_size <<= 1;
730                         new_cmnd = erealloc(cmnd, cmnd_size);
731                         dst = new_cmnd + (dst - cmnd);
732                         cmnd = new_cmnd;
733                     }
734                     if (isalnum((unsigned char)*src) || *src == '_' || *src == '-') {
735                         *dst++ = *src;
736                     } else {
737                         /* quote potential meta character */
738                         *dst++ = '\\';
739                         *dst++ = *src;
740                     }
741                 }
742                 *dst++ = ' ';
743             }
744             if (cmnd != dst)
745                 dst--;  /* replace last space with a NUL */
746             *dst = '\0';
747             av[1] = "-c";
748             av[2] = cmnd;
749             NewArgc = 2;
750         }
751         av[++NewArgc] = NULL;
752         NewArgv = av;
753     }
754 }
755
756 /*
757  * Fill in user_cmnd, user_args, user_base and user_stat variables
758  * and apply any command-specific defaults entries.
759  */
760 static int
761 set_cmnd(sudo_mode)
762     int sudo_mode;
763 {
764     int rval;
765     char *path = user_path;
766
767     /* Set project if applicable. */
768     set_project(runas_pw);
769
770     /* Resolve the path and return. */
771     rval = FOUND;
772     user_stat = emalloc(sizeof(struct stat));
773     if (sudo_mode & (MODE_RUN | MODE_EDIT | MODE_CHECK)) {
774         if (ISSET(sudo_mode, MODE_RUN | MODE_CHECK)) {
775             if (def_secure_path && !user_is_exempt())
776                 path = def_secure_path;
777             set_perms(PERM_RUNAS);
778             rval = find_path(NewArgv[0], &user_cmnd, user_stat, path,
779                 def_ignore_dot);
780             set_perms(PERM_ROOT);
781             if (rval != FOUND) {
782                 /* Failed as root, try as invoking user. */
783                 set_perms(PERM_USER);
784                 rval = find_path(NewArgv[0], &user_cmnd, user_stat, path,
785                     def_ignore_dot);
786                 set_perms(PERM_ROOT);
787             }
788         }
789
790         /* set user_args */
791         if (NewArgc > 1) {
792             char *to, **from;
793             size_t size, n;
794
795             /* If we didn't realloc NewArgv it is contiguous so just count. */
796             if (!ISSET(sudo_mode, MODE_SHELL)) {
797                 size = (size_t) (NewArgv[NewArgc-1] - NewArgv[1]) +
798                         strlen(NewArgv[NewArgc-1]) + 1;
799             } else {
800                 for (size = 0, from = NewArgv + 1; *from; from++)
801                     size += strlen(*from) + 1;
802             }
803
804             /* Alloc and build up user_args. */
805             user_args = (char *) emalloc(size);
806             for (to = user_args, from = NewArgv + 1; *from; from++) {
807                 n = strlcpy(to, *from, size - (to - user_args));
808                 if (n >= size - (to - user_args))
809                     errorx(1, "internal error, init_vars() overflow");
810                 to += n;
811                 *to++ = ' ';
812             }
813             *--to = '\0';
814         }
815     }
816     if ((user_base = strrchr(user_cmnd, '/')) != NULL)
817         user_base++;
818     else
819         user_base = user_cmnd;
820
821     if (!update_defaults(SETDEF_CMND))
822         log_error(NO_STDERR|NO_EXIT, "problem with defaults entries");
823
824     if (!runas_user && !runas_group)
825         set_runaspw(def_runas_default); /* may have been updated above */
826
827     return(rval);
828 }
829
830 /*
831  * Setup the execution environment immediately prior to the call to execve()
832  * Returns TRUE on success and FALSE on failure.
833  */
834 int
835 exec_setup(rbac_enabled, ttyname, ttyfd)
836     int rbac_enabled;
837     const char *ttyname;
838     int ttyfd;
839 {
840     int rval = FALSE;
841
842 #ifdef HAVE_SELINUX
843     if (rbac_enabled) {
844        if (selinux_setup(user_role, user_type, ttyname, ttyfd) == -1)
845            goto done;
846     }
847 #endif
848
849     /* Close the password and group files and free up memory. */
850     sudo_endpwent();
851     sudo_endgrent();
852
853     /*
854      * For sudoedit, the command runas a the user with no additional setup.
855      */
856     if (ISSET(sudo_mode, MODE_EDIT)) {
857         set_perms(PERM_FULL_USER);
858         rval = TRUE;
859         goto done;
860     }
861
862     /*
863      * Set umask based on sudoers.
864      * If user's umask is more restrictive, OR in those bits too
865      * unless umask_override is set.
866      */
867     if (def_umask != 0777) {
868         if (def_umask_override) {
869             umask(def_umask);
870         } else {
871             mode_t mask = umask(def_umask);
872             mask |= def_umask;
873             if (mask != def_umask)
874                 umask(mask);
875         }
876     }
877
878     /* Restore coredumpsize resource limit. */
879 #if defined(RLIMIT_CORE) && !defined(SUDO_DEVEL)
880     (void) setrlimit(RLIMIT_CORE, &corelimit);
881 #endif /* RLIMIT_CORE && !SUDO_DEVEL */
882
883     if (ISSET(sudo_mode, MODE_RUN))
884         set_perms(PERM_FULL_RUNAS);
885
886     if (ISSET(sudo_mode, MODE_LOGIN_SHELL)) {
887         /* Change to target user's homedir. */
888         if (chdir(runas_pw->pw_dir) == -1) {
889             warning("unable to change directory to %s", runas_pw->pw_dir);
890             goto done;
891         }
892     }
893
894     /*
895      * Restore nproc resource limit if pam_limits didn't do it for us.
896      * We must do this *after* the uid change to avoid potential EAGAIN
897      * from setuid().
898      */
899 #if defined(__linux__)
900     {
901         struct rlimit rl;
902         if (getrlimit(RLIMIT_NPROC, &rl) == 0) {
903             if (rl.rlim_cur == RLIM_INFINITY && rl.rlim_max == RLIM_INFINITY)
904                 (void) setrlimit(RLIMIT_NPROC, &nproclimit);
905         }
906     }
907 #endif
908
909     rval = TRUE;
910
911 done:
912     return(rval);
913 }
914
915 /*
916  * Run the command and wait for it to complete.
917  */
918 int
919 run_command(path, argv, envp, uid, dowait)
920     const char *path;
921     char *argv[];
922     char *envp[];
923     uid_t uid;
924     int dowait;
925 {
926     struct command_status cstat;
927     int exitcode = 1;
928
929 #ifdef PROFILING
930     exit(0);
931 #endif
932
933     cstat.type = CMD_INVALID;
934     cstat.val = 0;
935
936     sudo_execve(path, argv, envp, uid, &cstat, dowait,
937         ISSET(sudo_mode, MODE_BACKGROUND));
938
939     switch (cstat.type) {
940     case CMD_ERRNO:
941         /* exec_setup() or execve() returned an error. */
942         warningx("unable to execute %s: %s", path, strerror(cstat.val));
943         exitcode = 127;
944         break;
945     case CMD_WSTATUS:
946         /* Command ran, exited or was killed. */
947         if (WIFEXITED(cstat.val))
948             exitcode = WEXITSTATUS(cstat.val);
949         else if (WIFSIGNALED(cstat.val))
950             exitcode = WTERMSIG(cstat.val) | 128;
951         break;
952     default:
953         warningx("unexpected child termination condition: %d", cstat.type);
954         break;
955     }
956 #ifdef HAVE_PAM
957     pam_end_session();
958 #endif /* HAVE_PAM */
959 #ifdef _PATH_SUDO_IO_LOGDIR
960     io_log_close();
961 #endif
962     return(exitcode);
963 }
964
965 /*
966  * Open sudoers and sanity check mode/owner/type.
967  * Returns a handle to the sudoers file or NULL on error.
968  */
969 FILE *
970 open_sudoers(sudoers, doedit, keepopen)
971     const char *sudoers;
972     int doedit;
973     int *keepopen;
974 {
975     struct stat statbuf;
976     FILE *fp = NULL;
977     int rootstat;
978
979     /*
980      * Fix the mode and group on sudoers file from old default.
981      * Only works if file system is readable/writable by root.
982      */
983     if ((rootstat = stat_sudoers(sudoers, &statbuf)) == 0 &&
984         SUDOERS_UID == statbuf.st_uid && SUDOERS_MODE != 0400 &&
985         (statbuf.st_mode & 0007777) == 0400) {
986
987         if (chmod(sudoers, SUDOERS_MODE) == 0) {
988             warningx("fixed mode on %s", sudoers);
989             SET(statbuf.st_mode, SUDOERS_MODE);
990             if (statbuf.st_gid != SUDOERS_GID) {
991                 if (chown(sudoers, (uid_t) -1, SUDOERS_GID) == 0) {
992                     warningx("set group on %s", sudoers);
993                     statbuf.st_gid = SUDOERS_GID;
994                 } else
995                     warning("unable to set group on %s", sudoers);
996             }
997         } else
998             warning("unable to fix mode on %s", sudoers);
999     }
1000
1001     /*
1002      * Sanity checks on sudoers file.  Must be done as sudoers
1003      * file owner.  We already did a stat as root, so use that
1004      * data if we can't stat as sudoers file owner.
1005      */
1006     set_perms(PERM_SUDOERS);
1007
1008     if (rootstat != 0 && stat_sudoers(sudoers, &statbuf) != 0)
1009         log_error(USE_ERRNO|NO_EXIT, "can't stat %s", sudoers);
1010     else if (!S_ISREG(statbuf.st_mode))
1011         log_error(NO_EXIT, "%s is not a regular file", sudoers);
1012     else if ((statbuf.st_mode & 07777) != SUDOERS_MODE)
1013         log_error(NO_EXIT, "%s is mode 0%o, should be 0%o", sudoers,
1014             (unsigned int) (statbuf.st_mode & 07777),
1015             (unsigned int) SUDOERS_MODE);
1016     else if (statbuf.st_uid != SUDOERS_UID)
1017         log_error(NO_EXIT, "%s is owned by uid %lu, should be %lu", sudoers,
1018             (unsigned long) statbuf.st_uid, (unsigned long) SUDOERS_UID);
1019     else if (statbuf.st_gid != SUDOERS_GID)
1020         log_error(NO_EXIT, "%s is owned by gid %lu, should be %lu", sudoers,
1021             (unsigned long) statbuf.st_gid, (unsigned long) SUDOERS_GID);
1022     else if ((fp = fopen(sudoers, "r")) == NULL)
1023         log_error(USE_ERRNO|NO_EXIT, "can't open %s", sudoers);
1024     else {
1025         /*
1026          * Make sure we can actually read sudoers so we can present the
1027          * user with a reasonable error message (unlike the lexer).
1028          */
1029         if (statbuf.st_size != 0 && fgetc(fp) == EOF) {
1030             log_error(USE_ERRNO|NO_EXIT, "can't read %s", sudoers);
1031             fclose(fp);
1032             fp = NULL;
1033         }
1034     }
1035
1036     if (fp != NULL) {
1037         rewind(fp);
1038         (void) fcntl(fileno(fp), F_SETFD, 1);
1039     }
1040
1041     set_perms(PERM_ROOT);               /* change back to root */
1042     return(fp);
1043 }
1044
1045 /*
1046  * Close all open files (except std*) and turn off core dumps.
1047  * Also sets the set_perms() pointer to the correct function.
1048  */
1049 static void
1050 initial_setup()
1051 {
1052     int miss[3], devnull = -1;
1053 #if defined(__linux__) || (defined(RLIMIT_CORE) && !defined(SUDO_DEVEL))
1054     struct rlimit rl;
1055 #endif
1056
1057 #if defined(__linux__)
1058     /*
1059      * Unlimit the number of processes since Linux's setuid() will
1060      * apply resource limits when changing uid and return EAGAIN if
1061      * nproc would be violated by the uid switch.
1062      */
1063     (void) getrlimit(RLIMIT_NPROC, &nproclimit);
1064     rl.rlim_cur = rl.rlim_max = RLIM_INFINITY;
1065     if (setrlimit(RLIMIT_NPROC, &rl)) {
1066         memcpy(&rl, &nproclimit, sizeof(struct rlimit));
1067         rl.rlim_cur = rl.rlim_max;
1068         (void)setrlimit(RLIMIT_NPROC, &rl);
1069     }
1070 #endif /* __linux__ */
1071 #if defined(RLIMIT_CORE) && !defined(SUDO_DEVEL)
1072     /*
1073      * Turn off core dumps.
1074      */
1075     (void) getrlimit(RLIMIT_CORE, &corelimit);
1076     memcpy(&rl, &corelimit, sizeof(struct rlimit));
1077     rl.rlim_cur = 0;
1078     (void) setrlimit(RLIMIT_CORE, &rl);
1079 #endif /* RLIMIT_CORE && !SUDO_DEVEL */
1080
1081     /*
1082      * stdin, stdout and stderr must be open; set them to /dev/null
1083      * if they are closed and close all other fds.
1084      */
1085     miss[STDIN_FILENO] = fcntl(STDIN_FILENO, F_GETFL, 0) == -1;
1086     miss[STDOUT_FILENO] = fcntl(STDOUT_FILENO, F_GETFL, 0) == -1;
1087     miss[STDERR_FILENO] = fcntl(STDERR_FILENO, F_GETFL, 0) == -1;
1088     if (miss[STDIN_FILENO] || miss[STDOUT_FILENO] || miss[STDERR_FILENO]) {
1089         if ((devnull = open(_PATH_DEVNULL, O_RDWR, 0644)) == -1)
1090             error(1, "unable to open %s", _PATH_DEVNULL);
1091         if (miss[STDIN_FILENO] && dup2(devnull, STDIN_FILENO) == -1)
1092             error(1, "dup2");
1093         if (miss[STDOUT_FILENO] && dup2(devnull, STDOUT_FILENO) == -1)
1094             error(1, "dup2");
1095         if (miss[STDERR_FILENO] && dup2(devnull, STDERR_FILENO) == -1)
1096             error(1, "dup2");
1097         if (devnull > STDERR_FILENO)
1098             close(devnull);
1099     }
1100 }
1101
1102 #ifdef HAVE_LOGIN_CAP_H
1103 static void
1104 set_loginclass(pw)
1105     struct passwd *pw;
1106 {
1107     int errflags;
1108
1109     /*
1110      * Don't make it a fatal error if the user didn't specify the login
1111      * class themselves.  We do this because if login.conf gets
1112      * corrupted we want the admin to be able to use sudo to fix it.
1113      */
1114     if (login_class)
1115         errflags = NO_MAIL|MSG_ONLY;
1116     else
1117         errflags = NO_MAIL|MSG_ONLY|NO_EXIT;
1118
1119     if (login_class && strcmp(login_class, "-") != 0) {
1120         if (user_uid != 0 &&
1121             strcmp(runas_user ? runas_user : def_runas_default, "root") != 0)
1122             errorx(1, "only root can use -c %s", login_class);
1123     } else {
1124         login_class = pw->pw_class;
1125         if (!login_class || !*login_class)
1126             login_class =
1127                 (pw->pw_uid == 0) ? LOGIN_DEFROOTCLASS : LOGIN_DEFCLASS;
1128     }
1129
1130     lc = login_getclass(login_class);
1131     if (!lc || !lc->lc_class || strcmp(lc->lc_class, login_class) != 0) {
1132         log_error(errflags, "unknown login class: %s", login_class);
1133         if (!lc)
1134             lc = login_getclass(NULL);  /* needed for login_getstyle() later */
1135     }
1136 }
1137 #else
1138 static void
1139 set_loginclass(pw)
1140     struct passwd *pw;
1141 {
1142 }
1143 #endif /* HAVE_LOGIN_CAP_H */
1144
1145 #ifdef HAVE_PROJECT_H
1146 static void
1147 set_project(pw)
1148     struct passwd *pw;
1149 {
1150     int errflags = NO_MAIL|MSG_ONLY|NO_EXIT;
1151     int errval;
1152     struct project proj;
1153     struct project *resultp = '\0';
1154     char buf[1024];
1155
1156     /*
1157      * Collect the default project for the user and settaskid
1158      */
1159     setprojent();
1160     if (resultp = getdefaultproj(pw->pw_name, &proj, buf, sizeof(buf))) {
1161         errval = setproject(resultp->pj_name, pw->pw_name, TASK_NORMAL);
1162         if (errval != 0) {
1163             switch(errval) {
1164             case SETPROJ_ERR_TASK:
1165                 if (errno == EAGAIN)
1166                     log_error(errflags, "resource control limit has been reached");
1167                 else if (errno == ESRCH)
1168                     log_error(errflags, "user \"%s\" is not a member of "
1169                         "project \"%s\"", pw->pw_name, resultp->pj_name);
1170                 else if (errno == EACCES)
1171                     log_error(errflags, "the invoking task is final");
1172                 else
1173                     log_error(errflags, "could not join project \"%s\"",
1174                         resultp->pj_name);
1175                 break;
1176             case SETPROJ_ERR_POOL:
1177                 if (errno == EACCES)
1178                     log_error(errflags, "no resource pool accepting "
1179                             "default bindings exists for project \"%s\"",
1180                             resultp->pj_name);
1181                 else if (errno == ESRCH)
1182                     log_error(errflags, "specified resource pool does "
1183                             "not exist for project \"%s\"", resultp->pj_name);
1184                 else
1185                     log_error(errflags, "could not bind to default "
1186                             "resource pool for project \"%s\"", resultp->pj_name);
1187                 break;
1188             default:
1189                 if (errval <= 0) {
1190                     log_error(errflags, "setproject failed for project \"%s\"",
1191                         resultp->pj_name);
1192                 } else {
1193                     log_error(errflags, "warning, resource control assignment "
1194                         "failed for project \"%s\"", resultp->pj_name);
1195                 }
1196             }
1197         }
1198     } else {
1199         log_error(errflags, "getdefaultproj() error: %s", strerror(errno));
1200     }
1201     endprojent();
1202 }
1203 #else
1204 static void
1205 set_project(pw)
1206     struct passwd *pw;
1207 {
1208 }
1209 #endif /* HAVE_PROJECT_H */
1210
1211 /*
1212  * Look up the fully qualified domain name and set user_host and user_shost.
1213  */
1214 void
1215 set_fqdn()
1216 {
1217 #ifdef HAVE_GETADDRINFO
1218     struct addrinfo *res0, hint;
1219 #else
1220     struct hostent *hp;
1221 #endif
1222     char *p;
1223
1224 #ifdef HAVE_GETADDRINFO
1225     zero_bytes(&hint, sizeof(hint));
1226     hint.ai_family = PF_UNSPEC;
1227     hint.ai_flags = AI_CANONNAME;
1228     if (getaddrinfo(user_host, NULL, &hint, &res0) != 0) {
1229 #else
1230     if (!(hp = gethostbyname(user_host))) {
1231 #endif
1232         log_error(MSG_ONLY|NO_EXIT,
1233             "unable to resolve host %s", user_host);
1234     } else {
1235         if (user_shost != user_host)
1236             efree(user_shost);
1237         efree(user_host);
1238 #ifdef HAVE_GETADDRINFO
1239         user_host = estrdup(res0->ai_canonname);
1240         freeaddrinfo(res0);
1241 #else
1242         user_host = estrdup(hp->h_name);
1243 #endif
1244     }
1245     if ((p = strchr(user_host, '.'))) {
1246         *p = '\0';
1247         user_shost = estrdup(user_host);
1248         *p = '.';
1249     } else {
1250         user_shost = user_host;
1251     }
1252 }
1253
1254 /*
1255  * Get passwd entry for the user we are going to run commands as.
1256  * By default, this is "root".  Updates runas_pw as a side effect.
1257  */
1258 static void
1259 set_runaspw(user)
1260     char *user;
1261 {
1262     if (*user == '#') {
1263         if ((runas_pw = sudo_getpwuid(atoi(user + 1))) == NULL)
1264             runas_pw = sudo_fakepwnam(user, runas_gr ? runas_gr->gr_gid : 0);
1265     } else {
1266         if ((runas_pw = sudo_getpwnam(user)) == NULL) {
1267             audit_failure(NewArgv, "unknown user: %s", user);
1268             log_error(NO_MAIL|MSG_ONLY, "unknown user: %s", user);
1269         }
1270     }
1271 }
1272
1273 /*
1274  * Get group entry for the group we are going to run commands as.
1275  * Updates runas_pw as a side effect.
1276  */
1277 static void
1278 set_runasgr(group)
1279     char *group;
1280 {
1281     if (*group == '#') {
1282         if ((runas_gr = sudo_getgrgid(atoi(group + 1))) == NULL)
1283             runas_gr = sudo_fakegrnam(group);
1284     } else {
1285         if ((runas_gr = sudo_getgrnam(group)) == NULL)
1286             log_error(NO_MAIL|MSG_ONLY, "unknown group: %s", group);
1287     }
1288 }
1289
1290 /*
1291  * Get passwd entry for the user we are going to authenticate as.
1292  * By default, this is the user invoking sudo.  In the most common
1293  * case, this matches sudo_user.pw or runas_pw.
1294  */
1295 static struct passwd *
1296 get_authpw()
1297 {
1298     struct passwd *pw;
1299
1300     if (def_rootpw) {
1301         if ((pw = sudo_getpwuid(0)) == NULL)
1302             log_error(0, "unknown uid: 0");
1303     } else if (def_runaspw) {
1304         if ((pw = sudo_getpwnam(def_runas_default)) == NULL)
1305             log_error(0, "unknown user: %s", def_runas_default);
1306     } else if (def_targetpw) {
1307         if (runas_pw->pw_name == NULL)
1308             log_error(NO_MAIL|MSG_ONLY, "unknown uid: %lu",
1309                 (unsigned long) runas_pw->pw_uid);
1310         pw = runas_pw;
1311     } else
1312         pw = sudo_user.pw;
1313
1314     return(pw);
1315 }
1316
1317 /*
1318  * Cleanup hook for error()/errorx()
1319  */
1320 void
1321 cleanup(gotsignal)
1322     int gotsignal;
1323 {
1324     struct sudo_nss *nss;
1325
1326     if (!gotsignal) {
1327         if (snl != NULL) {
1328             tq_foreach_fwd(snl, nss)
1329                 nss->close(nss);
1330         }
1331 #ifdef USING_NONUNIX_GROUPS
1332         sudo_nonunix_groupcheck_cleanup();
1333 #endif
1334         sudo_endpwent();
1335         sudo_endgrent();
1336 #ifdef _PATH_SUDO_IO_LOGDIR
1337         io_log_close();
1338 #endif
1339     }
1340     term_restore(STDIN_FILENO, 0);
1341 #ifdef HAVE_SELINUX
1342     selinux_restore_tty();
1343 #endif
1344 }
1345
1346 static void
1347 show_version()
1348 {
1349     (void) printf("Sudo version %s\n", PACKAGE_VERSION);
1350     if (getuid() == 0) {
1351         putchar('\n');
1352         (void) printf("Configure args: %s\n", CONFIGURE_ARGS);
1353         (void) printf("Sudoers path: %s\n", _PATH_SUDOERS);
1354 #ifdef HAVE_LDAP
1355 # ifdef _PATH_NSSWITCH_CONF
1356         (void) printf("nsswitch path: %s\n", _PATH_NSSWITCH_CONF);
1357 # endif
1358         (void) printf("ldap.conf path: %s\n", _PATH_LDAP_CONF);
1359         (void) printf("ldap.secret path: %s\n", _PATH_LDAP_SECRET);
1360 #endif
1361         dump_auth_methods();
1362         dump_defaults();
1363         dump_interfaces();
1364     }
1365     exit(0);
1366 }
1367
1368 #ifdef USE_ADMIN_FLAG
1369 static void
1370 create_admin_success_flag()
1371 {
1372     struct stat statbuf;
1373     char flagfile[PATH_MAX];
1374     int fd, n;
1375
1376     /* Check whether the user is in the admin group. */
1377     if (!user_in_group(sudo_user.pw, "admin"))
1378         return;
1379
1380     /* Build path to flag file. */
1381     n = snprintf(flagfile, sizeof(flagfile), "%s/.sudo_as_admin_successful",
1382         user_dir);
1383     if (n <= 0 || n >= sizeof(flagfile))
1384         return;
1385
1386     /* Create admin flag file if it doesn't already exist. */
1387     set_perms(PERM_USER);
1388     if (stat(flagfile, &statbuf) == 0) {
1389         set_perms(PERM_ROOT);
1390         return;
1391     }
1392
1393     fd = open(flagfile, O_CREAT|O_WRONLY|O_EXCL, 0644);
1394     close(fd);
1395     set_perms(PERM_ROOT);
1396 }
1397 #else /* !USE_ADMIN_FLAG */
1398 static void
1399 create_admin_success_flag()
1400 {
1401     /* STUB */
1402 }
1403 #endif /* USE_ADMIN_FLAG */