From 78906da41140dc33119b419a410c4a4f0a3aee80 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Mattias=20Engdeg=C3=A5rd?= <mattiase@acm.org>
Date: Sat, 17 Apr 2021 20:53:39 +0200
Subject: [PATCH] Add macOS sandboxing (bug#45198)

This is the corresponding low-level sandboxing facility corresponding
to the recently added Seccomp for Linux.  `darwin-sandbox-init` gives
direct access to the system sandboxing call; `darwin-sandbox-enter` is
a wrapper that takes a list of directories under which files can be
read.  These should be considered internal mechanisms for now.

* lisp/subr.el (darwin-sandbox-enter):
* src/sysdep.c (Fdarwin_sandbox_init): New functions.
* test/src/emacs-tests.el (emacs-tests/darwin-sandbox): New test.
---
 lisp/subr.el            | 18 +++++++++++
 src/sysdep.c            | 32 +++++++++++++++++++
 test/src/emacs-tests.el | 70 +++++++++++++++++++++++++++++++++++++++++
 3 files changed, 120 insertions(+)

diff --git a/lisp/subr.el b/lisp/subr.el
index c2be26a15f..196512c0c6 100644
--- a/lisp/subr.el
+++ b/lisp/subr.el
@@ -6262,4 +6262,22 @@ internal--format-docstring-line
 This is intended for internal use only."
   (internal--fill-string-single-line (apply #'format string objects)))
 
+(when (eq system-type 'darwin)
+  (defun darwin-sandbox-enter (dirs)
+    "Enter a sandbox only permitting reading files under DIRS.
+DIRS is a list of directory names.  Most other operations such as
+writing files and network access are disallowed.
+Existing open descriptors can still be used freely.
+
+This is not a supported interface and is for internal use only."
+    (darwin-sandbox-init
+     (concat "(version 1)\n"
+             "(deny default)\n"
+             ;; Emacs seems to need /dev/null; allowing it does no harm.
+             "(allow file-read* (path \"/dev/null\"))\n"
+             (mapconcat (lambda (dir)
+                          (format "(allow file-read* (subpath %S))\n" dir))
+                        dirs ""))))
+  )
+
 ;;; subr.el ends here
diff --git a/src/sysdep.c b/src/sysdep.c
index d940acc4e0..44e8b82bc6 100644
--- a/src/sysdep.c
+++ b/src/sysdep.c
@@ -4286,8 +4286,40 @@ str_collate (Lisp_Object s1, Lisp_Object s2,
 }
 #endif	/* WINDOWSNT */
 
+#ifdef DARWIN_OS
+
+/* This function prototype is not in the platform header files.
+   See https://reverse.put.as/wp-content/uploads/2011/09/Apple-Sandbox-Guide-v1.0.pdf
+   and https://chromium.googlesource.com/chromium/src/+/master/sandbox/mac/seatbelt_sandbox_design.md */
+int sandbox_init_with_parameters(const char *profile,
+                                 uint64_t flags,
+                                 const char *const parameters[],
+                                 char **errorbuf);
+
+DEFUN ("darwin-sandbox-init", Fdarwin_sandbox_init, Sdarwin_sandbox_init,
+       1, 1, 0,
+       doc: /* Enter a sandbox whose permitted access is curtailed by PROFILE.
+Already open descriptors can be used freely.
+PROFILE is a string in the macOS sandbox profile language,
+a set of rules in a Lisp-like syntax.
+
+This is not a supported interface and is for internal use only. */)
+  (Lisp_Object profile)
+{
+  CHECK_STRING (profile);
+  char *err = NULL;
+  if (sandbox_init_with_parameters (SSDATA (profile), 0, NULL, &err) != 0)
+    error ("sandbox error: %s", err);
+  return Qnil;
+}
+
+#endif	/* DARWIN_OS */
+
 void
 syms_of_sysdep (void)
 {
   defsubr (&Sget_internal_run_time);
+#ifdef DARWIN_OS
+  defsubr (&Sdarwin_sandbox_init);
+#endif
 }
diff --git a/test/src/emacs-tests.el b/test/src/emacs-tests.el
index 09f9a248ef..c1a741c359 100644
--- a/test/src/emacs-tests.el
+++ b/test/src/emacs-tests.el
@@ -210,4 +210,74 @@ emacs-tests/bwrap/allows-stdout
           (should (eql status 0)))
         (should (equal (string-trim (buffer-string)) "Hi"))))))
 
+(defun emacs-tests--darwin-run-sandboxed-emacs (sandbox-dirs body)
+  "Run Emacs and evaluate BODY, only allowing reads from SANDBOX-DIRS.
+If SANDBOX-DIRS is `no-sandbox', then run without sandbox.
+Return (EXIT-STATUS . OUTPUT), where OUTPUT is stderr and stdout."
+  (let ((emacs (expand-file-name invocation-name invocation-directory))
+        (process-environment nil))
+    (with-temp-buffer
+      (let* ((prog `(progn
+                      ,@(and (not (eq sandbox-dirs 'no-sandbox))
+                             `((darwin-sandbox-enter ',sandbox-dirs)))
+                      ,@body))
+             (res (call-process emacs nil t nil
+                                "--quick" "--batch"
+                                (format "--eval=%S" prog))))
+        (cons res (buffer-string))))))
+
+(ert-deftest emacs-tests/darwin-sandbox ()
+  (skip-unless (eq system-type 'darwin))
+  (emacs-tests--with-temp-file test-file ("test")
+    (let ((some-text "abcdef")
+          (other-text "ghijkl")
+          (test-file (file-truename test-file)))   ; resolve symlinks
+      (with-temp-buffer
+        (insert some-text)
+        (write-file test-file))
+
+      ;; Read the file without allowing its directory -- should fail.
+      (let ((res-out (emacs-tests--darwin-run-sandboxed-emacs
+                      nil
+                      `((find-file-literally ,test-file)
+                        (message "OK: %s" (buffer-string))))))
+        (ert-info ((cdr res-out) :prefix "output: ")
+          (should-not (equal (car res-out) 0))
+          (should-not (string-search some-text (cdr res-out)))))
+
+      ;; Read the file allowing its directory -- should succeed.
+      (let ((res-out (emacs-tests--darwin-run-sandboxed-emacs
+                      (list (file-name-directory test-file))
+                      `((find-file-literally ,test-file)
+                        (message "OK: %s" (buffer-string))))))
+        (should (equal res-out (cons 0 (format "OK: %s\n" some-text)))))
+
+      ;; Write to the file allowing directory reads -- should fail.
+      (let ((res-out (emacs-tests--darwin-run-sandboxed-emacs
+                      (list (file-name-directory test-file))
+                      `((with-temp-buffer
+                          (insert ,other-text)
+                          (write-file ,test-file))))))
+        (ert-info ((cdr res-out) :prefix "output: ")
+          (should-not (equal (car res-out) 0))
+          ;; The file should be unchanged.
+          (let ((contents (with-temp-buffer
+                            (insert-file-contents-literally test-file)
+                            (buffer-string))))
+            (should (equal contents some-text)))))
+
+      ;; Write to the file without sandbox -- should succeed.
+      (let ((res-out (emacs-tests--darwin-run-sandboxed-emacs
+                      'no-sandbox
+                      `((with-temp-buffer
+                          (insert ,other-text)
+                          (write-file ,test-file))))))
+        (ert-info ((cdr res-out) :prefix "output: ")
+          (should (equal (car res-out) 0))
+          ;; The file should be changed.
+          (let ((contents (with-temp-buffer
+                            (insert-file-contents-literally test-file)
+                            (buffer-string))))
+            (should (equal contents other-text))))))))
+
 ;;; emacs-tests.el ends here
-- 
2.21.1 (Apple Git-122.3)

