Web application security · 5 MIN READ
Command injection: run tools without a shell and keep user input out of option position
Start external tools with exec.CommandContext and a fixed argv, block argument injection with validation and --, and bound the child's time and environment.
Go's os/exec does not invoke a shell: exec.Command takes a program and an argument slice, so semicolons and $(...) inside an argument are ordinary bytes. The operations lessons on Bash arguments and safe CLIs already rely on that. This lesson covers the injection that survives without a shell: a user value read as an option by the target program, an operation chosen by the request, and a child process that inherits your environment and outlives its deadline.
security · A MAP OF THE IDEA
- Fix program and argv
- Allow-list operations
- End options before data
- Bound time and env
Useful when
- Without a shell, no metacharacter in a user value is ever parsed.
- cmd.Args can be asserted in tests without running anything.
Watch out
- -- is honored by each program's parser, not by Go; check the target tool.
- A nil Env hands every secret in the service's environment to the child.
Implementation & operation cost: An allow-list per tool, explicit Env and Dir and a bounded output writer; starting a process stays far more expensive than calling a library.
Two injections: shell syntax and argument position
Shell injection needs a shell: sh -c, bash -c, cmd /c, or a script that hands its arguments to eval. Concatenating a user value into that single command string lets ; | && and $( ) start new commands, and quoting by hand fails on the first input that contains a quote. Argument injection needs no shell at all. Every program parses its own argv, so a value beginning with a dash is read as an option: --files0-from=FILE for GNU wc, --upload-pack=COMMAND for git ls-remote, -o for many tools that write files. The exec call is correct and the user still controls the program's behavior. Defending against both means deciding which argv positions hold data and making the target program agree.
Build the argv and print it without running anything
The program constructs commands and prints cmd.Args, the exact argv the child would receive. It never calls Run, Start or Output, so no process starts. It contrasts a shell string with a direct argv, rejects names that begin with a dash, and builds git invocations from an allow-list of operations with a timeout, a controlled environment and a bounded wait.
package main
import (
"context"
"errors"
"fmt"
"os/exec"
"strings"
"syscall"
"time"
)
// Vulnerable: the shell parses name as syntax, so ; | $( ) all work.
func countViaShell(name string) *exec.Cmd {
return exec.Command("sh", "-c", "wc -l "+name)
}
// countLines passes name as one argv element and ends option parsing first.
func countLines(ctx context.Context, name string) (*exec.Cmd, error) {
if name == "" || strings.HasPrefix(name, "-") {
return nil, errors.New("file name must not be empty or start with '-'")
}
return exec.CommandContext(ctx, "wc", "-l", "--", name), nil
}
// gitOps is the whole surface a request can reach: fixed argv per operation.
var gitOps = map[string][]string{
"status": {"status", "--porcelain=v1"},
"log": {"log", "--oneline", "--max-count=20"},
}
func gitCommand(ctx context.Context, op string) (*exec.Cmd, error) {
args, ok := gitOps[op]
if !ok {
return nil, fmt.Errorf("operation %q is not allowed", op)
}
cmd := exec.CommandContext(ctx, "git", args...)
cmd.Dir = "/srv/repos/site"
cmd.Env = []string{"PATH=/usr/bin:/bin", "LANG=C", "GIT_TERMINAL_PROMPT=0"}
cmd.Cancel = func() error { return cmd.Process.Signal(syscall.SIGTERM) }
cmd.WaitDelay = 2 * time.Second
return cmd, nil
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
hostile := "report.txt; touch pwned"
fmt.Printf("shell argv: %q\n", countViaShell(hostile).Args)
for _, name := range []string{hostile, "--files0-from=/etc/passwd", "-"} {
cmd, err := countLines(ctx, name)
if err != nil {
fmt.Printf("rejected %q: %v\n", name, err)
continue
}
fmt.Printf("direct argv: %q\n", cmd.Args)
}
for _, op := range []string{"log", "push"} {
cmd, err := gitCommand(ctx, op)
if err != nil {
fmt.Println("rejected:", err)
continue
}
fmt.Printf("git argv: %q\n", cmd.Args)
fmt.Printf("git env: %q\n", cmd.Env)
fmt.Println("git wait delay:", cmd.WaitDelay)
}
// Nothing above calls Run, Start or Output: no process was started.
}In the shell form the hostile name is part of one script, so sh would run touch pwned after wc. In the direct form the same bytes are one argument after --, and wc would only report that no file has that odd name. countLines rejects a leading dash before -- even matters; that also catches a lone -, which conventionally means standard input and which -- does not neutralize. gitCommand never copies request text into argv: the request selects a key, the argv comes from the map, and push is refused. Env replaces the environment entirely rather than adding to it. Cancel sends SIGTERM instead of the default Kill when the context ends (Windows supports only Kill), and WaitDelay bounds how long Wait then waits for the process to exit and its pipes to close. Args[0] is the name as written; the resolved executable is in cmd.Path.
Make the target program agree where options end
-- is a convention of each program's option parser, not of the kernel or of Go. Most getopt-style tools honor it, some treat it as data, and git uses it to separate revisions from paths, so git log -- main means the path main; git 2.24 and later accept --end-of-options for the revision case. Read the target's documentation, place user values after the terminator it actually supports, and still reject values that start with a dash when the field never legitimately does. Where the tool can read data from standard input or a file, prefer that over argv for free-form text. Never let a request choose the program name, and avoid wrapping tools whose purpose is to run other commands, such as find -exec, xargs, env, ssh or a script that calls eval.
Choose the executable and the operation in code
Map each user-visible operation to a complete argv in code, as gitOps does, and validate the few free-form values against strict patterns: a commit hash as 40 hexadecimal characters, a branch name against the repository's real branch list. Since Go 1.19, exec.LookPath refuses a program found through a relative PATH entry such as . and returns exec.ErrDot, which closes a classic hijack; an absolute path from configuration is clearer still. On Windows, a command line is a single string that each program parses itself, and .bat or .cmd files are interpreted by cmd.exe with its own metacharacters, so do not pass untrusted arguments to batch files there.
Bound time, output and inherited state
A request-scoped context lets a client disconnect or a deadline stop the child. By default CommandContext kills the process when the context is done, but a grandchild holding the output pipes can still keep Wait blocked, which is what WaitDelay bounds. Set Env explicitly: a nil Env inherits every variable of your service, including database URLs and API tokens, which the child may log or forward. Set Dir rather than relying on the service's working directory, cap captured output, and return a generic error to the client while logging argv and exit status for operators.
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
defer cancel()
cmd, err := gitCommand(ctx, r.PathValue("op"))
if err != nil {
http.Error(w, "unknown operation", http.StatusBadRequest)
return
}
out := newLimitedBuffer(1 << 20) // an io.Writer that fails past 1 MiB
cmd.Stdout, cmd.Stderr = out, out
if err := cmd.Run(); err != nil {
if ctx.Err() != nil {
http.Error(w, "operation timed out", http.StatusGatewayTimeout)
return
}
log.Printf("git %q failed: %v", cmd.Args, err)
http.Error(w, "operation failed", http.StatusInternalServerError)
return
}This fragment runs in your own service and reuses gitCommand from the program. newLimitedBuffer stands for a small io.Writer you write that returns an error once its byte budget is spent; an unbounded bytes.Buffer lets a chatty tool exhaust memory. Checking ctx.Err() separates a timeout from a non-zero exit, so the client sees 504 for one and 500 for the other, and neither response includes the tool's stderr.
Test the argv, not the side effect
Until Start is called, an exec.Cmd is a plain struct, so unit tests can assert on cmd.Args, cmd.Env and cmd.Dir for every operation and every hostile input, exactly as the program prints them, without installing the tool. Add a few integration tests that really run the command against a fixture directory with a short timeout. In review, search for sh -c, bash -c and cmd /c, for exec.Command calls whose program is not a constant, and for request-handling code that leaves Env nil.
TAKE THIS WITH YOU
Pass a fixed program and argv to exec.CommandContext, take operations from an allow-list, keep user values out of option position with validation and the target's terminator, and set Env, Dir, Cancel and WaitDelay deliberately.
Check your understanding
exec.Command runs no shell. Why put "--" before a user-supplied file name in the argument list?
Go to the source
Progress stays in this browser. No account needed.