From 6491fef1e0be72661aa8ed60d3784d4426f41c76 Mon Sep 17 00:00:00 2001 From: Samanta Navarro Date: Tue, 23 May 2023 11:57:50 +0000 Subject: [PATCH] libmisc: Use safer chroot/chdir sequence OpenSSH and coreutils' chroot call chroot first and then chdir. Doing it this way is a bit safer because otherwise something could happen between chdir and chroot to the specified path (like exchange of links) so the working directory would not end up within the chroot environment. This is a purely defensive measure. Signed-off-by: Samanta Navarro --- libmisc/root_flag.c | 8 ++++---- libmisc/sub.c | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/libmisc/root_flag.c b/libmisc/root_flag.c index 62915b06..5572831a 100644 --- a/libmisc/root_flag.c +++ b/libmisc/root_flag.c @@ -91,16 +91,16 @@ static void change_root (const char* newroot) exit (E_BAD_ARG); } - if (chdir (newroot) != 0) { + if (chroot (newroot) != 0) { fprintf(log_get_logfd(), - _("%s: cannot chdir to chroot directory %s: %s\n"), + _("%s: unable to chroot to directory %s: %s\n"), log_get_progname(), newroot, strerror (errno)); exit (E_BAD_ARG); } - if (chroot (newroot) != 0) { + if (chdir ("/") != 0) { fprintf(log_get_logfd(), - _("%s: unable to chroot to directory %s: %s\n"), + _("%s: cannot chdir in chroot directory %s: %s\n"), log_get_progname(), newroot, strerror (errno)); exit (E_BAD_ARG); } diff --git a/libmisc/sub.c b/libmisc/sub.c index 821596d1..d8e24473 100644 --- a/libmisc/sub.c +++ b/libmisc/sub.c @@ -57,8 +57,8 @@ void subsystem (const struct passwd *pw) * must be able to change into it. */ - if ( (chdir (pw->pw_dir) != 0) - || (chroot (pw->pw_dir) != 0)) { + if ( (chroot (pw->pw_dir) != 0) + || (chdir ("/") != 0)) { (void) printf (_("Can't change root directory to '%s'\n"), pw->pw_dir); SYSLOG ((LOG_WARN, NO_SUBROOT2, pw->pw_dir, pw->pw_name));