@@ -12,26 +12,49 @@ a malicious user may be able to run commands to exfiltrate data or compromise th
1212
1313<recommendation >
1414<p >
15- If possible, use hard-coded string literals to specify the command to run. Instead of interpreting
16- user input directly as command names, examine the input and then choose among hard-coded string
17- literals.
15+ Whenever possible, use hard-coded string literals for commands and avoid shell
16+ string interpreters like <code >sh -c</code >.
1817</p >
1918<p >
20- If this is not possible, then add sanitization code to verify that the user input is safe before
21- using it.
19+ If given arguments as a single string, avoid simply splitting the string on
20+ whitespace. Arguments may contain quoted whitespace, causing them to split into
21+ multiple arguments.
22+ </p >
23+ <p >
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.
2226</p >
2327</recommendation >
2428
2529<example >
2630<p >
27- In the following example, assume the function <code >handler</code > is an HTTP request handler in a
28- web application, whose parameter <code >req</code > contains the request object:
31+ In the following example, assume the function <code >handler</code > is an HTTP request
32+ handler in a web application, whose parameter <code >req</code > contains the request object:
33+ </p >
34+ <sample src =" examples/CommandInjection.go" />
35+ <p >
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.
38+ </p >
39+ <p >
40+ It's better to avoid shell commands by using the <code >exec.Command</code > function directly,
41+ as shown in the following example:
42+ </p >
43+ <sample src =" examples/CommandInjectionGood.go" />
44+ <p >
45+ Alternatively, a regular expression can be used to ensure that the image name is safe to use
46+ in a shell command:
47+ </p >
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.
2952</p >
30- <sample src =" CommandInjection.go" />
3153<p >
32- The handler extracts the name of a system command from the request object, and then runs it without
33- any further checks, which can cause a command-injection vulnerability .
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 > .
3456</p >
57+ <sample src =" examples/CommandInjectionGood3.go" />
3558</example >
3659<references >
3760<li >
0 commit comments