git: 4bd568bd759b - stable/14 - bhyveload: limit rights on the dirfds we create

From: Kyle Evans <kevans_at_FreeBSD.org>
Date: Mon, 22 Jan 2024 17:30:02 UTC
The branch stable/14 has been updated by kevans:

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

commit 4bd568bd759bfd632425ee13e5e4e83b6a935525
Author:     Kyle Evans <kevans@FreeBSD.org>
AuthorDate: 2024-01-05 06:21:14 +0000
Commit:     Kyle Evans <kevans@FreeBSD.org>
CommitDate: 2024-01-22 17:18:52 +0000

    bhyveload: limit rights on the dirfds we create
    
    In neither case do we need write access to the directories we're working
    with; userboot doesn't support fo_write on the host device, and the
    bootfd is only ever needed for loader loading.
    
    This improves on 8bf0882e18 ("bhyveload: enter capability mode [...]")
    so that arbitrary code in the loader can't open writable fds to either
    of the directories we need to maintain access to.
    
    Reviewed by:    imp
    
    (cherry picked from commit c067be72e835e469518ec985b6cc4e475c378944)
    (cherry picked from commit f9b17005bf8f1a30e2a74a3e66c92e34aa87f9bf)
---
 usr.sbin/bhyveload/bhyveload.c | 18 ++++++++++++++++++
 1 file changed, 18 insertions(+)

diff --git a/usr.sbin/bhyveload/bhyveload.c b/usr.sbin/bhyveload/bhyveload.c
index d4f930e8cc76..16131dacecaa 100644
--- a/usr.sbin/bhyveload/bhyveload.c
+++ b/usr.sbin/bhyveload/bhyveload.c
@@ -734,12 +734,17 @@ usage(void)
 static void
 hostbase_open(const char *base)
 {
+	cap_rights_t rights;
 
 	if (hostbase_fd != -1)
 		close(hostbase_fd);
 	hostbase_fd = open(base, O_DIRECTORY | O_PATH);
 	if (hostbase_fd == -1)
 		err(EX_OSERR, "open");
+
+	if (caph_rights_limit(hostbase_fd, cap_rights_init(&rights, CAP_FSTATAT,
+	    CAP_LOOKUP, CAP_READ)) < 0)
+		err(EX_OSERR, "caph_rights_limit");
 }
 
 static void
@@ -860,11 +865,24 @@ main(int argc, char** argv)
 	 * guest requesting a different one.
 	 */
 	if (explicit_loader_fd == -1) {
+		cap_rights_t rights;
+
 		bootfd = open("/boot", O_DIRECTORY | O_PATH);
 		if (bootfd == -1) {
 			perror("open");
 			exit(1);
 		}
+
+		/*
+		 * bootfd will be used to do a lookup of our loader and do an
+		 * fdlopen(3) on the loader; thus, we need mmap(2) in addition
+		 * to the more usual lookup rights.
+		 */
+		if (caph_rights_limit(bootfd, cap_rights_init(&rights,
+		    CAP_FSTATAT, CAP_LOOKUP, CAP_MMAP_RX, CAP_READ)) < 0) {
+			perror("caph_rights_limit");
+			exit(1);
+		}
 	}
 
 	vcpu = vm_vcpu_open(ctx, BSP);