2007-07-27 Sergey Vlasov Updated alt-chroot patch for nut-2.0.5. 2004-03-13 Dmitry V. Levin Improve chroot jailing support. * common/common.c: (become_user): Moved initgroups call from here ... (get_user_pwent): ... to here. (chroot_start): Call tzset(3) before chroot(2) call. Preopen /dev/null before chroot(2) call ... (background): ... and use the descriptor for redirection. (background): Do not close standard descriptors in parent process. --- nut-2.0.5/common/common.c.alt-chroot 2007-07-27 13:07:21 +0400 +++ nut-2.0.5/common/common.c 2007-07-27 13:14:22 +0400 @@ -26,6 +26,7 @@ int nut_debug_level = 0; static int upslog_flags = UPSLOG_STDERR; + static int null_fd = -1; static void xbit_set(int *val, int flag) { @@ -67,28 +68,29 @@ void open_syslog(const char *progname) /* close ttys and become a daemon */ void background(void) { - int pid; + int fd; + pid_t pid; if ((pid = fork()) < 0) fatal_with_errno("Unable to enter background"); - xbit_set(&upslog_flags, UPSLOG_SYSLOG); - xbit_clear(&upslog_flags, UPSLOG_STDERR); - - close(0); - close(1); - close(2); - if (pid != 0) _exit(EXIT_SUCCESS); /* parent */ /* child */ + xbit_set(&upslog_flags, UPSLOG_SYSLOG); + xbit_clear(&upslog_flags, UPSLOG_STDERR); + /* make fds 0-2 point somewhere defined */ - if (open("/dev/null", O_RDWR) != 0) + if ((null_fd < 0) && ((null_fd = open("/dev/null", O_RDWR)) < 0)) fatal_with_errno("open /dev/null"); - dup(0); - dup(0); + for (fd = 0; fd<= 2; ++fd) + if ((null_fd != fd) && (dup2(null_fd, fd) < 0)) + fatal_with_errno("dup2 /dev/null"); + if ((null_fd > 2) && (close(null_fd) < 0)) + fatal_with_errno("close /dev/null"); + null_fd = -1; #ifdef HAVE_SETSID setsid(); /* make a new session to dodge signals */ @@ -102,8 +104,11 @@ struct passwd *get_user_pwent(const char { struct passwd *r; errno = 0; - if ((r = getpwnam(name))) + if ((r = getpwnam(name))) { + if (!geteuid() && initgroups(r->pw_name, r->pw_gid) == -1) + fatal_with_errno("initgroups"); return r; + } /* POSIX does not specify that "user not found" is an error, so some implementations of getpwnam() do not set errno when this @@ -127,9 +132,6 @@ void become_user(struct passwd *pw) if (seteuid(0)) fatal_with_errno("getuid gave 0, but seteuid(0) failed"); - if (initgroups(pw->pw_name, pw->pw_gid) == -1) - fatal_with_errno("initgroups"); - if (setgid(pw->pw_gid) == -1) fatal_with_errno("setgid"); @@ -140,6 +142,11 @@ void become_user(struct passwd *pw) /* drop down into a directory and throw away pointers to the old path */ void chroot_start(const char *path) { + tzset(); + + if ((null_fd = open("/dev/null", O_RDWR)) < 0) + fatal_with_errno("open /dev/null"); + if (chdir(path)) fatal_with_errno("chdir(%s)", path);