-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathCommandInjection.qhelp
More file actions
64 lines (61 loc) · 2.09 KB
/
CommandInjection.qhelp
File metadata and controls
64 lines (61 loc) · 2.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
<!DOCTYPE qhelp PUBLIC
"-//Semmle//qhelp//EN"
"qhelp.dtd">
<qhelp>
<overview>
<p>
If a system command invocation is built from user-provided data without sufficient sanitization,
a malicious user may be able to run commands to exfiltrate data or compromise the system.
</p>
</overview>
<recommendation>
<p>
Whenever possible, use hard-coded string literals for commands and avoid shell
string interpreters like <code>sh -c</code>.
</p>
<p>
If given arguments as a single string, avoid simply splitting the string on
whitespace. Arguments may contain quoted whitespace, causing them to split into
multiple arguments.
</p>
<p>
If this is not possible, sanitize user input to avoid characters like spaces and
various kinds of quotes that can alter the meaning of the command.
</p>
</recommendation>
<example>
<p>
In the following example, assume the function <code>handler</code> is an HTTP request
handler in a web application, whose parameter <code>req</code> contains the request object:
</p>
<sample src="examples/CommandInjection.go"/>
<p>
The handler extracts the image file name from the request and uses the image name to construct a
shell command that is executed using <code>`sh -c`</code>, which can lead to command injection.
</p>
<p>
It's better to avoid shell commands by using the <code>exec.Command</code> function directly,
as shown in the following example:
</p>
<sample src="examples/CommandInjectionGood.go"/>
<p>
Alternatively, a regular expression can be used to ensure that the image name is safe to use
in a shell command:
</p>
<sample src="examples/CommandInjectionGood2.go"/>
<p>
Some commands, like <code>git</code>, can indirectly execute commands if an attacker specifies
the flags given to the command.
</p>
<p>
To mitigate this risk, either add a <code>--</code> argument to ensure subsequent arguments are
not interpreted as flags, or verify that the argument does not start with <code>"--"</code>.
</p>
<sample src="examples/CommandInjectionGood3.go"/>
</example>
<references>
<li>
OWASP: <a href="https://www.owasp.org/index.php/Command_Injection">Command Injection</a>.
</li>
</references>
</qhelp>