From 9e0128b205f568795d8c4688a7a94c175b1b2007 Mon Sep 17 00:00:00 2001 Message-ID: <9e0128b205f568795d8c4688a7a94c175b1b2007.1693295856.git.yantar92@posteo.net> From: Ihor Radchenko Date: Mon, 21 Aug 2023 09:57:50 +0300 Subject: [PATCH] org-macs: New common API function to quote shell arguments * lisp/org-macs.el (org-shell-arg-tag-unescaped): New auxiliary constant. (org-make-shell-command): New function that returns shell command built from individual shell arguments, escaping them to prevent malicious code execution. Link: https://orgmode.org/list/ub549k$q11$1@ciao.gmane.io --- lisp/org-macs.el | 51 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/lisp/org-macs.el b/lisp/org-macs.el index 907e8bed7..6bcd393ce 100644 --- a/lisp/org-macs.el +++ b/lisp/org-macs.el @@ -1593,6 +1593,57 @@ (defun org-sxhash-safe (obj &optional counter) (puthash hash obj org-sxhash-objects) (puthash obj hash org-sxhash-hashes))))) +;; We use `gensym' to avoid malicious code know in advance the symbol +;; used to prevent escaping. +(defconst org-shell-arg-tag-unescaped (gensym "literal") + "Symbol to be used to mark shell arguments that should not be escaped. +See `org-make-shell-command'.") +;; We are deliberately using `defsubst' below, to make it harder to +;; advice this function. +(defsubst org-shell-arg-unescaped (string-arg) + "Mark STRING-ARG argument to be unescaped in `org-make-shell-command'." + (list org-shell-arg-tag-unescaped string-arg)) +(defsubst org-make-shell-command (command &rest args) + "Build safe shell command string to run COMMAND with ARGS. + +The resulting shell command is safe against malicious shell expansion. + +This function is used to avoid unexpected shell expansion when +building shell command using header arguments from Org babel blocks. + +ARGS can be nil, strings, the return value of (org-shell-arg-unescaped +STRING), or a list of such elements. For example, + + (let ((files \\='(\"a.txt\" \"b.txt\" nil \"$HOME.txt\"))) + (org-make-shell-command \"command\" \"-l\" + \"value with spaces\" + (org-shell-arg-unescaped \"$HOME\") + files ; list variable + )) + +will shell-escape \"-l\", \"value with spaces\", and each non-nil member of +FILES list, but leave \"$HOME\" to be shell-expanded. + +COMMAND itself can contain shell expansion constructs - no escaping +will be performed." + (concat + command (when command " ") + (mapconcat + #'identity + (delq + nil + (mapcar + (lambda (str-def) + (pcase str-def + (`nil nil) + ((pred stringp) (shell-quote-argument str-def)) + (`(,(pred (eq org-shell-arg-tag-unescaped)) ,(and (pred stringp) str)) + str) + ((pred listp) (apply #'org-make-shell-command nil str-def)) + (_ (error "Unknown ARG specification: %S" str-def)))) + args)) + " "))) + (defun org-compile-file (source process ext &optional err-msg log-buf spec) "Compile a SOURCE file using PROCESS. -- 2.42.0