@@ -12,18 +12,17 @@ a malicious user may be able to run commands to exfiltrate data or compromise th
12
12
13
13
<recommendation >
14
14
<p >
15
- If possible, use hard-coded string literals to specify the command to run, and avoid using
16
- shell string interpreters such as <code >sh -c</code > to execute shell commands.
15
+ Whenever possible, use hard-coded string literals for commands and avoid shell
16
+ string interpreters like <code >sh -c</code >.
17
17
</p >
18
18
<p >
19
19
If given arguments as a single string, avoid simply splitting the string on
20
20
whitespace. Arguments may contain quoted whitespace, causing them to split into
21
21
multiple arguments.
22
22
</p >
23
23
<p >
24
- If this is not possible, then add sanitization code to verify that the user input is
25
- safe before using it, thereby avoiding characters that can change the meaning of the
26
- command such as spaces and quotes.
24
+ If this is not possible, sanitize user input to avoid characters like spaces and
25
+ various kinds of quotes that can alter the meaning of the command.
27
26
</p >
28
27
</recommendation >
29
28
@@ -34,12 +33,11 @@ handler in a web application, whose parameter <code>req</code> contains the requ
34
33
</p >
35
34
<sample src =" examples/CommandInjection.go" />
36
35
<p >
37
- The handler extracts the name of an image file from the request object, and then runs a command
38
- to process the image. The command is constructed by concatenating the image path and the output path,
39
- and then running it with <code >sh -c</code >. This can cause a command-injection vulnerability.
36
+ The handler extracts the image file name from the request and uses the image name to construct a
37
+ shell command that is executed using <code >`sh -c`</code >, which can lead to command injection.
40
38
</p >
41
39
<p >
42
- It's better to avoid shell strings by using the <code >exec.Command</code > function directly,
40
+ It's better to avoid shell commands by using the <code >exec.Command</code > function directly,
43
41
as shown in the following example:
44
42
</p >
45
43
<sample src =" examples/CommandInjectionGood.go" />
@@ -48,6 +46,15 @@ Alternatively, a regular expression can be used to ensure that the image name is
48
46
in a shell command:
49
47
</p >
50
48
<sample src =" examples/CommandInjectionGood2.go" />
49
+ <p >
50
+ Some commands, like <code >git</code >, can indirectly execute commands if an attacker specifies
51
+ the flags given to the command.
52
+ </p >
53
+ <p >
54
+ To mitigate this risk, either add a <code >--</code > argument to ensure subsequent arguments are
55
+ not interpreted as flags, or verify that the argument does not start with <code >"--"</code >.
56
+ </p >
57
+ <sample src =" examples/CommandInjectionGood3.go" />
51
58
</example >
52
59
<references >
53
60
<li >
0 commit comments