Is it possible to do command injection in os/exec Command method?

Viewed 34

My goal is to understand whether it is safe to use the Command method from os/exec package. This is important because I process file from the internet. Do I need to sanitize the file before adding it to exec.Command() ?

What I've did:

  1. Tried to use &&, it does not work.
    injection := "&& sh bash.sh"
    out, err := exec.Command("ls", injection).Output()
    fmt.Println(string(out), err)

bash.sh

#!/bin/bash
echo "Hello World"
1 Answers

As you're only passing thes arguments to ls, and not to sh, there's not really any (obvious) opportunity for "command injection", but there's still plenty of opportunity for shennanigans.

At the very least, someone may be able to pass an argument that could crash ls, or cause your disks to thrash. Arguments like */***********/**** or ../../../../../../../ or other odd combinations might do unexpected things. (I recall reading of web server exploits in the past using similar paths and causing a crash or hang of the system, trying to resolve an "impossible" path)

Further, depending on what you do with the result of ls, the user may be able to use this to learn priviledged information about your system. For example, someone might pass /home as an argument, and be returned a list of all users on your system. If your service is running as root, they may be able to get other priveledged information from various points in /var or /dev or elsewhere.

And finally, if there's ever a bug in ls, someone may be able to take advantage of that to do, well, whatever the bug permits.

Related