git: 952fd61504cc - stable/15 - kern: do not allow unprivileged chroot when pwd is shared

From: Konstantin Belousov <kib_at_FreeBSD.org>
Date: Wed, 11 Nov 2026 01:07:00 UTC
The branch stable/15 has been updated by kib:

URL: https://cgit.FreeBSD.org/src/commit/?id=952fd61504cceedf962457dbf87de6248e7e1ba4

commit 952fd61504cceedf962457dbf87de6248e7e1ba4
Author:     Konstantin Belousov <kib@FreeBSD.org>
AuthorDate: 2026-10-24 12:59:08 +0000
Commit:     Konstantin Belousov <kib@FreeBSD.org>
CommitDate: 2026-11-10 19:53:56 +0000

    kern: do not allow unprivileged chroot when pwd is shared
    
    (cherry picked from commit e95e010fd0de721ae0e87bb24e20ec53aec8629e)
---
 sys/kern/vfs_syscalls.c | 22 +++++++++++++++++++++-
 1 file changed, 21 insertions(+), 1 deletion(-)

diff --git a/sys/kern/vfs_syscalls.c b/sys/kern/vfs_syscalls.c
index 1aecd7f7d5a8..4c1a3f0252bf 100644
--- a/sys/kern/vfs_syscalls.c
+++ b/sys/kern/vfs_syscalls.c
@@ -972,14 +972,34 @@ SYSCTL_INT(_security_bsd, OID_AUTO, unprivileged_chroot, CTLFLAG_RW,
 static int
 chroot_check_priv(struct thread *td)
 {
+	struct proc *p;
+
 	if (priv_check(td, PRIV_VFS_CHROOT) == 0)
 		return (0);
 	if (unprivileged_chroot == 0)
 		return (EXTERROR(EPERM,
 		    "security.bsd.unprivileged_chroot sysctl not enabled"));
-	if ((td->td_proc->p_flag2 & P2_NO_NEW_PRIVS) == 0)
+	p = td->td_proc;
+	if ((p->p_flag2 & P2_NO_NEW_PRIVS) == 0)
 		return (EXTERROR(EPERM,
 		    "PROC_NO_NEW_PRIVS not enabled"));
+
+	/*
+	 * Refuse chroot() when the pwd is shared with other
+	 * processes, since they might have been created before
+	 * P2_NO_NEW_PRIVS was set.
+	 *
+	 * The check races with fork(), but the race is harmless.  If
+	 * pd_sharecount was observed as 1 and another thread forked
+	 * in the meantime, the child inherited P2_NO_NEW_PRIVS.  Then
+	 * neither the parent nor the child can gain privileges by
+	 * executing a set-ID image, which prevents the issues
+	 * otherwise possible due to the pwd sharing.
+	 */
+	atomic_thread_fence_acq();
+	if (refcount_load(&p->p_pd->pd_sharecount) > 1)
+		return (EXTERROR(EPERM,
+		    "root/current directory shared with another process"));
 	return (0);
 }