git: 9de9a3305064 - stable/13 - fexecve(2): allow O_PATH file descriptors opened without O_EXEC

From: Konstantin Belousov <kib_at_FreeBSD.org>
Date: Sat, 06 Nov 2021 02:25:31 UTC
The branch stable/13 has been updated by kib:

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

commit 9de9a33050640a96d4ebea8d4da7089d0dfa3947
Author:     Konstantin Belousov <kib@FreeBSD.org>
AuthorDate: 2021-11-03 12:51:06 +0000
Commit:     Konstantin Belousov <kib@FreeBSD.org>
CommitDate: 2021-11-06 02:12:33 +0000

    fexecve(2): allow O_PATH file descriptors opened without O_EXEC
    
    (cherry picked from commit be10c0a910155709dc4e521db3349d50e0440018)
---
 lib/libc/sys/open.2     |  3 ---
 sys/kern/kern_descrip.c |  5 +++--
 sys/kern/kern_exec.c    | 13 ++++++++++---
 3 files changed, 13 insertions(+), 8 deletions(-)

diff --git a/lib/libc/sys/open.2 b/lib/libc/sys/open.2
index da42c238a151..f6b061079ddf 100644
--- a/lib/libc/sys/open.2
+++ b/lib/libc/sys/open.2
@@ -334,9 +334,6 @@ but advisory locking is not allowed
 .It Xr close 2
 .It Xr fstat 2
 .It Xr fexecve 2
-requires that
-.Dv O_EXEC
-was also specified at open time
 .It Dv SCM_RIGHTS
 can be passed over a
 .Xr unix 4
diff --git a/sys/kern/kern_descrip.c b/sys/kern/kern_descrip.c
index 755b5df51c6a..794d72824cc9 100644
--- a/sys/kern/kern_descrip.c
+++ b/sys/kern/kern_descrip.c
@@ -3302,8 +3302,9 @@ _fget(struct thread *td, int fd, struct file **fpp, int flags,
 			error = EBADF;
 		break;
 	case FEXEC:
-	    	if ((fp->f_flag & (FREAD | FEXEC)) == 0 ||
-		    ((fp->f_flag & FWRITE) != 0))
+		if (fp->f_ops != &path_fileops &&
+		    ((fp->f_flag & (FREAD | FEXEC)) == 0 ||
+		    (fp->f_flag & FWRITE) != 0))
 			error = EBADF;
 		break;
 	case 0:
diff --git a/sys/kern/kern_exec.c b/sys/kern/kern_exec.c
index 06812a7a93d1..7b27e5b8a885 100644
--- a/sys/kern/kern_exec.c
+++ b/sys/kern/kern_exec.c
@@ -498,13 +498,20 @@ interpret:
 		}
 	} else {
 		AUDIT_ARG_FD(args->fd);
+
 		/*
-		 * Descriptors opened only with O_EXEC or O_RDONLY are allowed.
+		 * If the descriptors was not opened with O_PATH, then
+		 * we require that it was opened with O_EXEC or
+		 * O_RDONLY.  In either case, exec_check_permissions()
+		 * below checks _current_ file access mode regardless
+		 * of the permissions additionally checked at the
+		 * open(2).
 		 */
 		error = fgetvp_exec(td, args->fd, &cap_fexecve_rights,
 		    &newtextvp);
-		if (error)
+		if (error != 0)
 			goto exec_fail;
+
 		if (vn_fullpath(newtextvp, &imgp->execpath,
 		    &imgp->freepath) != 0)
 			imgp->execpath = args->fname;
@@ -859,7 +866,7 @@ interpret:
 
 	/*
 	 * Store the vp for use in kern.proc.pathname.  This vnode was
-	 * referenced by namei() or fgetvp_exec().
+	 * referenced by namei() or by fexecve variant of fname handling.
 	 */
 	oldtextvp = p->p_textvp;
 	p->p_textvp = newtextvp;