From 563288ea705e83ff5cb292adf794650c263bca1d Mon Sep 17 00:00:00 2001
From: Lasse Collin <lasse.collin@tukaani.org>
Date: Tue, 25 Oct 2022 21:11:58 +0300
Subject: xz: Add support for OpenBSD's pledge() sandbox.

---
 src/xz/file_io.c | 11 +++++++++++
 src/xz/main.c    | 13 +++++++++++++
 src/xz/private.h |  2 +-
 3 files changed, 25 insertions(+), 1 deletion(-)

(limited to 'src/xz')

diff --git a/src/xz/file_io.c b/src/xz/file_io.c
index 046ca7e3..61857029 100644
--- a/src/xz/file_io.c
+++ b/src/xz/file_io.c
@@ -212,6 +212,17 @@ io_sandbox_enter(int src_fd)
 	if (cap_enter())
 		goto error;
 
+#elif defined(HAVE_PLEDGE)
+	// pledge() was introduced in OpenBSD 5.9.
+	//
+	// main() unconditionally calls pledge() with fairly relaxed
+	// promises which work in all situations. Here we make the
+	// sandbox more strict.
+	if (pledge("stdio", ""))
+		goto error;
+
+	(void)src_fd;
+
 #else
 #	error ENABLE_SANDBOX is defined but no sandboxing method was found.
 #endif
diff --git a/src/xz/main.c b/src/xz/main.c
index ca8a4680..63e1780c 100644
--- a/src/xz/main.c
+++ b/src/xz/main.c
@@ -163,6 +163,19 @@ main(int argc, char **argv)
 	// on the command line, thus this must be done before args_parse().
 	hardware_init();
 
+#ifdef HAVE_PLEDGE
+	// OpenBSD's pledge() sandbox
+	//
+	// Unconditionally enable sandboxing with fairly relaxed promises.
+	// This is still way better than having no sandbox at all. :-)
+	// More strict promises will be made later in file_io.c if possible.
+	//
+	// This is done only after the above initializations
+	// as the error message needs locale support.
+	if (pledge("stdio rpath wpath cpath fattr", ""))
+		message_fatal(_("Failed to enable the sandbox"));
+#endif
+
 	// Parse the command line arguments and get an array of filenames.
 	// This doesn't return if something is wrong with the command line
 	// arguments. If there are no arguments, one filename ("-") is still
diff --git a/src/xz/private.h b/src/xz/private.h
index d97c22cc..6414bdb5 100644
--- a/src/xz/private.h
+++ b/src/xz/private.h
@@ -45,7 +45,7 @@
 #	define STDERR_FILENO (fileno(stderr))
 #endif
 
-#ifdef HAVE_CAPSICUM
+#if defined(HAVE_CAPSICUM) || defined(HAVE_PLEDGE)
 #	define ENABLE_SANDBOX 1
 #endif
 
-- 
cgit v1.2.3