Index: head/lib/libutil/pw_util.c =================================================================== --- head/lib/libutil/pw_util.c (revision 298875) +++ head/lib/libutil/pw_util.c (revision 298876) @@ -1,664 +1,663 @@ /*- * Copyright (c) 1990, 1993, 1994 * The Regents of the University of California. All rights reserved. * Copyright (c) 2002 Networks Associates Technology, Inc. * All rights reserved. * * Portions of this software were developed for the FreeBSD Project by * ThinkSec AS and NAI Labs, the Security Research Division of Network * Associates, Inc. under DARPA/SPAWAR contract N66001-01-C-8035 * ("CBOSS"), as part of the DARPA CHATS research program. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifndef lint #if 0 static const char sccsid[] = "@(#)pw_util.c 8.3 (Berkeley) 4/2/94"; #endif static const char rcsid[] = "$FreeBSD$"; #endif /* not lint */ /* * This file is used by all the "password" programs; vipw(8), chpass(1), * and passwd(1). */ #include #include #include #include #include #include #include #include #include #include -#include #include #include #include #include #include #include #include #include "libutil.h" static pid_t editpid = -1; static int lockfd = -1; static char masterpasswd[PATH_MAX]; static char passwd_dir[PATH_MAX]; static char tempname[PATH_MAX]; static int initialized; #if 0 void pw_cont(int sig) { if (editpid != -1) kill(editpid, sig); } #endif /* * Initialize statics and set limits, signals & umask to try to avoid * interruptions, crashes etc. that might expose passord data. */ int pw_init(const char *dir, const char *master) { #if 0 struct rlimit rlim; #endif if (dir == NULL) { strcpy(passwd_dir, _PATH_ETC); } else { if (strlen(dir) >= sizeof(passwd_dir)) { errno = ENAMETOOLONG; return (-1); } strcpy(passwd_dir, dir); } if (master == NULL) { if (dir == NULL) { strcpy(masterpasswd, _PATH_MASTERPASSWD); } else if (snprintf(masterpasswd, sizeof(masterpasswd), "%s/%s", passwd_dir, _MASTERPASSWD) > (int)sizeof(masterpasswd)) { errno = ENAMETOOLONG; return (-1); } } else { if (strlen(master) >= sizeof(masterpasswd)) { errno = ENAMETOOLONG; return (-1); } strcpy(masterpasswd, master); } /* * The code that follows is extremely disruptive to the calling * process, and is therefore disabled until someone can conceive * of a realistic scenario where it would fend off a compromise. * Race conditions concerning the temporary files can be guarded * against in other ways than masking signals (by checking stat(2) * results after creation). */ #if 0 /* Unlimited resource limits. */ rlim.rlim_cur = rlim.rlim_max = RLIM_INFINITY; (void)setrlimit(RLIMIT_CPU, &rlim); (void)setrlimit(RLIMIT_FSIZE, &rlim); (void)setrlimit(RLIMIT_STACK, &rlim); (void)setrlimit(RLIMIT_DATA, &rlim); (void)setrlimit(RLIMIT_RSS, &rlim); /* Don't drop core (not really necessary, but GP's). */ rlim.rlim_cur = rlim.rlim_max = 0; (void)setrlimit(RLIMIT_CORE, &rlim); /* Turn off signals. */ (void)signal(SIGALRM, SIG_IGN); (void)signal(SIGHUP, SIG_IGN); (void)signal(SIGINT, SIG_IGN); (void)signal(SIGPIPE, SIG_IGN); (void)signal(SIGQUIT, SIG_IGN); (void)signal(SIGTERM, SIG_IGN); (void)signal(SIGCONT, pw_cont); /* Create with exact permissions. */ (void)umask(0); #endif initialized = 1; return (0); } /* * Lock the master password file. */ int pw_lock(void) { if (*masterpasswd == '\0') return (-1); /* * If the master password file doesn't exist, the system is hosed. * Might as well try to build one. Set the close-on-exec bit so * that users can't get at the encrypted passwords while editing. * Open should allow flock'ing the file; see 4.4BSD. XXX */ for (;;) { struct stat st; lockfd = flopen(masterpasswd, O_RDONLY|O_NONBLOCK|O_CLOEXEC, 0); if (lockfd == -1) { if (errno == EWOULDBLOCK) { errx(1, "the password db file is busy"); } else { err(1, "could not lock the passwd file: "); } } /* * If the password file was replaced while we were trying to * get the lock, our hardlink count will be 0 and we have to * close and retry. */ if (fstat(lockfd, &st) == -1) err(1, "fstat() failed: "); if (st.st_nlink != 0) break; close(lockfd); lockfd = -1; } return (lockfd); } /* * Create and open a presumably safe temp file for editing the password * data, and copy the master password file into it. */ int pw_tmp(int mfd) { char buf[8192]; ssize_t nr; const char *p; int tfd; if (*masterpasswd == '\0') return (-1); if ((p = strrchr(masterpasswd, '/'))) ++p; else p = masterpasswd; if (snprintf(tempname, sizeof(tempname), "%.*spw.XXXXXX", (int)(p - masterpasswd), masterpasswd) >= (int)sizeof(tempname)) { errno = ENAMETOOLONG; return (-1); } if ((tfd = mkostemp(tempname, O_SYNC)) == -1) return (-1); if (mfd != -1) { while ((nr = read(mfd, buf, sizeof(buf))) > 0) if (write(tfd, buf, (size_t)nr) != nr) break; if (nr != 0) { unlink(tempname); *tempname = '\0'; close(tfd); return (-1); } } return (tfd); } /* * Regenerate the password database. */ int pw_mkdb(const char *user) { int pstat; pid_t pid; (void)fflush(stderr); switch ((pid = fork())) { case -1: return (-1); case 0: /* child */ if (user == NULL) execl(_PATH_PWD_MKDB, "pwd_mkdb", "-p", "-d", passwd_dir, tempname, (char *)NULL); else execl(_PATH_PWD_MKDB, "pwd_mkdb", "-p", "-d", passwd_dir, "-u", user, tempname, (char *)NULL); _exit(1); /* NOTREACHED */ default: /* parent */ break; } if (waitpid(pid, &pstat, 0) == -1) return (-1); if (WIFEXITED(pstat) && WEXITSTATUS(pstat) == 0) return (0); errno = 0; return (-1); } /* * Edit the temp file. Return -1 on error, >0 if the file was modified, 0 * if it was not. */ int pw_edit(int notsetuid) { struct sigaction sa, sa_int, sa_quit; sigset_t oldsigset, nsigset; struct stat st1, st2; const char *editor; int pstat; if ((editor = getenv("EDITOR")) == NULL) editor = _PATH_VI; if (stat(tempname, &st1) == -1) return (-1); sa.sa_handler = SIG_IGN; sigemptyset(&sa.sa_mask); sa.sa_flags = 0; sigaction(SIGINT, &sa, &sa_int); sigaction(SIGQUIT, &sa, &sa_quit); sigemptyset(&nsigset); sigaddset(&nsigset, SIGCHLD); sigprocmask(SIG_BLOCK, &nsigset, &oldsigset); switch ((editpid = fork())) { case -1: return (-1); case 0: sigaction(SIGINT, &sa_int, NULL); sigaction(SIGQUIT, &sa_quit, NULL); sigprocmask(SIG_SETMASK, &oldsigset, NULL); if (notsetuid) { (void)setgid(getgid()); (void)setuid(getuid()); } errno = 0; - execlp(editor, basename(editor), tempname, (char *)NULL); + execlp(editor, editor, tempname, (char *)NULL); _exit(errno); default: /* parent */ break; } for (;;) { if (waitpid(editpid, &pstat, WUNTRACED) == -1) { if (errno == EINTR) continue; unlink(tempname); editpid = -1; break; } else if (WIFSTOPPED(pstat)) { raise(WSTOPSIG(pstat)); } else if (WIFEXITED(pstat) && WEXITSTATUS(pstat) == 0) { editpid = -1; break; } else { unlink(tempname); editpid = -1; break; } } sigaction(SIGINT, &sa_int, NULL); sigaction(SIGQUIT, &sa_quit, NULL); sigprocmask(SIG_SETMASK, &oldsigset, NULL); if (stat(tempname, &st2) == -1) return (-1); return (st1.st_mtim.tv_sec != st2.st_mtim.tv_sec || st1.st_mtim.tv_nsec != st2.st_mtim.tv_nsec); } /* * Clean up. Preserve errno for the caller's convenience. */ void pw_fini(void) { int serrno, status; if (!initialized) return; initialized = 0; serrno = errno; if (editpid != -1) { kill(editpid, SIGTERM); kill(editpid, SIGCONT); waitpid(editpid, &status, 0); editpid = -1; } if (*tempname != '\0') { unlink(tempname); *tempname = '\0'; } if (lockfd != -1) close(lockfd); errno = serrno; } /* * Compares two struct pwds. */ int pw_equal(const struct passwd *pw1, const struct passwd *pw2) { return (strcmp(pw1->pw_name, pw2->pw_name) == 0 && pw1->pw_uid == pw2->pw_uid && pw1->pw_gid == pw2->pw_gid && strcmp(pw1->pw_class, pw2->pw_class) == 0 && pw1->pw_change == pw2->pw_change && pw1->pw_expire == pw2->pw_expire && strcmp(pw1->pw_gecos, pw2->pw_gecos) == 0 && strcmp(pw1->pw_dir, pw2->pw_dir) == 0 && strcmp(pw1->pw_shell, pw2->pw_shell) == 0); } /* * Make a passwd line out of a struct passwd. */ char * pw_make(const struct passwd *pw) { char *line; asprintf(&line, "%s:%s:%ju:%ju:%s:%ju:%ju:%s:%s:%s", pw->pw_name, pw->pw_passwd, (uintmax_t)pw->pw_uid, (uintmax_t)pw->pw_gid, pw->pw_class, (uintmax_t)pw->pw_change, (uintmax_t)pw->pw_expire, pw->pw_gecos, pw->pw_dir, pw->pw_shell); return (line); } /* * Make a passwd line (in v7 format) out of a struct passwd */ char * pw_make_v7(const struct passwd *pw) { char *line; asprintf(&line, "%s:*:%ju:%ju:%s:%s:%s", pw->pw_name, (uintmax_t)pw->pw_uid, (uintmax_t)pw->pw_gid, pw->pw_gecos, pw->pw_dir, pw->pw_shell); return (line); } /* * Copy password file from one descriptor to another, replacing, deleting * or adding a single record on the way. */ int pw_copy(int ffd, int tfd, const struct passwd *pw, struct passwd *old_pw) { char buf[8192], *end, *line, *p, *q, *r, t; struct passwd *fpw; const struct passwd *spw; size_t len; int eof, readlen; if (old_pw == NULL && pw == NULL) return (-1); spw = old_pw; /* deleting a user */ if (pw == NULL) { line = NULL; } else { if ((line = pw_make(pw)) == NULL) return (-1); } /* adding a user */ if (spw == NULL) spw = pw; eof = 0; len = 0; p = q = end = buf; for (;;) { /* find the end of the current line */ for (p = q; q < end && *q != '\0'; ++q) if (*q == '\n') break; /* if we don't have a complete line, fill up the buffer */ if (q >= end) { if (eof) break; if ((size_t)(q - p) >= sizeof(buf)) { warnx("passwd line too long"); errno = EINVAL; /* hack */ goto err; } if (p < end) { q = memmove(buf, p, end - p); end -= p - buf; } else { p = q = end = buf; } readlen = read(ffd, end, sizeof(buf) - (end - buf)); if (readlen == -1) goto err; else len = (size_t)readlen; if (len == 0 && p == buf) break; end += len; len = end - buf; if (len < (ssize_t)sizeof(buf)) { eof = 1; if (len > 0 && buf[len - 1] != '\n') ++len, *end++ = '\n'; } continue; } /* is it a blank line or a comment? */ for (r = p; r < q && isspace(*r); ++r) /* nothing */ ; if (r == q || *r == '#') { /* yep */ if (write(tfd, p, q - p + 1) != q - p + 1) goto err; ++q; continue; } /* is it the one we're looking for? */ t = *q; *q = '\0'; fpw = pw_scan(r, PWSCAN_MASTER); /* * fpw is either the struct passwd for the current line, * or NULL if the line is malformed. */ *q = t; if (fpw == NULL || strcmp(fpw->pw_name, spw->pw_name) != 0) { /* nope */ if (fpw != NULL) free(fpw); if (write(tfd, p, q - p + 1) != q - p + 1) goto err; ++q; continue; } if (old_pw && !pw_equal(fpw, old_pw)) { warnx("entry inconsistent"); free(fpw); errno = EINVAL; /* hack */ goto err; } free(fpw); /* it is, replace or remove it */ if (line != NULL) { len = strlen(line); if (write(tfd, line, len) != (int)len) goto err; } else { /* when removed, avoid the \n */ q++; } /* we're done, just copy the rest over */ for (;;) { if (write(tfd, q, end - q) != end - q) goto err; q = buf; readlen = read(ffd, buf, sizeof(buf)); if (readlen == 0) break; else len = (size_t)readlen; if (readlen == -1) goto err; end = buf + len; } goto done; } /* if we got here, we didn't find the old entry */ if (line == NULL) { errno = ENOENT; goto err; } len = strlen(line); if ((size_t)write(tfd, line, len) != len || write(tfd, "\n", 1) != 1) goto err; done: if (line != NULL) free(line); return (0); err: if (line != NULL) free(line); return (-1); } /* * Return the current value of tempname. */ const char * pw_tempname(void) { return (tempname); } /* * Duplicate a struct passwd. */ struct passwd * pw_dup(const struct passwd *pw) { char *dst; struct passwd *npw; ssize_t len; len = sizeof(*npw); if (pw->pw_name != NULL) len += strlen(pw->pw_name) + 1; if (pw->pw_passwd != NULL) len += strlen(pw->pw_passwd) + 1; if (pw->pw_class != NULL) len += strlen(pw->pw_class) + 1; if (pw->pw_gecos != NULL) len += strlen(pw->pw_gecos) + 1; if (pw->pw_dir != NULL) len += strlen(pw->pw_dir) + 1; if (pw->pw_shell != NULL) len += strlen(pw->pw_shell) + 1; if ((npw = malloc((size_t)len)) == NULL) return (NULL); memcpy(npw, pw, sizeof(*npw)); dst = (char *)npw + sizeof(*npw); if (pw->pw_name != NULL) { npw->pw_name = dst; dst = stpcpy(npw->pw_name, pw->pw_name) + 1; } if (pw->pw_passwd != NULL) { npw->pw_passwd = dst; dst = stpcpy(npw->pw_passwd, pw->pw_passwd) + 1; } if (pw->pw_class != NULL) { npw->pw_class = dst; dst = stpcpy(npw->pw_class, pw->pw_class) + 1; } if (pw->pw_gecos != NULL) { npw->pw_gecos = dst; dst = stpcpy(npw->pw_gecos, pw->pw_gecos) + 1; } if (pw->pw_dir != NULL) { npw->pw_dir = dst; dst = stpcpy(npw->pw_dir, pw->pw_dir) + 1; } if (pw->pw_shell != NULL) { npw->pw_shell = dst; dst = stpcpy(npw->pw_shell, pw->pw_shell) + 1; } return (npw); } #include "pw_scan.h" /* * Wrapper around an internal libc function */ struct passwd * pw_scan(const char *line, int flags) { struct passwd pw, *ret; char *bp; if ((bp = strdup(line)) == NULL) return (NULL); if (!__pw_scan(bp, &pw, flags)) { free(bp); return (NULL); } ret = pw_dup(&pw); free(bp); return (ret); } Index: head/sbin/hastd/hooks.c =================================================================== --- head/sbin/hastd/hooks.c (revision 298875) +++ head/sbin/hastd/hooks.c (revision 298876) @@ -1,391 +1,390 @@ /*- * Copyright (c) 2010 The FreeBSD Foundation * Copyright (c) 2010 Pawel Jakub Dawidek * All rights reserved. * * This software was developed by Pawel Jakub Dawidek under sponsorship from * the FreeBSD Foundation. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include __FBSDID("$FreeBSD$"); #include #include #include #include #include -#include #include #include #include #include #include #include #include #include #include #include #include "hooks.h" #include "subr.h" #include "synch.h" /* Report processes that are running for too long not often than this value. */ #define REPORT_INTERVAL 60 /* Are we initialized? */ static bool hooks_initialized = false; /* * Keep all processes we forked on a global queue, so we can report nicely * when they finish or report that they are running for a long time. */ #define HOOKPROC_MAGIC_ALLOCATED 0x80090ca #define HOOKPROC_MAGIC_ONLIST 0x80090c0 struct hookproc { /* Magic. */ int hp_magic; /* PID of a forked child. */ pid_t hp_pid; /* When process were forked? */ time_t hp_birthtime; /* When we logged previous reported? */ time_t hp_lastreport; /* Path to executable and all the arguments we passed. */ char hp_comm[PATH_MAX]; TAILQ_ENTRY(hookproc) hp_next; }; static TAILQ_HEAD(, hookproc) hookprocs; static pthread_mutex_t hookprocs_lock; static void hook_remove(struct hookproc *hp); static void hook_free(struct hookproc *hp); static void descriptors(void) { int fd; /* * Close all (or almost all) descriptors. */ if (pjdlog_mode_get() == PJDLOG_MODE_STD) { closefrom(MAX(MAX(STDIN_FILENO, STDOUT_FILENO), STDERR_FILENO) + 1); return; } closefrom(0); /* * Redirect stdin, stdout and stderr to /dev/null. */ fd = open(_PATH_DEVNULL, O_RDONLY); if (fd == -1) { pjdlog_errno(LOG_WARNING, "Unable to open %s for reading", _PATH_DEVNULL); } else if (fd != STDIN_FILENO) { if (dup2(fd, STDIN_FILENO) == -1) { pjdlog_errno(LOG_WARNING, "Unable to duplicate descriptor for stdin"); } close(fd); } fd = open(_PATH_DEVNULL, O_WRONLY); if (fd == -1) { pjdlog_errno(LOG_WARNING, "Unable to open %s for writing", _PATH_DEVNULL); } else { if (fd != STDOUT_FILENO && dup2(fd, STDOUT_FILENO) == -1) { pjdlog_errno(LOG_WARNING, "Unable to duplicate descriptor for stdout"); } if (fd != STDERR_FILENO && dup2(fd, STDERR_FILENO) == -1) { pjdlog_errno(LOG_WARNING, "Unable to duplicate descriptor for stderr"); } if (fd != STDOUT_FILENO && fd != STDERR_FILENO) close(fd); } } void hook_init(void) { PJDLOG_ASSERT(!hooks_initialized); mtx_init(&hookprocs_lock); TAILQ_INIT(&hookprocs); hooks_initialized = true; } void hook_fini(void) { struct hookproc *hp; PJDLOG_ASSERT(hooks_initialized); mtx_lock(&hookprocs_lock); while ((hp = TAILQ_FIRST(&hookprocs)) != NULL) { PJDLOG_ASSERT(hp->hp_magic == HOOKPROC_MAGIC_ONLIST); PJDLOG_ASSERT(hp->hp_pid > 0); hook_remove(hp); hook_free(hp); } mtx_unlock(&hookprocs_lock); mtx_destroy(&hookprocs_lock); TAILQ_INIT(&hookprocs); hooks_initialized = false; } static struct hookproc * hook_alloc(const char *path, char **args) { struct hookproc *hp; unsigned int ii; hp = malloc(sizeof(*hp)); if (hp == NULL) { pjdlog_error("Unable to allocate %zu bytes of memory for a hook.", sizeof(*hp)); return (NULL); } hp->hp_pid = 0; hp->hp_birthtime = hp->hp_lastreport = time(NULL); (void)strlcpy(hp->hp_comm, path, sizeof(hp->hp_comm)); /* We start at 2nd argument as we don't want to have exec name twice. */ for (ii = 1; args[ii] != NULL; ii++) { (void)snprlcat(hp->hp_comm, sizeof(hp->hp_comm), " %s", args[ii]); } if (strlen(hp->hp_comm) >= sizeof(hp->hp_comm) - 1) { pjdlog_error("Exec path too long, correct configuration file."); free(hp); return (NULL); } hp->hp_magic = HOOKPROC_MAGIC_ALLOCATED; return (hp); } static void hook_add(struct hookproc *hp, pid_t pid) { PJDLOG_ASSERT(hp->hp_magic == HOOKPROC_MAGIC_ALLOCATED); PJDLOG_ASSERT(hp->hp_pid == 0); hp->hp_pid = pid; mtx_lock(&hookprocs_lock); hp->hp_magic = HOOKPROC_MAGIC_ONLIST; TAILQ_INSERT_TAIL(&hookprocs, hp, hp_next); mtx_unlock(&hookprocs_lock); } static void hook_remove(struct hookproc *hp) { PJDLOG_ASSERT(hp->hp_magic == HOOKPROC_MAGIC_ONLIST); PJDLOG_ASSERT(hp->hp_pid > 0); PJDLOG_ASSERT(mtx_owned(&hookprocs_lock)); TAILQ_REMOVE(&hookprocs, hp, hp_next); hp->hp_magic = HOOKPROC_MAGIC_ALLOCATED; } static void hook_free(struct hookproc *hp) { PJDLOG_ASSERT(hp->hp_magic == HOOKPROC_MAGIC_ALLOCATED); PJDLOG_ASSERT(hp->hp_pid > 0); hp->hp_magic = 0; free(hp); } static struct hookproc * hook_find(pid_t pid) { struct hookproc *hp; PJDLOG_ASSERT(mtx_owned(&hookprocs_lock)); TAILQ_FOREACH(hp, &hookprocs, hp_next) { PJDLOG_ASSERT(hp->hp_magic == HOOKPROC_MAGIC_ONLIST); PJDLOG_ASSERT(hp->hp_pid > 0); if (hp->hp_pid == pid) break; } return (hp); } void hook_check_one(pid_t pid, int status) { struct hookproc *hp; mtx_lock(&hookprocs_lock); hp = hook_find(pid); if (hp == NULL) { mtx_unlock(&hookprocs_lock); pjdlog_debug(1, "Unknown process pid=%u", pid); return; } hook_remove(hp); mtx_unlock(&hookprocs_lock); if (WIFEXITED(status) && WEXITSTATUS(status) == 0) { pjdlog_debug(1, "Hook exited gracefully (pid=%u, cmd=[%s]).", pid, hp->hp_comm); } else if (WIFSIGNALED(status)) { pjdlog_error("Hook was killed (pid=%u, signal=%d, cmd=[%s]).", pid, WTERMSIG(status), hp->hp_comm); } else { pjdlog_error("Hook exited ungracefully (pid=%u, exitcode=%d, cmd=[%s]).", pid, WIFEXITED(status) ? WEXITSTATUS(status) : -1, hp->hp_comm); } hook_free(hp); } void hook_check(void) { struct hookproc *hp, *hp2; time_t now; PJDLOG_ASSERT(hooks_initialized); pjdlog_debug(2, "Checking hooks."); /* * Report about processes that are running for a long time. */ now = time(NULL); mtx_lock(&hookprocs_lock); TAILQ_FOREACH_SAFE(hp, &hookprocs, hp_next, hp2) { PJDLOG_ASSERT(hp->hp_magic == HOOKPROC_MAGIC_ONLIST); PJDLOG_ASSERT(hp->hp_pid > 0); /* * If process doesn't exists we somehow missed it. * Not much can be done expect for logging this situation. */ if (kill(hp->hp_pid, 0) == -1 && errno == ESRCH) { pjdlog_warning("Hook disappeared (pid=%u, cmd=[%s]).", hp->hp_pid, hp->hp_comm); hook_remove(hp); hook_free(hp); continue; } /* * Skip proccesses younger than 1 minute. */ if (now - hp->hp_lastreport < REPORT_INTERVAL) continue; /* * Hook is running for too long, report it. */ pjdlog_warning("Hook is running for %ju seconds (pid=%u, cmd=[%s]).", (uintmax_t)(now - hp->hp_birthtime), hp->hp_pid, hp->hp_comm); hp->hp_lastreport = now; } mtx_unlock(&hookprocs_lock); } void hook_exec(const char *path, ...) { va_list ap; va_start(ap, path); hook_execv(path, ap); va_end(ap); } void hook_execv(const char *path, va_list ap) { struct hookproc *hp; char *args[64]; unsigned int ii; sigset_t mask; pid_t pid; PJDLOG_ASSERT(hooks_initialized); if (path == NULL || path[0] == '\0') return; memset(args, 0, sizeof(args)); - args[0] = basename(path); + args[0] = __DECONST(char *, path); for (ii = 1; ii < sizeof(args) / sizeof(args[0]); ii++) { args[ii] = va_arg(ap, char *); if (args[ii] == NULL) break; } PJDLOG_ASSERT(ii < sizeof(args) / sizeof(args[0])); hp = hook_alloc(path, args); if (hp == NULL) return; pjdlog_debug(1, "Executing hook: %s", hp->hp_comm); pid = fork(); switch (pid) { case -1: /* Error. */ pjdlog_errno(LOG_ERR, "Unable to fork to execute %s", path); hook_free(hp); return; case 0: /* Child. */ descriptors(); PJDLOG_VERIFY(sigemptyset(&mask) == 0); PJDLOG_VERIFY(sigprocmask(SIG_SETMASK, &mask, NULL) == 0); /* * Dummy handler set for SIGCHLD in the parent will be restored * to SIG_IGN on execv(3) below, so there is no need to do * anything with it. */ execv(path, args); pjdlog_errno(LOG_ERR, "Unable to execute %s", path); exit(EX_SOFTWARE); default: /* Parent. */ hook_add(hp, pid); break; } } Index: head/usr.bin/newgrp/newgrp.c =================================================================== --- head/usr.bin/newgrp/newgrp.c (revision 298875) +++ head/usr.bin/newgrp/newgrp.c (revision 298876) @@ -1,311 +1,310 @@ /*- * Copyright (c) 2002 Tim J. Robbins. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * newgrp -- change to a new group */ #include __FBSDID("$FreeBSD$"); #include #include #include #include -#include #include #include #include #include #include #include #include #include static void addgroup(const char *grpname); static void doshell(void); static int inarray(gid_t, const gid_t[], int); static void loginshell(void); static void restoregrps(void); static void usage(void); static struct passwd *pwd; static uid_t euid; extern char **environ; /* Manipulate effective user ID. */ #define PRIV_START do { \ if (seteuid(euid) < 0) \ err(1, "seteuid"); \ } while (0) #define PRIV_END do { \ if (seteuid(getuid()) < 0) \ err(1, "seteuid"); \ } while (0) int main(int argc, char *argv[]) { int ch, login; if ((euid = geteuid()) != 0) warnx("need root permissions to function properly, check setuid bit"); if (seteuid(getuid()) < 0) err(1, "seteuid"); if ((pwd = getpwuid(getuid())) == NULL) errx(1, "unknown user"); login = 0; while ((ch = getopt(argc, argv, "-l")) != -1) { switch (ch) { case '-': /* Obsolescent */ case 'l': login = 1; break; default: usage(); } } argc -= optind; argv += optind; switch (argc) { case 0: restoregrps(); break; case 1: addgroup(*argv); break; default: usage(); } if (seteuid(euid) < 0) err(1, "seteuid"); if (setuid(getuid()) < 0) err(1, "setuid"); if (login) loginshell(); else doshell(); /*NOTREACHED*/ exit(1); } static void usage(void) { fprintf(stderr, "usage: newgrp [-l] [group]\n"); exit(1); } static void restoregrps(void) { int initres, setres; PRIV_START; initres = initgroups(pwd->pw_name, pwd->pw_gid); setres = setgid(pwd->pw_gid); PRIV_END; if (initres < 0) warn("initgroups"); if (setres < 0) warn("setgid"); } static void addgroup(const char *grpname) { gid_t *grps; long lgid, ngrps_max; int dbmember, i, ngrps; gid_t egid; struct group *grp; char *ep, *pass, *cryptpw; char **p; egid = getegid(); /* Try it as a group name, then a group id. */ if ((grp = getgrnam(grpname)) == NULL) if ((lgid = strtol(grpname, &ep, 10)) <= 0 || *ep != '\0' || (grp = getgrgid((gid_t)lgid)) == NULL ) { warnx("%s: bad group name", grpname); return; } /* * If the user is not a member of the requested group and the group * has a password, prompt and check it. */ dbmember = 0; if (pwd->pw_gid == grp->gr_gid) dbmember = 1; for (p = grp->gr_mem; *p != NULL; p++) if (strcmp(*p, pwd->pw_name) == 0) { dbmember = 1; break; } if (!dbmember && *grp->gr_passwd != '\0' && getuid() != 0) { pass = getpass("Password:"); if (pass == NULL) return; cryptpw = crypt(pass, grp->gr_passwd); if (cryptpw == NULL || strcmp(grp->gr_passwd, cryptpw) != 0) { fprintf(stderr, "Sorry\n"); return; } } ngrps_max = sysconf(_SC_NGROUPS_MAX) + 1; if ((grps = malloc(sizeof(gid_t) * ngrps_max)) == NULL) err(1, "malloc"); if ((ngrps = getgroups(ngrps_max, (gid_t *)grps)) < 0) { warn("getgroups"); goto end; } /* Remove requested gid from supp. list if it exists. */ if (grp->gr_gid != egid && inarray(grp->gr_gid, grps, ngrps)) { for (i = 0; i < ngrps; i++) if (grps[i] == grp->gr_gid) break; ngrps--; memmove(&grps[i], &grps[i + 1], (ngrps - i) * sizeof(gid_t)); PRIV_START; if (setgroups(ngrps, (const gid_t *)grps) < 0) { PRIV_END; warn("setgroups"); goto end; } PRIV_END; } PRIV_START; if (setgid(grp->gr_gid)) { PRIV_END; warn("setgid"); goto end; } PRIV_END; grps[0] = grp->gr_gid; /* Add old effective gid to supp. list if it does not exist. */ if (egid != grp->gr_gid && !inarray(egid, grps, ngrps)) { if (ngrps == ngrps_max) warnx("too many groups"); else { grps[ngrps++] = egid; PRIV_START; if (setgroups(ngrps, (const gid_t *)grps)) { PRIV_END; warn("setgroups"); goto end; } PRIV_END; } } end: free(grps); } static int inarray(gid_t gid, const gid_t grps[], int ngrps) { int i; for (i = 0; i < ngrps; i++) if (grps[i] == gid) return (1); return (0); } /* * Set the environment to what would be expected if the user logged in * again; this performs the same steps as su(1)'s -l option. */ static void loginshell(void) { char *args[2], **cleanenv, *term, *ticket; const char *shell; login_cap_t *lc; shell = pwd->pw_shell; if (*shell == '\0') shell = _PATH_BSHELL; if (chdir(pwd->pw_dir) < 0) { warn("%s", pwd->pw_dir); chdir("/"); } term = getenv("TERM"); ticket = getenv("KRBTKFILE"); if ((cleanenv = calloc(20, sizeof(char *))) == NULL) err(1, "calloc"); *cleanenv = NULL; environ = cleanenv; lc = login_getpwclass(pwd); setusercontext(lc, pwd, pwd->pw_uid, LOGIN_SETPATH|LOGIN_SETUMASK|LOGIN_SETENV); login_close(lc); setenv("USER", pwd->pw_name, 1); setenv("SHELL", shell, 1); setenv("HOME", pwd->pw_dir, 1); if (term != NULL) setenv("TERM", term, 1); if (ticket != NULL) setenv("KRBTKFILE", ticket, 1); - if (asprintf(args, "-%s", basename(shell)) < 0) + if (asprintf(args, "-%s", shell) < 0) err(1, "asprintf"); args[1] = NULL; execv(shell, args); err(1, "%s", shell); } static void doshell(void) { const char *shell; shell = pwd->pw_shell; if (*shell == '\0') shell = _PATH_BSHELL; - execl(shell, basename(shell), (char *)NULL); + execl(shell, shell, (char *)NULL); err(1, "%s", shell); }