Hi Gert, hi all,

This follows up on the "[RFC] Optional Landlock filesystem sandbox after
privilege drop (Linux)" thread. Following Gert's feedback, the option is
named "--sandbox landlock" rather than --landlock, the change is a single
patch, the man page and Changes.md are updated, and the structure follows
OpenSSH (one sandbox interface with per-platform backends, privileged work
kept outside the sandbox, and a hard failure if the sandbox can't be
applied).

The patch is attached as git format-patch output (applies with git am on
current master), so that the mail client can't mangle whitespace. I'm
happy to resend it with git send-email or push it to Gerrit if you
prefer.

For the three open questions in the RFC:
1. Scripts and plugins: refused for now, with a clear error.
2. Kernels without Landlock: fatal error.
3. SIGHUP: supported. The config file stays readable, and edits saved
by rename (editors, sed -i) are handled.

Two things came up during testing that changed the design compared to
the RFC:
- In 2.7+ the default dns-updown command is executed directly when
running as root. Inside the sandbox it could not run, so DNS settings
would not be reverted on disconnect. With --sandbox, the existing
privileged dns-updown runner is now always used, and it is forked
before privileges are dropped.
- Landlock rules are bound to inodes. A renewed CRL installed via
mv makes OpenVPN see the change, fail to reopen the file and then
reject every client. Read access is therefore granted to the directory
that holds each file (never / or /etc itself). The man page explains
this and recommends a dedicated directory.

Testing (Linux 6.18, Landlock ABI 7):
- "make check" passes, including the new test_sandbox. CMake builds
pass with and without <linux/landlock.h>, and a build without it
rejects the option.
- The Landlock part of test_sandbox fails as expected when
landlock_restrict_self() is stubbed out.
- End-to-end test with a server, and a client in a separate network
namespace, both run with --sandbox landlock, the client with --user
nobody: tunnel traffic, status and ifconfig-pool-persist updates,
a revoked client rejected via the CRL, client SIGUSR1, the CRL
replaced via mv while valid clients keep connecting, a config edited
with sed -i followed by SIGHUP, dns-updown up and down through the
runner (exit status 0), and a SIGHUP that points --ca at a file
outside the allowed paths, which fails with "Permission denied" from
the kernel. All 25 checks pass; I can send the script if useful.

Possible follow-ups, if this one is accepted: Landlock network rules
(ABI 4) to limit TCP bind/connect, Landlock scoping (ABI 6), and
script support.

Disclosure, as in the RFC: this was written with substantial help from
an AI coding assistant (Claude). I have reviewed every line and am
responsible for it, and I'm happy to answer questions on any part.

Thanks,
Robson

15 files changed, 1356 insertions(+)

On Wed, Dec 02, 2026 02:11 AM, Gert Doering <[email protected]> wrote:

> Hi,
>
> On Tue, Dec 01, 2026 at 07:40:20PM -0500, Robson Pereira wrote:
> > Before writing any code I'd like to ask whether an optional, Linux-only
> > sandbox based on Landlock would be welcome, and if so, how you'd want it
> > scoped.
>
> I think the suggested approach is reasonable, and would like to see
> it happen.  I'd go along with most of your suggestions for the first
> round :-)
>
> A few notes
>
>  - have a look at OpenSSH, how they do their sandboxing across various
>    OSes, and if we can learn about it
>
>  - please do not make the option "--landlock", but more something
>    extensible for when we add, say, macOS sandboxing - so maybe
>    "--sandbox landlock"?  Not sure this is the best way, but creating
>    very platform specific options is generally making later extensibility
>    more painful.
>
>  - use of AI is fine, but you(!) own the code, and take responsibility,
>    so please be sure you fully understand what you submit.
>
>  - patch granularity - please don't go for a many-patches set, because
>    "more patches = more work for me".  I think this can be done with just
>    one larger patch - you need configure & unit test to test the actual
>    code, so the only thing that could be reasonably split off is
>    "options.c for the generic parts", and those are just a few lines
>    which doesn't make much sense.
>
>  - documentation, of course ;-)
>
> gert
>
> --
> "If was one thing all people took for granted, was conviction that if you
>  feed honest figures into a computer, honest figures come out. Never
> doubted
>  it myself till I met a computer with a sense of humor."
>                              Robert A. Heinlein, The Moon is a Harsh
> Mistress
>
> Gert Doering - Munich, Germany
> [email protected]
>
From 4e26a3f7a806c13e8ff852ea31168dfa1fb6c233 Mon Sep 17 00:00:00 2001
From: Robson Pereira <[email protected]>
Date: Wed, 2 Dec 2026 12:47:01 -0500
Subject: [PATCH] Add optional Landlock filesystem sandbox (--sandbox landlock)

Add a new option, --sandbox landlock, that uses Landlock (Linux 5.13+)
to restrict filesystem access after initialization to the files OpenVPN
still needs. It is applied once in do_uid_gid_chroot(), after --user,
--group, --chroot and --setcon, so it covers the same window as the
privilege drop and stays in effect across SIGUSR1 and SIGHUP restarts.

The allowlist is derived from the options in use: the config file, TLS
files, the CRL, credential files, --client-config-dir, the --status and
--ifconfig-pool-persist files and --tmp-dir, plus the system files
needed for name resolution, time zones, loading shared libraries and
reopening the tun device. Everything else becomes inaccessible,
including executing any program. Inline files are not included.

Files named by options are commonly replaced by rename (a renewed CRL,
a config file saved by an editor), and Landlock rules are bound to
inodes. A rule for the file alone would break CRL reloads after every
renewal and SIGHUP after every config edit, so read access is granted
to the directory holding each such file instead, except for files that
live directly in / or /etc.

Following OpenSSH, the code is split into a platform independent rule
list and a backend that applies it, and the option takes the backend
name, so that other mechanisms (e.g. on macOS) can be added later
without new options. Also like OpenSSH's monitor, work that needs
privileges stays outside the sandbox: with --sandbox the existing
dns-updown runner is always used, and it is started before privileges
are dropped, so DNS settings can still be applied and reverted.

Restrictions in this first step:

 - --sandbox is refused together with --script-security 2 or higher and
   with --plugin, as those would run inside the sandbox with
   no_new_privs set, which breaks setuid helpers such as sudo
 - it is refused in --enable-iproute2 builds, which execute ip(8)
 - a kernel without Landlock support is a fatal error rather than a
   warning, since the user explicitly asked for the sandbox

A new unit test (test_sandbox) covers option parsing, building the
rule list from options, and applying a real Landlock ruleset in a
forked child, checking allowed and denied reads, writes, file creation,
execution, and files replaced by rename. The Landlock part is skipped
on kernels without Landlock support.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Robson Pereira <[email protected]>
---

This follows up on the "[RFC] Optional Landlock filesystem sandbox after
privilege drop (Linux)" thread. Following Gert's feedback, the option is
named "--sandbox landlock" rather than --landlock, the change is a single
patch, the man page and Changes.md are updated, and the structure follows
OpenSSH (one sandbox interface with per-platform backends, privileged work
kept outside the sandbox, and a hard failure if the sandbox can't be
applied).

For the three open questions in the RFC:
 1. Scripts and plugins: refused for now, with a clear error.
 2. Kernels without Landlock: fatal error.
 3. SIGHUP: supported. The config file stays readable, and edits saved
    by rename (editors, sed -i) are handled.

Two things came up during testing that changed the design compared to
the RFC:
 - In 2.7+ the default dns-updown command is executed directly when
   running as root. Inside the sandbox it could not run, so DNS settings
   would not be reverted on disconnect. With --sandbox, the existing
   privileged dns-updown runner is now always used, and it is forked
   before privileges are dropped.
 - Landlock rules are bound to inodes. A renewed CRL installed via
   mv makes OpenVPN see the change, fail to reopen the file and then
   reject every client. Read access is therefore granted to the directory
   that holds each file (never / or /etc itself). The man page explains
   this and recommends a dedicated directory.

Testing (Linux 6.18, Landlock ABI 7):
 - "make check" passes, including the new test_sandbox. CMake builds
   pass with and without <linux/landlock.h>, and a build without it
   rejects the option.
 - The Landlock part of test_sandbox fails as expected when
   landlock_restrict_self() is stubbed out.
 - End-to-end test with a server, and a client in a separate network
   namespace, both run with --sandbox landlock, the client with --user
   nobody: tunnel traffic, status and ifconfig-pool-persist updates,
   a revoked client rejected via the CRL, client SIGUSR1, the CRL
   replaced via mv while valid clients keep connecting, a config edited
   with sed -i followed by SIGHUP, dns-updown up and down through the
   runner (exit status 0), and a SIGHUP that points --ca at a file
   outside the allowed paths, which fails with "Permission denied" from
   the kernel. All 25 checks pass; I can send the script if useful.

Possible follow-ups, if this one is accepted: Landlock network rules
(ABI 4) to limit TCP bind/connect, Landlock scoping (ABI 6), and
script support.

Disclosure, as in the RFC: this was written with substantial help from
an AI coding assistant (Claude). I have reviewed every line and am
responsible for it, and I'm happy to answer questions on any part.

 CMakeLists.txt                          |  10 +
 Changes.md                              |   9 +
 config.h.cmake.in                       |   3 +
 configure.ac                            |   1 +
 doc/man-sections/generic-options.rst    |  64 +++
 src/openvpn/Makefile.am                 |   1 +
 src/openvpn/dns.c                       |   9 +
 src/openvpn/dns.h                       |  13 +
 src/openvpn/init.c                      |  30 +-
 src/openvpn/options.c                   |  42 ++
 src/openvpn/options.h                   |   2 +
 src/openvpn/sandbox.c                   | 579 ++++++++++++++++++++++++
 src/openvpn/sandbox.h                   | 149 ++++++
 tests/unit_tests/openvpn/Makefile.am    |  14 +
 tests/unit_tests/openvpn/test_sandbox.c | 432 ++++++++++++++++++
 15 files changed, 1356 insertions(+), 2 deletions(-)
 create mode 100644 src/openvpn/sandbox.c
 create mode 100644 src/openvpn/sandbox.h
 create mode 100644 tests/unit_tests/openvpn/test_sandbox.c

diff --git a/CMakeLists.txt b/CMakeLists.txt
index d9a0369..18c6bc3 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -286,6 +286,7 @@ check_include_files(poll.h HAVE_POLL_H)
 check_include_files("${NETEXTRA};resolv.h" HAVE_RESOLV_H)
 check_include_files(sys/ioctl.h HAVE_SYS_IOCTL_H)
 check_include_files(sys/inotify.h HAVE_SYS_INOTIFY_H)
+check_include_files(linux/landlock.h HAVE_LINUX_LANDLOCK_H)
 check_include_files("${NETEXTRA};sys/uio.h" HAVE_SYS_UIO_H)
 check_include_files(sys/un.h HAVE_SYS_UN_H)
 check_include_files(sys/wait.h HAVE_SYS_WAIT_H)
@@ -573,6 +574,8 @@ set(SOURCE_FILES
     src/openvpn/pool.h
     src/openvpn/probe.c
     src/openvpn/probe.h
+    src/openvpn/sandbox.c
+    src/openvpn/sandbox.h
     src/openvpn/proto.c
     src/openvpn/proto.h
     src/openvpn/proxy.c
@@ -703,6 +706,7 @@ if (BUILD_TESTING)
         "test_packet_id"
         "test_pkt"
         "test_provider"
+        "test_sandbox"
         "test_socket"
         "test_ssl"
         "test_user_pass"
@@ -941,6 +945,12 @@ if (BUILD_TESTING)
         )
 
     target_link_libraries(test_socket PUBLIC ${RESOLV_LIBRARIES})
+    target_sources(test_sandbox PRIVATE
+        tests/unit_tests/openvpn/mock_get_random.c
+        src/openvpn/buffer.c
+        src/openvpn/sandbox.c
+        )
+
     target_sources(test_socket PRIVATE
         tests/unit_tests/openvpn/mock_get_random.c
         tests/unit_tests/openvpn/mock_management.c
diff --git a/Changes.md b/Changes.md
index 8d10d1e..05eb847 100644
--- a/Changes.md
+++ b/Changes.md
@@ -1,5 +1,14 @@
 # Overview of changes in 2.8
 
+## New features
+
+* **Optional filesystem sandbox on Linux (`--sandbox landlock`)**
+
+  The new `--sandbox landlock` option uses Landlock to restrict OpenVPN,
+  after initialization, to the files it still needs. The list of files is
+  derived from the options in use. It cannot be combined with user-defined
+  scripts or plugins yet. See `--sandbox` in the manual for details.
+
 ## User-visible Changes
 
 * **Parsing Distinguished Names in certificates**
diff --git a/config.h.cmake.in b/config.h.cmake.in
index aa21532..a102851 100644
--- a/config.h.cmake.in
+++ b/config.h.cmake.in
@@ -291,6 +291,9 @@
 /* Define to 1 if you have the <sys/inotify.h> header file. */
 #cmakedefine HAVE_SYS_INOTIFY_H
 
+/* Define to 1 if you have the <linux/landlock.h> header file. */
+#cmakedefine HAVE_LINUX_LANDLOCK_H
+
 /* Define to 1 if you have the <sys/ioctl.h> header file. */
 #cmakedefine HAVE_SYS_IOCTL_H
 
diff --git a/configure.ac b/configure.ac
index ef05253..e8379b8 100644
--- a/configure.ac
+++ b/configure.ac
@@ -612,6 +612,7 @@ AC_CHECK_HEADERS(
 	],
 	[have_tap_header="yes"]
 )
+AC_CHECK_HEADERS([linux/landlock.h])
 CFLAGS="${old_CFLAGS}"
 test "${have_tap_header}" = "yes" || AC_MSG_ERROR([no tap header could be found])
 
diff --git a/doc/man-sections/generic-options.rst b/doc/man-sections/generic-options.rst
index 17e4372..2babbf7 100644
--- a/doc/man-sections/generic-options.rst
+++ b/doc/man-sections/generic-options.rst
@@ -339,6 +339,70 @@ which mode OpenVPN is configured as.
   Please note the single quote marks and the escaping of the backslashes
   (``\\``) and the space character.
 
+--sandbox type
+  Restrict OpenVPN after initialization so that it can only access the
+  files it still needs. ``type`` selects the mechanism. The only type
+  supported so far is ``landlock``, which needs Linux 5.13 or later with
+  Landlock enabled (see the ``lsm=`` kernel parameter).
+
+  The sandbox is applied once, at the same point as ``--user``,
+  ``--group``, ``--chroot`` and ``--setcon``: after initialization, or
+  after the first successful connection with ``--client``, ``--pull`` or
+  ``--up-delay``. It stays in effect for the lifetime of the process,
+  including ``SIGUSR1`` and ``SIGHUP`` restarts, and is inherited by child
+  processes. If the sandbox cannot be applied, for example because the
+  kernel lacks Landlock support, OpenVPN exits instead of continuing
+  without it.
+
+  The files that remain accessible are derived from the options in use:
+
+  - read: the configuration file, ``--ca``, ``--capath``, ``--cert``,
+    ``--extra-certs``, ``--key``, ``--pkcs12``, ``--dh``, ``--askpass``,
+    ``--tls-auth``, ``--tls-crypt``, ``--tls-crypt-v2``, ``--crl-verify``,
+    ``--auth-user-pass``, ``--auth-gen-token-secret``, the ``--management``
+    password file, proxy credential files and ``--client-config-dir``.
+    Files given inline or as ``stdin`` are read only once and are not
+    included.
+
+    Because such files are often updated by replacing them with a new
+    file (a renewed CRL, a certificate renewed before ``SIGHUP``, or a
+    configuration file saved by an editor), read access is granted to the
+    directory containing each file, including everything below it, rather
+    than to the file alone. Files located directly in ``/`` or ``/etc``
+    are the exception: only the file itself is accessible. Keeping
+    OpenVPN's files in a directory of their own, such as
+    ``/etc/openvpn/server``, keeps this access narrow.
+  - read and write: ``--status`` and ``--ifconfig-pool-persist``.
+  - create and remove files in: ``--tmp-dir``, ``--tls-export-cert`` and
+    the ``--port-share`` journal directory.
+  - system files: those needed for name resolution (``/etc/resolv.conf``,
+    ``/etc/hosts``, ``/etc/nsswitch.conf``, ``/etc/gai.conf``,
+    ``/etc/host.conf``, ``/etc/services``), time zone data, shared
+    libraries, ``/dev/null``, ``/dev/random``, ``/dev/urandom`` and
+    ``/dev/net/tun``.
+
+  Nothing else can be read, written or executed. Files that were already
+  open when the sandbox was applied, such as the ``--log`` file, remain
+  usable. With ``--chroot``, paths are resolved inside the chroot.
+
+  Limitations:
+
+  - ``--sandbox`` cannot be combined with ``--script-security 2`` or
+    higher, or with ``--plugin``. The default ``--dns-updown`` command
+    still works: it is run by a helper process that is started before the
+    sandbox is applied and keeps the original privileges.
+  - ``SIGHUP`` re-reads the configuration file, but only files that were
+    accessible when the sandbox was applied can be opened. Configuration
+    changes that refer to files in other directories need a full restart.
+  - If ``/etc/resolv.conf`` or ``/etc/hosts`` is replaced by a new file
+    while OpenVPN runs, the new file cannot be read. When the file is a
+    symbolic link to a file outside ``/etc``, as with systemd-resolved,
+    the directory holding that file is made readable instead, so such
+    updates are picked up.
+  - Interactive prompts after initialization (e.g. ``--auth-retry
+    interact``) can use the standard input that is already open, but
+    ``/dev/tty`` is not accessible.
+
 --setcon context
   Apply SELinux ``context`` after initialization. This essentially
   provides the ability to restrict OpenVPN's rights to only network I/O
diff --git a/src/openvpn/Makefile.am b/src/openvpn/Makefile.am
index 4c8edea..bb68ae6 100644
--- a/src/openvpn/Makefile.am
+++ b/src/openvpn/Makefile.am
@@ -127,6 +127,7 @@ openvpn_SOURCES = \
 	ps.c ps.h \
 	push.c push.h \
 	push_util.c \
+	sandbox.c sandbox.h \
 	pushlist.h \
 	reflect_filter.c reflect_filter.h \
 	reliable.c reliable.h \
diff --git a/src/openvpn/dns.c b/src/openvpn/dns.c
index 8c6fd97..7cbcc9f 100644
--- a/src/openvpn/dns.c
+++ b/src/openvpn/dns.c
@@ -1025,6 +1025,15 @@ run_up_down_command(bool up, struct options *o, const struct tuntap *tt,
     msg(M_INFO, "dns %s command exited with status %d", up ? "up" : "down", status);
 }
 
+void
+dns_updown_runner_start(struct options *o, struct dns_updown_runner_info *duri)
+{
+    if (o->dns_options.updown && duri->required && duri->pid < 1)
+    {
+        run_updown_runner(o, duri);
+    }
+}
+
 #endif /* _WIN32 */
 
 void
diff --git a/src/openvpn/dns.h b/src/openvpn/dns.h
index 2c20b0e..add8d46 100644
--- a/src/openvpn/dns.h
+++ b/src/openvpn/dns.h
@@ -202,6 +202,19 @@ void dns_options_postprocess_pull(struct dns_options *o);
 void run_dns_up_down(bool up, struct options *o, const struct tuntap *tt,
                      struct dns_updown_runner_info *duri);
 
+#if !defined(_WIN32)
+/**
+ * Start the privileged dns-updown runner process now, if one is required
+ * and not running yet.  Used before the process drops privileges or enters
+ * a sandbox, so that the runner keeps the rights it needs to apply and
+ * revert DNS settings for the lifetime of the process.
+ *
+ * @param   o           Pointer to the program options
+ * @param   duri        Pointer to the updown runner info struct
+ */
+void dns_updown_runner_start(struct options *o, struct dns_updown_runner_info *duri);
+#endif
+
 /**
  * Prints configured DNS options.
  *
diff --git a/src/openvpn/init.c b/src/openvpn/init.c
index 49fcaf6..8ed09b3 100644
--- a/src/openvpn/init.c
+++ b/src/openvpn/init.c
@@ -1154,6 +1154,16 @@ do_uid_gid_chroot(struct context *c, bool no_delay)
 
     if (c0 && !c0->uid_gid_chroot_set)
     {
+#if !defined(_WIN32)
+        /* Start the privileged dns-updown runner before giving up any
+         * rights, so that DNS settings can be reverted later even from
+         * inside the sandbox. */
+        if (no_delay && c->options.sandbox != SANDBOX_NONE)
+        {
+            dns_updown_runner_start(&c->options, &c->persist.duri);
+        }
+#endif
+
         /* chroot if requested */
         if (c->options.chroot_dir)
         {
@@ -1208,6 +1218,20 @@ do_uid_gid_chroot(struct context *c, bool no_delay)
         }
 #endif
 
+        /* Restrict filesystem access last, so that it covers the same
+         * window as the privilege drop and paths resolve inside a chroot. */
+        if (c->options.sandbox != SANDBOX_NONE)
+        {
+            if (no_delay)
+            {
+                sandbox_apply(&c->options);
+            }
+            else if (c->first_time)
+            {
+                msg(M_INFO, "NOTE: sandbox %s", why_not);
+            }
+        }
+
         /* Privileges are going to be dropped by now (if requested), be sure
          * to prevent any future privilege dropping attempts from now on.
          */
@@ -3792,8 +3816,10 @@ do_init_first_time(struct context *c)
 
         c0->uid_gid_specified = user_defined || group_defined;
 
-        /* fork the dns script runner to preserve root? */
-        c->persist.duri.required = user_defined;
+        /* fork the dns script runner to preserve root? With --sandbox it
+         * is always needed, as the sandboxed process cannot run the
+         * dns-updown command itself. */
+        c->persist.duri.required = user_defined || c->options.sandbox != SANDBOX_NONE;
 
         /* perform postponed chdir if --daemon */
         if (c->did_we_daemonize && c->options.cd_dir == NULL)
diff --git a/src/openvpn/options.c b/src/openvpn/options.c
index 1e0b4d8..6c91af7 100644
--- a/src/openvpn/options.c
+++ b/src/openvpn/options.c
@@ -354,6 +354,8 @@ static const char usage_message[] =
 #ifdef ENABLE_SELINUX
     "--setcon context: Apply this SELinux context after initialization.\n"
 #endif
+    "--sandbox type  : Restrict filesystem access after initialization to the\n"
+    "                  files OpenVPN still needs. type: landlock (Linux)\n"
     "--cd dir        : Change to this directory before initialization.\n"
     "--daemon [name] : Become a daemon after initialization.\n"
     "                  The optional 'name' parameter will be passed\n"
@@ -2551,6 +2553,27 @@ options_postprocess_verify(const struct options *o)
 
     dns_options_verify(M_FATAL, &o->dns_options);
 
+    if (o->sandbox != SANDBOX_NONE)
+    {
+        /* User scripts and plugins would run inside the sandbox, and with
+         * no_new_privs set setuid helpers like sudo stop working. Refuse
+         * the combination instead of failing later at runtime. */
+        if (script_security() >= SSEC_SCRIPTS)
+        {
+            msg(M_USAGE, "--sandbox cannot be combined with --script-security 2 or higher; "
+                         "user-defined scripts are not supported in the sandbox yet");
+        }
+        if (o->plugin_list)
+        {
+            msg(M_USAGE, "--sandbox cannot be combined with --plugin");
+        }
+#ifdef ENABLE_IPROUTE
+        msg(M_USAGE, "--sandbox is not supported by builds that use the iproute2 binary "
+                     "(--enable-iproute2), as route and address changes on restart "
+                     "need to execute it");
+#endif
+    }
+
     if (dco_enabled(o))
     {
         if (o->enable_c2c)
@@ -4665,6 +4688,25 @@ add_option(struct options *options, char *p[], bool is_inline, const char *file,
         VERIFY_PERMISSION(OPT_P_GENERAL);
         options->chroot_dir = p[1];
     }
+    else if (streq(p[0], "sandbox") && p[1] && !p[2])
+    {
+        enum sandbox_type type;
+
+        VERIFY_PERMISSION(OPT_P_GENERAL);
+        if (!sandbox_parse_type(p[1], &type))
+        {
+            msg(msglevel, "--sandbox: unknown sandbox type '%s', supported types: landlock",
+                p[1]);
+            goto err;
+        }
+        if (!sandbox_type_supported(type))
+        {
+            msg(msglevel, "--sandbox %s is not supported on this platform or by this build",
+                p[1]);
+            goto err;
+        }
+        options->sandbox = type;
+    }
     else if (streq(p[0], "cd") && p[1] && !p[2])
     {
         VERIFY_PERMISSION(OPT_P_GENERAL);
diff --git a/src/openvpn/options.h b/src/openvpn/options.h
index 0112c5f..7701efa 100644
--- a/src/openvpn/options.h
+++ b/src/openvpn/options.h
@@ -42,6 +42,7 @@
 #include "clinat.h"
 #include "crypto_backend.h"
 #include "dns.h"
+#include "sandbox.h"
 
 
 /*
@@ -382,6 +383,7 @@ struct options
     const char *groupname;
     const char *chroot_dir;
     const char *cd_dir;
+    enum sandbox_type sandbox;
 #ifdef ENABLE_SELINUX
     char *selinux_context;
 #endif
diff --git a/src/openvpn/sandbox.c b/src/openvpn/sandbox.c
new file mode 100644
index 0000000..9ead80e
--- /dev/null
+++ b/src/openvpn/sandbox.c
@@ -0,0 +1,579 @@
+/*
+ *  OpenVPN -- An application to securely tunnel IP networks
+ *             over a single TCP/UDP port, with support for SSL/TLS-based
+ *             session authentication and key exchange,
+ *             packet encryption, packet authentication, and
+ *             packet compression.
+ *
+ *  Copyright (C) 2026 Robson Pereira <[email protected]>
+ *
+ *  This program is free software; you can redistribute it and/or modify
+ *  it under the terms of the GNU General Public License version 2
+ *  as published by the Free Software Foundation.
+ *
+ *  This program is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *  GNU General Public License for more details.
+ *
+ *  You should have received a copy of the GNU General Public License along
+ *  with this program; if not, see <https://www.gnu.org/licenses/>.
+ */
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "syshead.h"
+
+#include "sandbox.h"
+#include "buffer.h"
+#include "options.h"
+
+#include "memdbg.h"
+
+#if defined(TARGET_LINUX) && defined(HAVE_LINUX_LANDLOCK_H)
+#include <linux/landlock.h>
+#include <sys/prctl.h>
+#include <sys/syscall.h>
+#if defined(__NR_landlock_create_ruleset) && defined(__NR_landlock_add_rule) \
+    && defined(__NR_landlock_restrict_self)
+#define HAVE_LANDLOCK 1
+#endif
+#endif
+
+bool
+sandbox_parse_type(const char *name, enum sandbox_type *type)
+{
+    if (streq(name, "landlock"))
+    {
+        *type = SANDBOX_LANDLOCK;
+        return true;
+    }
+    return false;
+}
+
+const char *
+sandbox_type_name(enum sandbox_type type)
+{
+    switch (type)
+    {
+        case SANDBOX_LANDLOCK:
+            return "landlock";
+
+        case SANDBOX_NONE:
+        default:
+            return "none";
+    }
+}
+
+bool
+sandbox_type_supported(enum sandbox_type type)
+{
+    switch (type)
+    {
+        case SANDBOX_NONE:
+            return true;
+
+        case SANDBOX_LANDLOCK:
+#ifdef HAVE_LANDLOCK
+            return true;
+#else
+            return false;
+#endif
+
+        default:
+            return false;
+    }
+}
+
+void
+sandbox_rules_add(struct sandbox_rules *rules, const char *path, unsigned int flags,
+                  struct gc_arena *gc)
+{
+    if (!path)
+    {
+        return;
+    }
+
+    if (rules->len == rules->capacity)
+    {
+        size_t capacity = rules->capacity ? rules->capacity * 2 : 32;
+        struct sandbox_rule *grown = gc_malloc(capacity * sizeof(*grown), true, gc);
+        if (rules->len)
+        {
+            memcpy(grown, rules->rules, rules->len * sizeof(*grown));
+        }
+        rules->rules = grown;
+        rules->capacity = capacity;
+    }
+
+    rules->rules[rules->len].path = path;
+    rules->rules[rules->len].flags = flags;
+    rules->len++;
+}
+
+/**
+ * Read access for files named by options.  They are marked replaceable,
+ * because they are commonly updated by writing a new file and renaming it
+ * over the old one: a renewed CRL, certificates renewed before a SIGHUP,
+ * or the configuration file saved by an editor.
+ */
+#define OPTION_READ (SANDBOX_READ | SANDBOX_REPLACEABLE)
+
+/**
+ * Add a file named by an option, unless it was given inline or as "stdin"
+ * (both are read once at startup and never again).
+ */
+static void
+add_option_file(struct sandbox_rules *rules, const char *file, bool is_inline,
+                unsigned int flags, struct gc_arena *gc)
+{
+    if (file && !is_inline && !streq(file, "stdin"))
+    {
+        sandbox_rules_add(rules, file, flags, gc);
+    }
+}
+
+static void
+add_connection_entry(struct sandbox_rules *rules, const struct connection_entry *ce,
+                     struct gc_arena *gc)
+{
+    /* tls-auth/tls-crypt keys are read again on SIGHUP */
+    add_option_file(rules, ce->tls_auth_file, ce->tls_auth_file_inline, OPTION_READ, gc);
+    add_option_file(rules, ce->tls_crypt_file, ce->tls_crypt_file_inline, OPTION_READ, gc);
+    add_option_file(rules, ce->tls_crypt_v2_file, ce->tls_crypt_v2_file_inline, OPTION_READ,
+                    gc);
+
+    /* proxy credentials are read on every (re)connect */
+    if (ce->http_proxy_options)
+    {
+        const struct http_proxy_options *hpo = ce->http_proxy_options;
+        add_option_file(rules, hpo->auth_file, false, OPTION_READ, gc);
+        add_option_file(rules, hpo->auth_file_up, hpo->inline_creds, OPTION_READ, gc);
+    }
+    add_option_file(rules, ce->socks_proxy_authfile, false, OPTION_READ, gc);
+}
+
+#ifdef TARGET_LINUX
+/**
+ * System files and device nodes OpenVPN or the C library may open after
+ * initialization.  Shared libraries are readable so that NSS modules and
+ * OpenSSL providers can still be loaded on first use.
+ */
+static const struct sandbox_rule linux_system_rules[] = {
+    /* name resolution, needed to re-resolve --remote on reconnect */
+    { "/etc/resolv.conf", SANDBOX_READ | SANDBOX_REPLACEABLE },
+    { "/etc/hosts", SANDBOX_READ | SANDBOX_REPLACEABLE },
+    { "/etc/nsswitch.conf", SANDBOX_READ },
+    { "/etc/host.conf", SANDBOX_READ },
+    { "/etc/gai.conf", SANDBOX_READ },
+    { "/etc/services", SANDBOX_READ },
+    /* time zone, for log timestamps */
+    { "/etc/localtime", SANDBOX_READ },
+    { "/usr/share/zoneinfo", SANDBOX_READ },
+    /* dynamic loader and libraries */
+    { "/etc/ld.so.cache", SANDBOX_READ },
+    { "/lib", SANDBOX_READ },
+    { "/lib64", SANDBOX_READ },
+    { "/usr/lib", SANDBOX_READ },
+    { "/usr/lib64", SANDBOX_READ },
+    /* device nodes; the tun device is reopened on restarts without
+     * --persist-tun when running as root.  /dev/tty is deliberately not
+     * included, as write and ioctl access to the controlling terminal
+     * would allow input injection (TIOCSTI) outside the sandbox. */
+    { "/dev/null", SANDBOX_DEVICE },
+    { "/dev/random", SANDBOX_READ },
+    { "/dev/urandom", SANDBOX_READ },
+    { "/dev/net/tun", SANDBOX_DEVICE },
+    /* checked by DCO when options are re-evaluated on SIGHUP */
+    { "/sys/module/ovpn", SANDBOX_READ },
+};
+#endif
+
+void
+sandbox_build_rules(const struct options *o, struct sandbox_rules *rules, struct gc_arena *gc)
+{
+    /* SIGHUP re-reads the configuration file */
+    add_option_file(rules, o->config, false, OPTION_READ, gc);
+
+    /* TLS material, read again on SIGHUP */
+    add_option_file(rules, o->ca_file, o->ca_file_inline, OPTION_READ, gc);
+    add_option_file(rules, o->ca_path, false, OPTION_READ, gc);
+    add_option_file(rules, o->dh_file, o->dh_file_inline, OPTION_READ, gc);
+    add_option_file(rules, o->cert_file, o->cert_file_inline, OPTION_READ, gc);
+    add_option_file(rules, o->extra_certs_file, o->extra_certs_file_inline, OPTION_READ, gc);
+    add_option_file(rules, o->priv_key_file, o->priv_key_file_inline, OPTION_READ, gc);
+    add_option_file(rules, o->pkcs12_file, o->pkcs12_file_inline, OPTION_READ, gc);
+    add_option_file(rules, o->key_pass_file, false, OPTION_READ, gc);
+    add_option_file(rules, o->tls_auth_file, o->tls_auth_file_inline, OPTION_READ, gc);
+    add_option_file(rules, o->tls_crypt_file, o->tls_crypt_file_inline, OPTION_READ, gc);
+    add_option_file(rules, o->tls_crypt_v2_file, o->tls_crypt_v2_file_inline, OPTION_READ, gc);
+
+    /* the CRL file (or directory with --crl-verify dir) is checked for
+     * changes and reloaded during TLS handshakes */
+    add_option_file(rules, o->crl_file, o->crl_file_inline, OPTION_READ, gc);
+
+    /* credentials read on every (re)connect or restart */
+    add_option_file(rules, o->auth_user_pass_file, o->auth_user_pass_file_inline, OPTION_READ,
+                    gc);
+    add_option_file(rules, o->auth_token_secret_file, o->auth_token_secret_file_inline,
+                    OPTION_READ, gc);
+#ifdef ENABLE_MANAGEMENT
+    add_option_file(rules, o->management_user_pass, false, OPTION_READ, gc);
+#endif
+
+    if (o->connection_list)
+    {
+        for (int i = 0; i < o->connection_list->len; ++i)
+        {
+            add_connection_entry(rules, o->connection_list->array[i], gc);
+        }
+    }
+    else
+    {
+        add_connection_entry(rules, &o->ce, gc);
+    }
+
+    /* server: per-client configuration files are read on each connect */
+    add_option_file(rules, o->client_config_dir, false, OPTION_READ, gc);
+
+    /* files rewritten periodically, and recreated on SIGHUP */
+    add_option_file(rules, o->status_file, false, SANDBOX_READ | SANDBOX_WRITE, gc);
+    add_option_file(rules, o->ifconfig_pool_persist_filename, false,
+                    SANDBOX_READ | SANDBOX_WRITE, gc);
+
+    /* directories in which OpenVPN creates and removes files */
+    add_option_file(rules, o->tmp_dir, false, SANDBOX_CREATE, gc);
+    add_option_file(rules, o->tls_export_peer_cert_dir, false, SANDBOX_CREATE, gc);
+#if PORT_SHARE
+    add_option_file(rules, o->port_share_journal_dir, false, SANDBOX_CREATE, gc);
+#endif
+
+#ifdef TARGET_LINUX
+    for (size_t i = 0; i < SIZE(linux_system_rules); ++i)
+    {
+        sandbox_rules_add(rules, linux_system_rules[i].path, linux_system_rules[i].flags, gc);
+    }
+#endif
+}
+
+#ifdef HAVE_LANDLOCK
+
+static inline int
+landlock_create_ruleset(const struct landlock_ruleset_attr *attr, size_t size, uint32_t flags)
+{
+    return (int)syscall(__NR_landlock_create_ruleset, attr, size, flags);
+}
+
+static inline int
+landlock_add_rule(int ruleset_fd, enum landlock_rule_type type, const void *attr,
+                  uint32_t flags)
+{
+    return (int)syscall(__NR_landlock_add_rule, ruleset_fd, type, attr, flags);
+}
+
+static inline int
+landlock_restrict_self(int ruleset_fd, uint32_t flags)
+{
+    return (int)syscall(__NR_landlock_restrict_self, ruleset_fd, flags);
+}
+
+/**
+ * All filesystem rights known to the given Landlock ABI version.  Handling
+ * every right we know of means anything not explicitly allowed is denied.
+ */
+static uint64_t
+landlock_handled_fs(int abi)
+{
+    uint64_t access = LANDLOCK_ACCESS_FS_EXECUTE | LANDLOCK_ACCESS_FS_WRITE_FILE
+                      | LANDLOCK_ACCESS_FS_READ_FILE | LANDLOCK_ACCESS_FS_READ_DIR
+                      | LANDLOCK_ACCESS_FS_REMOVE_DIR | LANDLOCK_ACCESS_FS_REMOVE_FILE
+                      | LANDLOCK_ACCESS_FS_MAKE_CHAR | LANDLOCK_ACCESS_FS_MAKE_DIR
+                      | LANDLOCK_ACCESS_FS_MAKE_REG | LANDLOCK_ACCESS_FS_MAKE_SOCK
+                      | LANDLOCK_ACCESS_FS_MAKE_FIFO | LANDLOCK_ACCESS_FS_MAKE_BLOCK
+                      | LANDLOCK_ACCESS_FS_MAKE_SYM;
+#ifdef LANDLOCK_ACCESS_FS_REFER
+    if (abi >= 2)
+    {
+        access |= LANDLOCK_ACCESS_FS_REFER;
+    }
+#endif
+#ifdef LANDLOCK_ACCESS_FS_TRUNCATE
+    if (abi >= 3)
+    {
+        access |= LANDLOCK_ACCESS_FS_TRUNCATE;
+    }
+#endif
+#ifdef LANDLOCK_ACCESS_FS_IOCTL_DEV
+    if (abi >= 5)
+    {
+        access |= LANDLOCK_ACCESS_FS_IOCTL_DEV;
+    }
+#endif
+    return access;
+}
+
+/** Rights that Landlock accepts on a rule for a non-directory */
+static uint64_t
+landlock_file_rights(void)
+{
+    uint64_t access = LANDLOCK_ACCESS_FS_EXECUTE | LANDLOCK_ACCESS_FS_WRITE_FILE
+                      | LANDLOCK_ACCESS_FS_READ_FILE;
+#ifdef LANDLOCK_ACCESS_FS_TRUNCATE
+    access |= LANDLOCK_ACCESS_FS_TRUNCATE;
+#endif
+#ifdef LANDLOCK_ACCESS_FS_IOCTL_DEV
+    access |= LANDLOCK_ACCESS_FS_IOCTL_DEV;
+#endif
+    return access;
+}
+
+static uint64_t
+landlock_truncate(void)
+{
+#ifdef LANDLOCK_ACCESS_FS_TRUNCATE
+    return LANDLOCK_ACCESS_FS_TRUNCATE;
+#else
+    return 0;
+#endif
+}
+
+/** Map abstract sandbox flags to Landlock filesystem rights */
+static uint64_t
+landlock_rights(unsigned int flags)
+{
+    uint64_t access = 0;
+
+    if (flags & SANDBOX_READ)
+    {
+        access |= LANDLOCK_ACCESS_FS_READ_FILE | LANDLOCK_ACCESS_FS_READ_DIR;
+    }
+    if (flags & SANDBOX_WRITE)
+    {
+        access |= LANDLOCK_ACCESS_FS_WRITE_FILE | landlock_truncate();
+    }
+    if (flags & SANDBOX_CREATE)
+    {
+        access |= LANDLOCK_ACCESS_FS_READ_FILE | LANDLOCK_ACCESS_FS_READ_DIR
+                  | LANDLOCK_ACCESS_FS_WRITE_FILE | landlock_truncate()
+                  | LANDLOCK_ACCESS_FS_MAKE_REG | LANDLOCK_ACCESS_FS_REMOVE_FILE;
+    }
+    if (flags & SANDBOX_DEVICE)
+    {
+        access |= LANDLOCK_ACCESS_FS_READ_FILE | LANDLOCK_ACCESS_FS_WRITE_FILE
+                  | landlock_truncate();
+#ifdef LANDLOCK_ACCESS_FS_IOCTL_DEV
+        access |= LANDLOCK_ACCESS_FS_IOCTL_DEV;
+#endif
+    }
+    return access;
+}
+
+/**
+ * For a file that may be replaced by rename, return the directory that
+ * holds the real file (after resolving symbolic links), unless that is
+ * / or /etc; otherwise return \c path.
+ */
+static const char *
+replaceable_target(const char *path, char *buf, size_t size)
+{
+    char real[PATH_MAX];
+    if (!realpath(path, real))
+    {
+        return path;
+    }
+    char *slash = strrchr(real, '/');
+    if (!slash || slash == real)
+    {
+        return path;
+    }
+    *slash = '\0';
+    size_t len = strlen(real);
+    if (streq(real, "/etc") || len >= size)
+    {
+        return path;
+    }
+    memcpy(buf, real, len + 1);
+    return buf;
+}
+
+/**
+ * Open \c path with O_PATH and stat it.  Return the descriptor, or -1
+ * after logging why the path is skipped.
+ */
+static int
+open_rule_path(const char *path, struct stat *st)
+{
+    int fd = open(path, O_PATH | O_CLOEXEC);
+    if (fd < 0)
+    {
+        msg(D_LOW, "Sandbox: skipping '%s': %s", path, strerror(errno));
+        return -1;
+    }
+    if (fstat(fd, st) != 0)
+    {
+        msg(D_LOW, "Sandbox: skipping '%s': %s", path, strerror(errno));
+        close(fd);
+        return -1;
+    }
+    return fd;
+}
+
+/** Add one rule to the ruleset, return true if it was added */
+static bool
+landlock_add_path(int ruleset_fd, const struct sandbox_rule *rule, uint64_t handled)
+{
+    char dirbuf[PATH_MAX];
+    const char *path = rule->path;
+    struct stat st;
+
+    int fd = open_rule_path(path, &st);
+    if (fd < 0)
+    {
+        return false;
+    }
+
+    /* only files can be replaced; a directory rule already covers new files */
+    if ((rule->flags & SANDBOX_REPLACEABLE) && !S_ISDIR(st.st_mode))
+    {
+        const char *dir = replaceable_target(path, dirbuf, sizeof(dirbuf));
+        if (dir != path)
+        {
+            close(fd);
+            path = dir;
+            fd = open_rule_path(path, &st);
+            if (fd < 0)
+            {
+                return false;
+            }
+        }
+    }
+
+    struct landlock_path_beneath_attr attr = {
+        .allowed_access = landlock_rights(rule->flags) & handled,
+        .parent_fd = fd,
+    };
+    if (!S_ISDIR(st.st_mode))
+    {
+        attr.allowed_access &= landlock_file_rights();
+    }
+
+    bool added = false;
+    if (attr.allowed_access == 0)
+    {
+        msg(D_LOW, "Sandbox: skipping '%s': no applicable access rights", path);
+    }
+    else if (landlock_add_rule(ruleset_fd, LANDLOCK_RULE_PATH_BENEATH, &attr, 0) != 0)
+    {
+        msg(D_LOW, "Sandbox: skipping '%s': adding Landlock rule failed: %s", path,
+            strerror(errno));
+    }
+    else
+    {
+        msg(D_LOW, "Sandbox: allowing '%s' (flags 0x%x)", path, rule->flags);
+        added = true;
+    }
+
+    close(fd);
+    return added;
+}
+
+int
+sandbox_landlock_restrict(const struct sandbox_rules *rules, msglvl_t msglevel)
+{
+    int abi = landlock_create_ruleset(NULL, 0, LANDLOCK_CREATE_RULESET_VERSION);
+    if (abi < 0)
+    {
+        msg(msglevel, "Sandbox: Landlock is not available in the running kernel (%s). "
+                      "It needs Linux 5.13 or later with Landlock enabled, "
+                      "see the lsm= kernel parameter.",
+            strerror(errno));
+        return -1;
+    }
+
+    const uint64_t handled = landlock_handled_fs(abi);
+    struct landlock_ruleset_attr ruleset_attr = {
+        .handled_access_fs = handled,
+    };
+
+    int ruleset_fd = landlock_create_ruleset(&ruleset_attr, sizeof(ruleset_attr), 0);
+    if (ruleset_fd < 0)
+    {
+        msg(msglevel, "Sandbox: creating Landlock ruleset failed: %s", strerror(errno));
+        return -1;
+    }
+
+    size_t added = 0;
+    for (size_t i = 0; i < rules->len; ++i)
+    {
+        if (landlock_add_path(ruleset_fd, &rules->rules[i], handled))
+        {
+            added++;
+        }
+    }
+
+    /* required for an unprivileged process; also stops any child from
+     * regaining privileges through setuid binaries */
+    if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) != 0)
+    {
+        msg(msglevel, "Sandbox: prctl(PR_SET_NO_NEW_PRIVS) failed: %s", strerror(errno));
+        close(ruleset_fd);
+        return -1;
+    }
+
+    if (landlock_restrict_self(ruleset_fd, 0) != 0)
+    {
+        msg(msglevel, "Sandbox: applying Landlock ruleset failed: %s", strerror(errno));
+        close(ruleset_fd);
+        return -1;
+    }
+
+    close(ruleset_fd);
+    msg(D_LOW, "Sandbox: %zu of %zu Landlock rules added", added, rules->len);
+    return abi;
+}
+
+#else  /* ifdef HAVE_LANDLOCK */
+
+int
+sandbox_landlock_restrict(const struct sandbox_rules *rules, msglvl_t msglevel)
+{
+    (void)rules;
+    msg(msglevel, "Sandbox: Landlock is not supported by this build of OpenVPN");
+    return -1;
+}
+
+#endif /* ifdef HAVE_LANDLOCK */
+
+void
+sandbox_apply(const struct options *o)
+{
+    if (o->sandbox == SANDBOX_NONE)
+    {
+        return;
+    }
+
+    struct gc_arena gc = gc_new();
+    struct sandbox_rules rules = { 0 };
+    sandbox_build_rules(o, &rules, &gc);
+
+    switch (o->sandbox)
+    {
+        case SANDBOX_LANDLOCK:
+        {
+            int abi = sandbox_landlock_restrict(&rules, M_FATAL);
+            msg(M_INFO, "Sandbox: Landlock (ABI v%d) applied, filesystem access is "
+                        "now limited to the files OpenVPN needs",
+                abi);
+            break;
+        }
+
+        default:
+            msg(M_FATAL, "Sandbox: '%s' is not supported by this build of OpenVPN",
+                sandbox_type_name(o->sandbox));
+            break;
+    }
+
+    gc_free(&gc);
+}
diff --git a/src/openvpn/sandbox.h b/src/openvpn/sandbox.h
new file mode 100644
index 0000000..4be6de0
--- /dev/null
+++ b/src/openvpn/sandbox.h
@@ -0,0 +1,149 @@
+/*
+ *  OpenVPN -- An application to securely tunnel IP networks
+ *             over a single TCP/UDP port, with support for SSL/TLS-based
+ *             session authentication and key exchange,
+ *             packet encryption, packet authentication, and
+ *             packet compression.
+ *
+ *  Copyright (C) 2026 Robson Pereira <[email protected]>
+ *
+ *  This program is free software; you can redistribute it and/or modify
+ *  it under the terms of the GNU General Public License version 2
+ *  as published by the Free Software Foundation.
+ *
+ *  This program is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *  GNU General Public License for more details.
+ *
+ *  You should have received a copy of the GNU General Public License along
+ *  with this program; if not, see <https://www.gnu.org/licenses/>.
+ */
+
+/**
+ * @file
+ * Optional process sandbox (\c --sandbox), applied once after initialization.
+ *
+ * The sandbox is split into two layers:
+ *
+ *  - A platform independent list of filesystem rules (path + abstract
+ *    access flags) that is derived from the options in use.  This is what
+ *    OpenVPN may still need to touch after initialization, e.g. to reload
+ *    a CRL, re-read keys on SIGUSR1 or rewrite the status file.
+ *
+ *  - A backend that turns this list into an OS specific restriction.  The
+ *    only backend so far is Landlock on Linux; others (e.g. macOS) can be
+ *    added as further values of enum sandbox_type without new options.
+ */
+
+#ifndef SANDBOX_H
+#define SANDBOX_H
+
+#include <stdbool.h>
+
+#include "error.h"
+
+struct options;
+struct gc_arena;
+
+/** Sandbox backends selectable with --sandbox */
+enum sandbox_type
+{
+    SANDBOX_NONE = 0,
+    SANDBOX_LANDLOCK,
+};
+
+/* Abstract access flags of a sandbox rule */
+
+/** Read the file, or read all files and list all directories below it */
+#define SANDBOX_READ        (1u << 0)
+/** Write to (and truncate) the file, or any existing file below it */
+#define SANDBOX_WRITE       (1u << 1)
+/** Create, write and remove regular files below this directory */
+#define SANDBOX_CREATE      (1u << 2)
+/** Read, write and ioctl() on this device node */
+#define SANDBOX_DEVICE      (1u << 3)
+/**
+ * The file may be replaced by a new one (rename) rather than rewritten in
+ * place, e.g. a renewed CRL, a configuration file saved by an editor, or
+ * /etc/resolv.conf managed by systemd-resolved.  Landlock rules are bound
+ * to inodes, so a rule for the file itself would not cover its successor.
+ * Grant the access to the directory holding the real file instead, unless
+ * that directory is / or /etc.  Has no effect on directories.
+ */
+#define SANDBOX_REPLACEABLE (1u << 4)
+
+/** One path the sandboxed process may still access */
+struct sandbox_rule
+{
+    const char *path;
+    unsigned int flags;
+};
+
+/** A growable list of sandbox rules, allocated from a gc_arena */
+struct sandbox_rules
+{
+    struct sandbox_rule *rules;
+    size_t len;
+    size_t capacity;
+};
+
+/**
+ * Parse the argument of --sandbox.
+ *
+ * @param name  the backend name given by the user
+ * @param type  set to the matching backend on success
+ * @return      true if \c name is a backend known to OpenVPN, even if it is
+ *              not available in this build (see sandbox_type_supported())
+ */
+bool sandbox_parse_type(const char *name, enum sandbox_type *type);
+
+/** Return the --sandbox argument for a backend, for logging */
+const char *sandbox_type_name(enum sandbox_type type);
+
+/** Return whether this build can apply the given backend */
+bool sandbox_type_supported(enum sandbox_type type);
+
+/**
+ * Build the list of filesystem rules needed after initialization for the
+ * given options: files OpenVPN re-reads or rewrites, plus the system files
+ * needed for name resolution, time zones and device nodes.
+ *
+ * Inline files and unset options are skipped.  Paths are not checked for
+ * existence here; missing paths are skipped when the sandbox is applied.
+ *
+ * @param o      the options in use
+ * @param rules  the list to append to
+ * @param gc     arena used for the list
+ */
+void sandbox_build_rules(const struct options *o, struct sandbox_rules *rules,
+                         struct gc_arena *gc);
+
+/**
+ * Append a rule to a rule list.  NULL paths are ignored.
+ */
+void sandbox_rules_add(struct sandbox_rules *rules, const char *path, unsigned int flags,
+                       struct gc_arena *gc);
+
+/**
+ * Restrict the calling process with the Landlock backend so that only the
+ * given rules apply.  This is irreversible and inherited by child processes.
+ *
+ * @param rules     the rules to allow
+ * @param msglevel  message level used for failures
+ * @return          the Landlock ABI version used (>= 1) on success, or
+ *                  -1 on failure, after logging at \c msglevel
+ */
+int sandbox_landlock_restrict(const struct sandbox_rules *rules, msglvl_t msglevel);
+
+/**
+ * Apply the sandbox selected with --sandbox, if any.  Called once, after
+ * the user/group drop, chroot and SELinux context switch.  Any failure is
+ * fatal: the user explicitly asked for the sandbox, so OpenVPN must not
+ * continue without it.
+ *
+ * @param o  the options in use
+ */
+void sandbox_apply(const struct options *o);
+
+#endif /* SANDBOX_H */
diff --git a/tests/unit_tests/openvpn/Makefile.am b/tests/unit_tests/openvpn/Makefile.am
index de498d2..db17f25 100644
--- a/tests/unit_tests/openvpn/Makefile.am
+++ b/tests/unit_tests/openvpn/Makefile.am
@@ -19,6 +19,7 @@ test_binaries = argv_testdriver \
 	pkt_testdriver \
 	provider_testdriver \
 	push_update_msg_testdriver \
+	sandbox_testdriver \
 	socket_testdriver \
 	ssl_testdriver \
 	user_pass_testdriver
@@ -398,6 +399,19 @@ mbuf_testdriver_SOURCES = test_mbuf.c \
 	$(top_srcdir)/src/openvpn/platform.c \
 	$(top_srcdir)/src/openvpn/mbuf.c
 
+sandbox_testdriver_CFLAGS  = \
+	-I$(top_srcdir)/include -I$(top_srcdir)/src/compat -I$(top_srcdir)/src/openvpn \
+	@TEST_CFLAGS@
+sandbox_testdriver_LDFLAGS = @TEST_LDFLAGS@
+sandbox_testdriver_SOURCES = test_sandbox.c \
+	mock_msg.c test_common.h \
+	mock_get_random.c \
+	$(top_srcdir)/src/compat/compat-strlcpy.c \
+	$(top_srcdir)/src/openvpn/buffer.c \
+	$(top_srcdir)/src/openvpn/platform.c \
+	$(top_srcdir)/src/openvpn/win32-util.c \
+	$(top_srcdir)/src/openvpn/sandbox.c
+
 misc_testdriver_CFLAGS  = \
 	-I$(top_srcdir)/include -I$(top_srcdir)/src/compat -I$(top_srcdir)/src/openvpn \
 	-DSOURCEDIR=\"$(top_srcdir)\" @TEST_CFLAGS@
diff --git a/tests/unit_tests/openvpn/test_sandbox.c b/tests/unit_tests/openvpn/test_sandbox.c
new file mode 100644
index 0000000..1a5639e
--- /dev/null
+++ b/tests/unit_tests/openvpn/test_sandbox.c
@@ -0,0 +1,432 @@
+/*
+ *  OpenVPN -- An application to securely tunnel IP networks
+ *             over a single UDP port, with support for SSL/TLS-based
+ *             session authentication and key exchange,
+ *             packet encryption, packet authentication, and
+ *             packet compression.
+ *
+ *  Copyright (C) 2026 Robson Pereira <[email protected]>
+ *
+ *  This program is free software; you can redistribute it and/or modify
+ *  it under the terms of the GNU General Public License version 2
+ *  as published by the Free Software Foundation.
+ *
+ *  This program is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *  GNU General Public License for more details.
+ *
+ *  You should have received a copy of the GNU General Public License along
+ *  with this program; if not, see <https://www.gnu.org/licenses/>.
+ */
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "syshead.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdarg.h>
+#include <string.h>
+#include <setjmp.h>
+#include <cmocka.h>
+
+#include "options.h"
+#include "sandbox.h"
+#include "test_common.h"
+
+#ifndef _WIN32
+#include <sys/wait.h>
+#endif
+
+/* files named by options are readable and may be replaced by rename */
+#define OPTION_READ (SANDBOX_READ | SANDBOX_REPLACEABLE)
+
+/* Return the flags of the first rule for path, or -1 if there is none */
+static int
+rule_flags(const struct sandbox_rules *rules, const char *path)
+{
+    for (size_t i = 0; i < rules->len; ++i)
+    {
+        if (streq(rules->rules[i].path, path))
+        {
+            return (int)rules->rules[i].flags;
+        }
+    }
+    return -1;
+}
+
+static void
+test_parse_type(void **state)
+{
+    enum sandbox_type type = SANDBOX_NONE;
+
+    assert_true(sandbox_parse_type("landlock", &type));
+    assert_int_equal(type, SANDBOX_LANDLOCK);
+    assert_string_equal(sandbox_type_name(type), "landlock");
+
+    type = SANDBOX_NONE;
+    assert_false(sandbox_parse_type("Landlock", &type));
+    assert_false(sandbox_parse_type("seccomp", &type));
+    assert_false(sandbox_parse_type("", &type));
+    assert_int_equal(type, SANDBOX_NONE);
+
+    assert_true(sandbox_type_supported(SANDBOX_NONE));
+#if defined(TARGET_LINUX) && defined(HAVE_LINUX_LANDLOCK_H)
+    assert_true(sandbox_type_supported(SANDBOX_LANDLOCK));
+#else
+    assert_false(sandbox_type_supported(SANDBOX_LANDLOCK));
+#endif
+}
+
+static void
+test_rules_add_grows(void **state)
+{
+    struct gc_arena gc = gc_new();
+    struct sandbox_rules rules = { 0 };
+    char names[100][16];
+
+    for (int i = 0; i < 100; ++i)
+    {
+        snprintf(names[i], sizeof(names[i]), "/path/%d", i);
+        sandbox_rules_add(&rules, names[i], (unsigned int)i, &gc);
+    }
+    /* NULL paths are ignored */
+    sandbox_rules_add(&rules, NULL, SANDBOX_READ, &gc);
+
+    assert_int_equal(rules.len, 100);
+    for (int i = 0; i < 100; ++i)
+    {
+        assert_string_equal(rules.rules[i].path, names[i]);
+        assert_int_equal(rules.rules[i].flags, i);
+    }
+    gc_free(&gc);
+}
+
+static void
+test_build_rules_from_options(void **state)
+{
+    struct gc_arena gc = gc_new();
+    struct options o;
+    struct connection_entry ce1, ce2;
+    struct connection_entry *entries[2] = { &ce1, &ce2 };
+    struct connection_list list = { .capacity = 2, .len = 2, .array = entries };
+    struct http_proxy_options hpo;
+    struct sandbox_rules rules = { 0 };
+
+    CLEAR(o);
+    CLEAR(ce1);
+    CLEAR(ce2);
+    CLEAR(hpo);
+
+    o.config = "/etc/openvpn/server.conf";
+    o.ca_file = "/etc/openvpn/ca.crt";
+    o.cert_file = "/etc/openvpn/server.crt";
+    o.priv_key_file = "-----BEGIN PRIVATE KEY-----";
+    o.priv_key_file_inline = true;
+    o.crl_file = "/etc/openvpn/crl.pem";
+    o.auth_user_pass_file = "stdin";
+    o.status_file = "/run/openvpn/status.log";
+    o.ifconfig_pool_persist_filename = "/var/lib/openvpn/ipp.txt";
+    o.client_config_dir = "/etc/openvpn/ccd";
+    o.tmp_dir = "/run/openvpn/tmp";
+
+    ce1.tls_crypt_file = "/etc/openvpn/tc.key";
+    ce2.tls_auth_file = "inline tls-auth key";
+    ce2.tls_auth_file_inline = true;
+    ce2.http_proxy_options = &hpo;
+    hpo.auth_file = "/etc/openvpn/proxy-auth";
+    hpo.auth_file_up = "user\npass";
+    hpo.inline_creds = true;
+    ce2.socks_proxy_authfile = "/etc/openvpn/socks-auth";
+    o.connection_list = &list;
+
+    sandbox_build_rules(&o, &rules, &gc);
+
+    assert_int_equal(rule_flags(&rules, "/etc/openvpn/server.conf"), OPTION_READ);
+    assert_int_equal(rule_flags(&rules, "/etc/openvpn/ca.crt"), OPTION_READ);
+    assert_int_equal(rule_flags(&rules, "/etc/openvpn/server.crt"), OPTION_READ);
+    assert_int_equal(rule_flags(&rules, "/etc/openvpn/crl.pem"), OPTION_READ);
+    assert_int_equal(rule_flags(&rules, "/etc/openvpn/ccd"), OPTION_READ);
+    assert_int_equal(rule_flags(&rules, "/etc/openvpn/tc.key"), OPTION_READ);
+    assert_int_equal(rule_flags(&rules, "/etc/openvpn/proxy-auth"), OPTION_READ);
+    assert_int_equal(rule_flags(&rules, "/etc/openvpn/socks-auth"), OPTION_READ);
+    assert_int_equal(rule_flags(&rules, "/run/openvpn/status.log"),
+                     SANDBOX_READ | SANDBOX_WRITE);
+    assert_int_equal(rule_flags(&rules, "/var/lib/openvpn/ipp.txt"),
+                     SANDBOX_READ | SANDBOX_WRITE);
+    assert_int_equal(rule_flags(&rules, "/run/openvpn/tmp"), SANDBOX_CREATE);
+
+    /* inline material and stdin are never re-read, so never allowed */
+    assert_int_equal(rule_flags(&rules, "-----BEGIN PRIVATE KEY-----"), -1);
+    assert_int_equal(rule_flags(&rules, "inline tls-auth key"), -1);
+    assert_int_equal(rule_flags(&rules, "user\npass"), -1);
+    assert_int_equal(rule_flags(&rules, "stdin"), -1);
+
+    for (size_t i = 0; i < rules.len; ++i)
+    {
+        assert_non_null(rules.rules[i].path);
+    }
+
+#ifdef TARGET_LINUX
+    assert_int_equal(rule_flags(&rules, "/etc/resolv.conf"),
+                     SANDBOX_READ | SANDBOX_REPLACEABLE);
+    assert_int_equal(rule_flags(&rules, "/dev/net/tun"), SANDBOX_DEVICE);
+    /* the controlling terminal must never be writable (TIOCSTI) */
+    assert_int_equal(rule_flags(&rules, "/dev/tty"), -1);
+#endif
+
+    gc_free(&gc);
+}
+
+/* Without a connection list, the single connection entry is used */
+static void
+test_build_rules_single_entry(void **state)
+{
+    struct gc_arena gc = gc_new();
+    struct options o;
+    struct sandbox_rules rules = { 0 };
+
+    CLEAR(o);
+    o.ce.tls_crypt_v2_file = "/etc/openvpn/client-tc2.key";
+    sandbox_build_rules(&o, &rules, &gc);
+
+    assert_int_equal(rule_flags(&rules, "/etc/openvpn/client-tc2.key"), OPTION_READ);
+    gc_free(&gc);
+}
+
+#if defined(TARGET_LINUX) && defined(HAVE_LINUX_LANDLOCK_H)
+
+#define CHILD_SKIP 77
+
+static char tmpdir[64];
+
+static void
+make_path(char *buf, size_t size, const char *name)
+{
+    snprintf(buf, size, "%s/%s", tmpdir, name);
+}
+
+static void
+write_file(const char *path, const char *content)
+{
+    FILE *fp = fopen(path, "w");
+    assert_non_null(fp);
+    assert_int_equal(fputs(content, fp) >= 0, 1);
+    assert_int_equal(fclose(fp), 0);
+}
+
+/* Return 0 if open succeeds, otherwise errno */
+static int
+try_open(const char *path, int flags)
+{
+    int fd = open(path, flags, 0600);
+    if (fd < 0)
+    {
+        return errno;
+    }
+    close(fd);
+    return 0;
+}
+
+#define CHILD_CHECK(cond)                                                            \
+    do                                                                               \
+    {                                                                                \
+        if (!(cond))                                                                 \
+        {                                                                            \
+            fprintf(stderr, "child check failed at line %d: %s\n", __LINE__, #cond); \
+            _exit(1);                                                                \
+        }                                                                            \
+    } while (0)
+
+/*
+ * Runs in a forked child: restrict to the test rules, then check that
+ * exactly the allowed access works.  The parent replaces a file between
+ * the two pipe handshakes to exercise SANDBOX_REPLACEABLE.
+ */
+static void
+landlock_child(int to_parent, int from_parent)
+{
+    struct gc_arena gc = gc_new();
+    struct sandbox_rules rules = { 0 };
+    char allowed[128], denied[128], rwdir[128], newfile[128], outside[128], status[128];
+    char link[128], realfile[128], conf[128];
+    char c = 'x';
+
+    make_path(allowed, sizeof(allowed), "allowed.txt");
+    make_path(denied, sizeof(denied), "denied.txt");
+    make_path(rwdir, sizeof(rwdir), "rw");
+    make_path(newfile, sizeof(newfile), "rw/new.txt");
+    make_path(outside, sizeof(outside), "outside.txt");
+    make_path(status, sizeof(status), "status.txt");
+    make_path(link, sizeof(link), "link.conf");
+    make_path(realfile, sizeof(realfile), "real/resolv.conf");
+    make_path(conf, sizeof(conf), "conf/server.conf");
+
+    sandbox_rules_add(&rules, allowed, SANDBOX_READ, &gc);
+    sandbox_rules_add(&rules, conf, OPTION_READ, &gc);
+    sandbox_rules_add(&rules, status, SANDBOX_READ | SANDBOX_WRITE, &gc);
+    sandbox_rules_add(&rules, rwdir, SANDBOX_CREATE, &gc);
+    sandbox_rules_add(&rules, link, SANDBOX_READ | SANDBOX_REPLACEABLE, &gc);
+    sandbox_rules_add(&rules, "/nonexistent/path/is/skipped", SANDBOX_READ, &gc);
+
+    if (sandbox_landlock_restrict(&rules, M_WARN) < 0)
+    {
+        _exit(CHILD_SKIP);
+    }
+
+    /* read-only file: read yes, write no */
+    CHILD_CHECK(try_open(allowed, O_RDONLY) == 0);
+    CHILD_CHECK(try_open(allowed, O_WRONLY) == EACCES);
+
+    /* status-like file: read, write and truncate */
+    CHILD_CHECK(try_open(status, O_RDWR | O_TRUNC) == 0);
+
+    /* anything not listed is denied, including creating new files */
+    CHILD_CHECK(try_open(denied, O_RDONLY) == EACCES);
+    CHILD_CHECK(try_open(outside, O_WRONLY | O_CREAT) == EACCES);
+    CHILD_CHECK(try_open("/etc/passwd", O_RDONLY) == EACCES);
+
+    /* create and remove files in a SANDBOX_CREATE directory */
+    CHILD_CHECK(try_open(newfile, O_WRONLY | O_CREAT) == 0);
+    CHILD_CHECK(unlink(newfile) == 0);
+    CHILD_CHECK(mkdir(newfile, 0700) != 0 && errno == EACCES);
+
+    /* executing anything is denied; if the exec did succeed, the shell
+     * exits with 3 and the parent sees the failure */
+    execl("/bin/sh", "sh", "-c", "exit 3", (char *)NULL);
+    CHILD_CHECK(errno == EACCES);
+
+    /* replaceable files (a symlink to a file, and a plain file) stay
+     * readable, but not writable, after being replaced by rename */
+    CHILD_CHECK(try_open(link, O_RDONLY) == 0);
+    CHILD_CHECK(try_open(conf, O_RDONLY) == 0);
+    CHILD_CHECK(write(to_parent, &c, 1) == 1);
+    CHILD_CHECK(read(from_parent, &c, 1) == 1);
+    CHILD_CHECK(try_open(link, O_RDONLY) == 0);
+    CHILD_CHECK(try_open(realfile, O_WRONLY) == EACCES);
+    CHILD_CHECK(try_open(conf, O_RDONLY) == 0);
+    CHILD_CHECK(try_open(conf, O_WRONLY) == EACCES);
+
+    gc_free(&gc);
+    _exit(0);
+}
+
+static void
+test_landlock_enforced(void **state)
+{
+    char path[128], path2[128];
+    int to_parent[2], from_parent[2];
+    char c;
+
+    if (!sandbox_type_supported(SANDBOX_LANDLOCK))
+    {
+        skip();
+    }
+
+    strcpy(tmpdir, "/tmp/ovpn-sandbox-XXXXXX");
+    assert_non_null(mkdtemp(tmpdir));
+
+    make_path(path, sizeof(path), "allowed.txt");
+    write_file(path, "allowed\n");
+    make_path(path, sizeof(path), "denied.txt");
+    write_file(path, "denied\n");
+    make_path(path, sizeof(path), "status.txt");
+    write_file(path, "status\n");
+    make_path(path, sizeof(path), "rw");
+    assert_int_equal(mkdir(path, 0700), 0);
+    make_path(path, sizeof(path), "real");
+    assert_int_equal(mkdir(path, 0700), 0);
+    make_path(path, sizeof(path), "real/resolv.conf");
+    write_file(path, "nameserver 192.0.2.1\n");
+    make_path(path2, sizeof(path2), "link.conf");
+    assert_int_equal(symlink(path, path2), 0);
+    make_path(path, sizeof(path), "conf");
+    assert_int_equal(mkdir(path, 0700), 0);
+    make_path(path, sizeof(path), "conf/server.conf");
+    write_file(path, "verb 3\n");
+
+    assert_int_equal(pipe(to_parent), 0);
+    assert_int_equal(pipe(from_parent), 0);
+
+    pid_t pid = fork();
+    assert_true(pid >= 0);
+    if (pid == 0)
+    {
+        close(to_parent[0]);
+        close(from_parent[1]);
+        landlock_child(to_parent[1], from_parent[0]);
+    }
+
+    /* close our copies of the child's ends, so that a read returns EOF
+     * instead of blocking if the child exits early */
+    close(to_parent[1]);
+    close(from_parent[0]);
+
+    /* replace real/resolv.conf with a new inode, like systemd-resolved */
+    int replaced = 0;
+    if (read(to_parent[0], &c, 1) == 1)
+    {
+        make_path(path, sizeof(path), "real/resolv.conf.new");
+        write_file(path, "nameserver 192.0.2.2\n");
+        make_path(path2, sizeof(path2), "real/resolv.conf");
+        replaced = rename(path, path2) == 0;
+
+        /* and the config file, like an editor or sed -i would */
+        make_path(path, sizeof(path), "conf/server.conf.new");
+        write_file(path, "verb 4\n");
+        make_path(path2, sizeof(path2), "conf/server.conf");
+        replaced = replaced && rename(path, path2) == 0;
+        assert_int_equal(write(from_parent[1], &c, 1), 1);
+    }
+
+    int status;
+    close(from_parent[1]);
+    assert_int_equal(waitpid(pid, &status, 0), pid);
+    close(to_parent[0]);
+
+    /* clean up */
+    const char *files[] = { "allowed.txt", "denied.txt", "status.txt", "link.conf",
+                            "real/resolv.conf", "rw/new.txt", "conf/server.conf" };
+    for (size_t i = 0; i < SIZE(files); ++i)
+    {
+        make_path(path, sizeof(path), files[i]);
+        unlink(path);
+    }
+    make_path(path, sizeof(path), "real");
+    rmdir(path);
+    make_path(path, sizeof(path), "conf");
+    rmdir(path);
+    make_path(path, sizeof(path), "rw");
+    rmdir(path);
+    rmdir(tmpdir);
+
+    assert_true(WIFEXITED(status));
+    if (WEXITSTATUS(status) == CHILD_SKIP)
+    {
+        /* kernel without Landlock support */
+        skip();
+    }
+    assert_int_equal(WEXITSTATUS(status), 0);
+    assert_true(replaced);
+}
+#endif /* if defined(TARGET_LINUX) && defined(HAVE_LINUX_LANDLOCK_H) */
+
+const struct CMUnitTest sandbox_tests[] = {
+    cmocka_unit_test(test_parse_type),
+    cmocka_unit_test(test_rules_add_grows),
+    cmocka_unit_test(test_build_rules_from_options),
+    cmocka_unit_test(test_build_rules_single_entry),
+#if defined(TARGET_LINUX) && defined(HAVE_LINUX_LANDLOCK_H)
+    cmocka_unit_test(test_landlock_enforced),
+#endif
+};
+
+int
+main(void)
+{
+    openvpn_unit_test_setup();
+    return cmocka_run_group_tests(sandbox_tests, NULL, NULL);
+}
-- 
2.53.0

_______________________________________________
Openvpn-devel mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/openvpn-devel

Reply via email to