git: e6c623e9bad5 - main - chroot: Improve error message for unprivileged use

From: Ed Maste <emaste_at_FreeBSD.org>
Date: Fri, 01 Aug 2025 20:36:49 UTC
The branch main has been updated by emaste:

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

commit e6c623e9bad56271d6c5fffaaf994d27b65404e5
Author:     Ed Maste <emaste@FreeBSD.org>
AuthorDate: 2025-08-01 19:53:00 +0000
Commit:     Ed Maste <emaste@FreeBSD.org>
CommitDate: 2025-08-01 20:35:07 +0000

    chroot: Improve error message for unprivileged use
    
    When the security.bsd.unprivileged_chroot sysctl is set, chroot(2) can
    be used by unprivileged users as long as the PROC_NO_NEW_PRIVS_CTL
    process control is set.
    
    chroot(8) has a -n command line flag to set this process control.
    Add an explicit error for EPERM from chroot(2) if the -n flag is
    necessary, but not present.
    
    Before:
      $ chroot / /bin/sh
      chroot: /: Operation not permitted
    
    After:
      $ chroot / /bin/sh
      chroot: unprivileged use requires -n
    
    Reviewed by:    kevans
    Sponsored by:   The FreeBSD Foundation
    Differential Revision: https://reviews.freebsd.org/D51687
---
 usr.sbin/chroot/chroot.c | 8 +++++++-
 1 file changed, 7 insertions(+), 1 deletion(-)

diff --git a/usr.sbin/chroot/chroot.c b/usr.sbin/chroot/chroot.c
index bd4932ee9b48..c978fc019c95 100644
--- a/usr.sbin/chroot/chroot.c
+++ b/usr.sbin/chroot/chroot.c
@@ -34,6 +34,7 @@
 
 #include <ctype.h>
 #include <err.h>
+#include <errno.h>
 #include <grp.h>
 #include <limits.h>
 #include <paths.h>
@@ -158,8 +159,13 @@ main(int argc, char *argv[])
 			err(1, "procctl");
 	}
 
-	if (chdir(argv[0]) == -1 || chroot(".") == -1)
+	if (chdir(argv[0]) == -1)
 		err(1, "%s", argv[0]);
+	if (chroot(".") == -1) {
+		if (errno == EPERM && !nonprivileged && geteuid() != 0)
+			errx(1, "unprivileged use requires -n");
+		err(1, "%s", argv[0]);
+	}
 
 	if (gids && setgroups(gids, gidlist) == -1)
 		err(1, "setgroups");