git: fc287f28dfc9 - stable/13 - posix_spawn(3): add POSIX_SPAWN_DISABLE_ASLR_NP

From: Konstantin Belousov <kib_at_FreeBSD.org>
Date: Mon, 11 Mar 2024 00:30:32 UTC
The branch stable/13 has been updated by kib:

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

commit fc287f28dfc99bfe47d7a6071f52ddecd9983472
Author:     Konstantin Belousov <kib@FreeBSD.org>
AuthorDate: 2024-03-03 13:30:04 +0000
Commit:     Konstantin Belousov <kib@FreeBSD.org>
CommitDate: 2024-03-11 00:29:51 +0000

    posix_spawn(3): add POSIX_SPAWN_DISABLE_ASLR_NP
    
    (cherry picked from commit 822042fdfca79faada89e67110b01dd9ecc05996)
---
 include/spawn.h            |  1 +
 lib/libc/gen/posix_spawn.c | 13 +++++++++++--
 2 files changed, 12 insertions(+), 2 deletions(-)

diff --git a/include/spawn.h b/include/spawn.h
index 9643fcda5c13..a93315930954 100644
--- a/include/spawn.h
+++ b/include/spawn.h
@@ -59,6 +59,7 @@ typedef struct __posix_spawn_file_actions	*posix_spawn_file_actions_t;
 #define POSIX_SPAWN_SETSCHEDULER	0x08
 #define POSIX_SPAWN_SETSIGDEF		0x10
 #define POSIX_SPAWN_SETSIGMASK		0x20
+#define	POSIX_SPAWN_DISABLE_ASLR_NP	0x40
 
 __BEGIN_DECLS
 /*
diff --git a/lib/libc/gen/posix_spawn.c b/lib/libc/gen/posix_spawn.c
index 49a63bb40501..eda654a2f7e6 100644
--- a/lib/libc/gen/posix_spawn.c
+++ b/lib/libc/gen/posix_spawn.c
@@ -29,6 +29,7 @@
 #include <sys/cdefs.h>
 #include "namespace.h"
 #include <sys/param.h>
+#include <sys/procctl.h>
 #include <sys/queue.h>
 #include <sys/wait.h>
 
@@ -92,7 +93,7 @@ static int
 process_spawnattr(const posix_spawnattr_t sa)
 {
 	struct sigaction sigact = { .sa_flags = 0, .sa_handler = SIG_DFL };
-	int i;
+	int aslr, i;
 
 	/*
 	 * POSIX doesn't really describe in which order everything
@@ -140,6 +141,13 @@ process_spawnattr(const posix_spawnattr_t sa)
 		}
 	}
 
+	/* Disable ASLR. */
+	if ((sa->sa_flags & POSIX_SPAWN_DISABLE_ASLR_NP) != 0) {
+		aslr = PROC_ASLR_FORCE_DISABLE;
+		if (procctl(P_PID, 0, PROC_ASLR_CTL, &aslr) != 0)
+			return (errno);
+	}
+
 	return (0);
 }
 
@@ -632,7 +640,8 @@ posix_spawnattr_setflags(posix_spawnattr_t *sa, short flags)
 {
 	if ((flags & ~(POSIX_SPAWN_RESETIDS | POSIX_SPAWN_SETPGROUP |
 	    POSIX_SPAWN_SETSCHEDPARAM | POSIX_SPAWN_SETSCHEDULER |
-	    POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETSIGMASK)) != 0)
+	    POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETSIGMASK |
+	    POSIX_SPAWN_DISABLE_ASLR_NP)) != 0)
 		return (EINVAL);
 	(*sa)->sa_flags = flags;
 	return (0);