Subject: Re: bug#45198: 28.0.50; Sandbox mode

From: Philipp <[email-masked]>
Date: Sat, 17 Apr 2021 21:42:31 +0200

> Am 17.04.2021 um 20:59 schrieb Mattias Engdegård <[email-masked]>:
> 
> 17 apr. 2021 kl. 20.21 skrev Stefan Monnier <[email-masked]>:
> 
>>> Very reasonable. Or would you prefer having the sandboxing in flymake?
>> 
>> AFAICT this question refers to a minor implementation detail ;-)
> 
> Of course, sorry.
> 
> Looks like I forgot to attach the updated patch in a previous message. Here it is.
> 
> <0001-Add-macOS-sandboxing-bug-45198.patch>

Looks generally fine, just a few minor comments.

> diff --git a/lisp/subr.el b/lisp/subr.el
> index c2be26a15f..196512c0c6 100644
> --- a/lisp/subr.el
> +++ b/lisp/subr.el

Should this maybe be in a platform-specific file such as ns-fns.el (like dos-fns.el, w32-fns.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)

I don't think we use the "darwin-" prefix anywhere else in Emacs.  Maybe use a "ns-" prefix.
Also I think such internal functions commonly have an "internal" piece somewhere in their name, e.g. "ns-enter-sandbox-internal".

> +    "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

Can you also refer to the documents listed below, so that readers aren't wondering what this syntax means?

> +     (concat "(version 1)\n"

Since this uses Lisp syntax, maybe use (prin1-to-string `(...))?

> +             "(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))

Are you sure that the string quoting syntaxes are compatible?  We really need to avoid injection attacks here.

> +                        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 */

Thanks, I'd expect at least the Chromium reference to stick around.

> +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,

Similar comments about naming here; maybe call this ns-init-sandbox-internal or so.

> +       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.

I'd also refer to the Chromium document here, otherwise C-h f for this function won't be very useful.

> +
> +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)

If you're using SSDATA, better check that the string doesn't contain embedded null bytes.
Also does this need to be encoded somehow?  What happens if the string contains non-Unicode characters like raw bytes?

> +    error ("sandbox error: %s", err);

This looks like an error that clients could handle, so I'd signal a specific error symbol here.

> +  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

This should probably be in subr-tests.el since it tests a function in subr.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))))))

This is more of a personal style, feel free to ignore:
I like tests that are somewhat repetitive but more decoupled and easier to read better than tests with factored-out assertions.  See e.g. the arguments in https://www.maaikebrinkhof.nl/2016/03/repetition-in-testing/ and https://stackoverflow.com/a/130038.

> +
> +(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))))))))

These should be four separate tests, as they test four separate things.