Skip to contentSkip to conversation

sandbox/sandbox: do not follow symlinks when shredding sandbox directories

PATCH In review Stephen Smalley 2 participants 7 messages Nov 19 SELinux security module

lore
Share & tools
lore

Stephen Smalley

author maintainer
#0 lore raw

PATCH 1/3 sandbox/sandbox: do not follow symlinks when shredding sandbox directories

sandbox --shred walks the sandbox home/tmp/runuser directories after the sandboxed process has exited and passes each file to /usr/bin/shred. os.walk() reports symbolic links to files in its "files" list, and shred opens its operand following symlinks and overwrites the target file in place.

The walk runs in the invoking user's domain, not in the sandbox domain, so a symlink planted by the sandboxed process lets it destroy files it could not otherwise reach. Further, a child of the sandboxed process can survive and race with the walk to swap a file with a symlink to a file it could not otherwise reach.

Fix by replacing the use of /usr/bin/shred with an inline fd-based walk using os.fwalk(follow_symlinks=False) that pins each directory by fd and rejects a directory that was replaced by a symlink after lstat and open; open each leaf O_WRONLY|O_NOFOLLOW|O_NONBLOCK so that we do not follow symlinks and cannot be blocked by a planted fifo; refuse to act on anything that is not a regular file after open; then zero and fsync.

Fixing seunshare to ensure that no sandbox descendant survives is left to a future change but is not necessary to close this issue.

---
 sandbox/sandbox | 22 +++++++++++++++++++---
 1 file changed, 19 insertions(+), 3 deletions(-)
sandbox/sandbox +19 -3
index 6a18b660..cfcc0b61 100644
@@ -540,10 +540,26 @@ sandbox [-h] [-l level ] [-[X|M] [-H homedir] [-T tempdir]] [-I includefile ] [-
                 shutil.rmtree(self.__runuserdir)
 
     def shred(self, path):
-        for root, dirs, files in os.walk(path):
+        for root, dirs, files, dirfd in os.fwalk(path, follow_symlinks=False):
             for f in files:
-                dest = root + "/" + f
-                subprocess.Popen(["/usr/bin/shred", dest]).wait()
+                try:
+                    fd = os.open(f, os.O_WRONLY | os.O_NOFOLLOW | os.O_NONBLOCK,
+                                 dir_fd=dirfd)
+                except OSError:
+                    continue
+                try:
+                    st = os.fstat(fd)
+                    if not stat.S_ISREG(st.st_mode):
+                        continue
+                    remaining = st.st_size
+                    while remaining > 0:
+                        chunk = b"\x00" * min(remaining, 1 << 20)
+                        remaining -= os.write(fd, chunk)
+                    os.fsync(fd)
+                except OSError:
+                    pass
+                finally:
+                    os.close(fd)
 
     def main(self):
         try:
Signature · 1 line
2.47.3
author maintainer
#1 lore raw

PATCH 2/3 sandbox/seunshare: SIGKILL and drain the child process group

After the sandboxed process exits, seunshare sends SIGTERM to its process group and returns; sandbox(1) then walks the sandbox directories. A descendant that ignores SIGTERM, or that is stll draining, is still alive during that walk.

Send SIGKILL instead and loop until kill(-child, SIGKILL) reports ESRCH, re-sending each pass so a process that fork()s between our signal and its own exit is caught the next time. Bound the loop at 2s:
a grandchild stuck in uninterruptible sleep, or a zombie not yet reaped by init, holds the pgid alive, and with the fd-based shred in the previous commit, sandbox is safe against a survivor anyway.

The SIGINT/SIGHUP forwarder in handler() is left forwarding the received signal so ^C still reaches the sandboxed application; the post-wait SIGKILL sweep runs afterwards.

This does not cover a descendant that left the process group via setsid()/setpgid() before the sweep. Placing the child in its own PID namespace would make waitpid() returning imply no descendant exists; that is left to a future change.

---
 sandbox/seunshare.c | 22 ++++++++++++++++++++--
 1 file changed, 20 insertions(+), 2 deletions(-)
sandbox/seunshare.c +20 -2
index 9f7e49da..b39ca010 100644
@@ -7,6 +7,7 @@
 #include <stdbool.h>
 #include <signal.h>
 #include <sys/fsuid.h>
+#include <time.h>
 #include <sys/stat.h>
 #include <sys/types.h>
 #include <sys/wait.h>
@@ -1274,8 +1275,25 @@ childerr:
 	waitpid(child, &status, 0);
 	status_to_retval(status, status);
 
-	/* Make sure all child processes exit */
-	kill(-child, SIGTERM);
+	/*
+	 * Make sure the child process group is gone before cleanup runs.
+	 * SIGKILL each iteration so a descendant that fork()s between our
+	 * signal and its own exit is caught on the next pass. Zombies keep
+	 * the pgid alive until init reaps them, so give this a bounded
+	 * budget; with the fd-based shred in sandbox(1), timing out here
+	 * only leaves a straggler alongside a race-free cleanup.
+	 *
+	 * This does not cover a descendant that left the process group via
+	 * setsid()/setpgid(); a PID namespace is the complete answer.
+	 */
+	for (int i = 0; i < 400; i++) {
+		struct timespec ts = { .tv_sec = 0,
+				       .tv_nsec = 5 * 1000 * 1000 };
+
+		if (kill(-child, SIGKILL) < 0 && errno == ESRCH)
+			break;
+		nanosleep(&ts, NULL);
+	}
 
 	if (execcon && kill_all)
 		fprintf(stderr,
Signature · 1 line
2.47.3
Acked-by on v1 2/3
#2 lore raw

Re: [PATCH 2/3] sandbox/seunshare: SIGKILL and drain the child process group

Quoted 16 lines · Stephen Smalley

After the sandboxed process exits, seunshare sends SIGTERM to its process group and returns; sandbox(1) then walks the sandbox directories. A descendant that ignores SIGTERM, or that is stll draining, is still alive during that walk.

Send SIGKILL instead and loop until kill(-child, SIGKILL) reports ESRCH, re-sending each pass so a process that fork()s between our signal and its own exit is caught the next time. Bound the loop at 2s:
a grandchild stuck in uninterruptible sleep, or a zombie not yet reaped by init, holds the pgid alive, and with the fd-based shred in the previous commit, sandbox is safe against a survivor anyway.

The SIGINT/SIGHUP forwarder in handler() is left forwarding the received signal so ^C still reaches the sandboxed application; the post-wait SIGKILL sweep runs afterwards.

Quoted 6 lines

This does not cover a descendant that left the process group via setsid()/setpgid() before the sweep. Placing the child in its own PID namespace would make waitpid() returning imply no descendant exists; that is left to a future change.

Quoted 46 lines
---
 sandbox/seunshare.c | 22 ++++++++++++++++++++--
 1 file changed, 20 insertions(+), 2 deletions(-)
sandbox/seunshare.c +20 -2
index 9f7e49da..b39ca010 100644
@@ -7,6 +7,7 @@
 #include <stdbool.h>
 #include <signal.h>
 #include <sys/fsuid.h>
+#include <time.h>
 #include <sys/stat.h>
 #include <sys/types.h>
 #include <sys/wait.h>
@@ -1274,8 +1275,25 @@ childerr:
 	waitpid(child, &status, 0);
 	status_to_retval(status, status);
 
-	/* Make sure all child processes exit */
-	kill(-child, SIGTERM);
+	/*
+	 * Make sure the child process group is gone before cleanup runs.
+	 * SIGKILL each iteration so a descendant that fork()s between our
+	 * signal and its own exit is caught on the next pass. Zombies keep
+	 * the pgid alive until init reaps them, so give this a bounded
+	 * budget; with the fd-based shred in sandbox(1), timing out here
+	 * only leaves a straggler alongside a race-free cleanup.
+	 *
+	 * This does not cover a descendant that left the process group via
+	 * setsid()/setpgid(); a PID namespace is the complete answer.
+	 */
+	for (int i = 0; i < 400; i++) {
+		struct timespec ts = { .tv_sec = 0,
+				       .tv_nsec = 5 * 1000 * 1000 };
+
+		if (kill(-child, SIGKILL) < 0 && errno == ESRCH)
+			break;
+		nanosleep(&ts, NULL);
+	}
 
 	if (execcon && kill_all)
 		fprintf(stderr,
Signature · 1 line
2.47.3
author maintainer
#3 lore raw

PATCH 3/3 sandbox/seunshare: run the sandbox in its own PID namespace

In reply to Stephen Smalley

The SIGKILL sweep after waitpid() only reaches the child process group; a sandbox descendant that has called setsid() or setpgid() escapes it and can still be running while sandbox(1) walks the sandbox directories. The fd-based shred in sandbox is safe against that, but leaving the escapee alive at all is avoidable.

Give the sandbox its own PID namespace so the sandboxed command is its
init: when it exits the kernel SIGKILLs every remaining descendant and waits for the namespace to drain before the exit completes, so by the time the outer waitpid() returns nothing from the sandbox is running.

unshare(CLONE_NEWPID) affects children only, so this needs an intermediate process between the parent and the sandbox init. That process takes the new session so the parent's kill(-child, ...) still addresses the sandbox process group, ignores forwarded signals so it outlives the sandbox, and relays its exit status. The setsid() before execv() is dropped so the sandbox stays in that group.

/proc is left as-is; the sandbox process still has a PID in the outer namespace so /proc/self and the /proc/self/fd/N mount helpers keep working.

---
 sandbox/seunshare.c | 58 ++++++++++++++++++++++++++++++++++++++++++---
 1 file changed, 55 insertions(+), 3 deletions(-)
sandbox/seunshare.c +55 -3
index b39ca010..528eefd4 100644
@@ -1009,6 +1009,57 @@ int main(int argc, char **argv)
 		int fd_runuserdir_s = -1, fd_runtime_dir = -1;
 		int fd_tmpdir_r = -1, fd_tmp = -1, fd_var_tmp = -1;
 		struct stat sb;
+		pid_t sandbox;
+
+		/*
+		 * Put the sandbox in its own PID namespace so that when its
+		 * init (the sandboxed command) exits, the kernel SIGKILLs
+		 * every remaining descendant regardless of process group,
+		 * and does so before the parent's waitpid() can return.
+		 * This closes the setsid()/setpgid() escape the post-wait
+		 * SIGKILL sweep cannot cover.
+		 *
+		 * unshare(CLONE_NEWPID) affects subsequent children only,
+		 * so fork once more; this intermediate process is what the
+		 * parent waits on and just relays the sandbox exit status.
+		 * Take a new session first so the parent's kill(-child, ...)
+		 * addresses this process group, which the sandbox and its
+		 * well-behaved descendants stay in.
+		 */
+		if (setsid() == (pid_t)-1) {
+			perror(_("setsid"));
+			exit(-1);
+		}
+		if (unshare(CLONE_NEWPID) < 0) {
+			perror(_("Failed to create PID namespace"));
+			exit(-1);
+		}
+		sandbox = fork();
+		if (sandbox == -1) {
+			perror(_("Unable to fork"));
+			exit(-1);
+		}
+		if (sandbox > 0) {
+			int st;
+
+			/*
+			 * Ignore forwarded signals so this process outlives
+			 * the sandbox and the PID namespace guarantee holds;
+			 * the process-group signal reaches the sandbox
+			 * directly.
+			 */
+			signal(SIGINT, SIG_IGN);
+			signal(SIGHUP, SIG_IGN);
+			signal(SIGTERM, SIG_IGN);
+			signal(SIGQUIT, SIG_IGN);
+
+			if (waitpid(sandbox, &st, 0) < 0)
+				exit(-1);
+			status_to_retval(st, st);
+			exit(st);
+		}
+
+		/* PID 1 in the new namespace from here on. */
 
 		if (unshare(CLONE_NEWNS) < 0) {
 			perror(_("Failed to unshare"));
@@ -1225,7 +1276,6 @@ int main(int argc, char **argv)
 			perror(_("Failed to change dir to homedir"));
 			goto childerr;
 		}
-		setsid();
 
 		/* selinux context */
 		if (execcon) {
@@ -1283,8 +1333,10 @@ childerr:
 	 * budget; with the fd-based shred in sandbox(1), timing out here
 	 * only leaves a straggler alongside a race-free cleanup.
 	 *
-	 * This does not cover a descendant that left the process group via
-	 * setsid()/setpgid(); a PID namespace is the complete answer.
+	 * With the PID namespace above, waitpid() returning implies the
+	 * namespace has been torn down and no sandbox descendant is
+	 * running, so this sweep breaks on the first iteration; kept as
+	 * a cheap safety belt.
 	 */
 	for (int i = 0; i < 400; i++) {
 		struct timespec ts = { .tv_sec = 0,
Signature · 1 line
2.47.3
Acked-by on v1 3/3
#4 lore raw

Re: [PATCH 3/3] sandbox/seunshare: run the sandbox in its own PID namespace

Quoted 18 lines · Stephen Smalley

The SIGKILL sweep after waitpid() only reaches the child process group; a sandbox descendant that has called setsid() or setpgid() escapes it and can still be running while sandbox(1) walks the sandbox directories. The fd-based shred in sandbox is safe against that, but leaving the escapee alive at all is avoidable.

Give the sandbox its own PID namespace so the sandboxed command is its
init: when it exits the kernel SIGKILLs every remaining descendant and waits for the namespace to drain before the exit completes, so by the time the outer waitpid() returns nothing from the sandbox is running.

unshare(CLONE_NEWPID) affects children only, so this needs an intermediate process between the parent and the sandbox init. That process takes the new session so the parent's kill(-child, ...) still addresses the sandbox process group, ignores forwarded signals so it outlives the sandbox, and relays its exit status. The setsid() before execv() is dropped so the sandbox stays in that group.

Quoted 5 lines

/proc is left as-is; the sandbox process still has a PID in the outer namespace so /proc/self and the /proc/self/fd/N mount helpers keep working.

Quoted 89 lines
---
 sandbox/seunshare.c | 58 ++++++++++++++++++++++++++++++++++++++++++---
 1 file changed, 55 insertions(+), 3 deletions(-)
sandbox/seunshare.c +55 -3
index b39ca010..528eefd4 100644
@@ -1009,6 +1009,57 @@ int main(int argc, char **argv)
 		int fd_runuserdir_s = -1, fd_runtime_dir = -1;
 		int fd_tmpdir_r = -1, fd_tmp = -1, fd_var_tmp = -1;
 		struct stat sb;
+		pid_t sandbox;
+
+		/*
+		 * Put the sandbox in its own PID namespace so that when its
+		 * init (the sandboxed command) exits, the kernel SIGKILLs
+		 * every remaining descendant regardless of process group,
+		 * and does so before the parent's waitpid() can return.
+		 * This closes the setsid()/setpgid() escape the post-wait
+		 * SIGKILL sweep cannot cover.
+		 *
+		 * unshare(CLONE_NEWPID) affects subsequent children only,
+		 * so fork once more; this intermediate process is what the
+		 * parent waits on and just relays the sandbox exit status.
+		 * Take a new session first so the parent's kill(-child, ...)
+		 * addresses this process group, which the sandbox and its
+		 * well-behaved descendants stay in.
+		 */
+		if (setsid() == (pid_t)-1) {
+			perror(_("setsid"));
+			exit(-1);
+		}
+		if (unshare(CLONE_NEWPID) < 0) {
+			perror(_("Failed to create PID namespace"));
+			exit(-1);
+		}
+		sandbox = fork();
+		if (sandbox == -1) {
+			perror(_("Unable to fork"));
+			exit(-1);
+		}
+		if (sandbox > 0) {
+			int st;
+
+			/*
+			 * Ignore forwarded signals so this process outlives
+			 * the sandbox and the PID namespace guarantee holds;
+			 * the process-group signal reaches the sandbox
+			 * directly.
+			 */
+			signal(SIGINT, SIG_IGN);
+			signal(SIGHUP, SIG_IGN);
+			signal(SIGTERM, SIG_IGN);
+			signal(SIGQUIT, SIG_IGN);
+
+			if (waitpid(sandbox, &st, 0) < 0)
+				exit(-1);
+			status_to_retval(st, st);
+			exit(st);
+		}
+
+		/* PID 1 in the new namespace from here on. */
 
 		if (unshare(CLONE_NEWNS) < 0) {
 			perror(_("Failed to unshare"));
@@ -1225,7 +1276,6 @@ int main(int argc, char **argv)
 			perror(_("Failed to change dir to homedir"));
 			goto childerr;
 		}
-		setsid();
 
 		/* selinux context */
 		if (execcon) {
@@ -1283,8 +1333,10 @@ childerr:
 	 * budget; with the fd-based shred in sandbox(1), timing out here
 	 * only leaves a straggler alongside a race-free cleanup.
 	 *
-	 * This does not cover a descendant that left the process group via
-	 * setsid()/setpgid(); a PID namespace is the complete answer.
+	 * With the PID namespace above, waitpid() returning implies the
+	 * namespace has been torn down and no sandbox descendant is
+	 * running, so this sweep breaks on the first iteration; kept as
+	 * a cheap safety belt.
 	 */
 	for (int i = 0; i < 400; i++) {
 		struct timespec ts = { .tv_sec = 0,
Signature · 1 line
2.47.3
Acked-by on v1 1/3
#5 lore raw
In reply to Stephen Smalley
Quoted 20 lines · Stephen Smalley

sandbox --shred walks the sandbox home/tmp/runuser directories after the sandboxed process has exited and passes each file to /usr/bin/shred. os.walk() reports symbolic links to files in its "files" list, and shred opens its operand following symlinks and overwrites the target file in place.

The walk runs in the invoking user's domain, not in the sandbox domain, so a symlink planted by the sandboxed process lets it destroy files it could not otherwise reach. Further, a child of the sandboxed process can survive and race with the walk to swap a file with a symlink to a file it could not otherwise reach.

Fix by replacing the use of /usr/bin/shred with an inline fd-based walk using os.fwalk(follow_symlinks=False) that pins each directory by fd and rejects a directory that was replaced by a symlink after lstat and open; open each leaf O_WRONLY|O_NOFOLLOW|O_NONBLOCK so that we do not follow symlinks and cannot be blocked by a planted fifo; refuse to act on anything that is not a regular file after open; then zero and fsync.

Quoted 4 lines

Fixing seunshare to ensure that no sandbox descendant survives is left to a future change but is not necessary to close this issue.

Quoted 40 lines
---
 sandbox/sandbox | 22 +++++++++++++++++++---
 1 file changed, 19 insertions(+), 3 deletions(-)
sandbox/sandbox +19 -3
index 6a18b660..cfcc0b61 100644
@@ -540,10 +540,26 @@ sandbox [-h] [-l level ] [-[X|M] [-H homedir] [-T tempdir]] [-I includefile ] [-
                 shutil.rmtree(self.__runuserdir)
 
     def shred(self, path):
-        for root, dirs, files in os.walk(path):
+        for root, dirs, files, dirfd in os.fwalk(path, follow_symlinks=False):
             for f in files:
-                dest = root + "/" + f
-                subprocess.Popen(["/usr/bin/shred", dest]).wait()
+                try:
+                    fd = os.open(f, os.O_WRONLY | os.O_NOFOLLOW | os.O_NONBLOCK,
+                                 dir_fd=dirfd)
+                except OSError:
+                    continue
+                try:
+                    st = os.fstat(fd)
+                    if not stat.S_ISREG(st.st_mode):
+                        continue
+                    remaining = st.st_size
+                    while remaining > 0:
+                        chunk = b"\x00" * min(remaining, 1 << 20)
+                        remaining -= os.write(fd, chunk)
+                    os.fsync(fd)
+                except OSError:
+                    pass
+                finally:
+                    os.close(fd)
 
     def main(self):
         try:
Signature · 1 line
2.47.3
#6 lore raw
Quoted 22 lines · Petr Lautrbach
Quoted 20 lines · Stephen Smalley

sandbox --shred walks the sandbox home/tmp/runuser directories after the sandboxed process has exited and passes each file to /usr/bin/shred. os.walk() reports symbolic links to files in its "files" list, and shred opens its operand following symlinks and overwrites the target file in place.

The walk runs in the invoking user's domain, not in the sandbox domain, so a symlink planted by the sandboxed process lets it destroy files it could not otherwise reach. Further, a child of the sandboxed process can survive and race with the walk to swap a file with a symlink to a file it could not otherwise reach.

Fix by replacing the use of /usr/bin/shred with an inline fd-based walk using os.fwalk(follow_symlinks=False) that pins each directory by fd and rejects a directory that was replaced by a symlink after lstat and open; open each leaf O_WRONLY|O_NOFOLLOW|O_NONBLOCK so that we do not follow symlinks and cannot be blocked by a planted fifo; refuse to act on anything that is not a regular file after open; then zero and fsync.

Quoted 6 lines
Quoted 4 lines

Fixing seunshare to ensure that no sandbox descendant survives is left to a future change but is not necessary to close this issue.

This series has been merged.

Quoted 40 lines
Quoted 40 lines
---
 sandbox/sandbox | 22 +++++++++++++++++++---
 1 file changed, 19 insertions(+), 3 deletions(-)
sandbox/sandbox +19 -3
index 6a18b660..cfcc0b61 100644
@@ -540,10 +540,26 @@ sandbox [-h] [-l level ] [-[X|M] [-H homedir] [-T tempdir]] [-I includefile ] [-
                 shutil.rmtree(self.__runuserdir)
 
     def shred(self, path):
-        for root, dirs, files in os.walk(path):
+        for root, dirs, files, dirfd in os.fwalk(path, follow_symlinks=False):
             for f in files:
-                dest = root + "/" + f
-                subprocess.Popen(["/usr/bin/shred", dest]).wait()
+                try:
+                    fd = os.open(f, os.O_WRONLY | os.O_NOFOLLOW | os.O_NONBLOCK,
+                                 dir_fd=dirfd)
+                except OSError:
+                    continue
+                try:
+                    st = os.fstat(fd)
+                    if not stat.S_ISREG(st.st_mode):
+                        continue
+                    remaining = st.st_size
+                    while remaining > 0:
+                        chunk = b"\x00" * min(remaining, 1 << 20)
+                        remaining -= os.write(fd, chunk)
+                    os.fsync(fd)
+                except OSError:
+                    pass
+                finally:
+                    os.close(fd)
 
     def main(self):
         try:
Signature · 1 line
2.47.3