luci-base: introduce luci.util.shellquote()

Introduce a new function luci.util.shellquote() which encloses the given
string argument in single quotes and escapes any embedded single quote
characters.

This function is intended to be used when interpolating untrusted input
into shell commands.

Signed-off-by: Jo-Philipp Wich <jo@mein.io>
This commit is contained in:
Jo-Philipp Wich 2018-04-05 09:29:38 +02:00
parent 9e4b8a9138
commit 45cefe71f6
2 changed files with 14 additions and 1 deletions

View file

@ -164,6 +164,10 @@ function striptags(value)
return value and tparser.striptags(tostring(value)) return value and tparser.striptags(tostring(value))
end end
function shellquote(value)
return string.format("'%s'", string.gsub(value or "", "'", "'\\''"))
end
-- for bash, ash and similar shells single-quoted strings are taken -- for bash, ash and similar shells single-quoted strings are taken
-- literally except for single quotes (which terminate the string) -- literally except for single quotes (which terminate the string)
-- (and the exception noted below for dash (-) at the start of a -- (and the exception noted below for dash (-) at the start of a
@ -656,7 +660,7 @@ function checklib(fullpathexe, wantedlib)
if not haveldd or not haveexe then if not haveldd or not haveexe then
return false return false
end end
local libs = exec("/usr/bin/ldd " .. fullpathexe) local libs = exec(string.format("/usr/bin/ldd %s", shellquote(fullpathexe)))
if not libs then if not libs then
return false return false
end end

View file

@ -82,6 +82,15 @@ Strip HTML tags from given string.
@return String with HTML tags stripped of @return String with HTML tags stripped of
]] ]]
---[[
Safely quote value for use in shell commands.
@class function
@name shellquote
@param value String containing the value to quote
@return Single-quote enclosed string with embedded quotes escaped
]]
---[[ ---[[
Splits given string on a defined separator sequence and return a table Splits given string on a defined separator sequence and return a table