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