...

Text file src/github.com/cli/safeexec/README.md

Documentation: github.com/cli/safeexec

     1# safeexec
     2
     3A Go module that provides a safer alternative to `exec.LookPath()` on Windows.
     4
     5The following, relatively common approach to running external commands has a subtle vulnerability on Windows:
     6```go
     7import "os/exec"
     8
     9func gitStatus() error {
    10    // On Windows, this will result in `.\git.exe` or `.\git.bat` being executed
    11    // if either were found in the current working directory.
    12    cmd := exec.Command("git", "status")
    13    return cmd.Run()
    14}
    15```
    16
    17Searching the current directory (surprising behavior) before searching folders listed in the PATH environment variable (expected behavior) seems to be intended in Go and unlikely to be changed: https://github.com/golang/go/issues/38736
    18
    19Since Go does not provide a version of [`exec.LookPath()`](https://golang.org/pkg/os/exec/#LookPath) that only searches PATH and does not search the current working directory, this module provides a `LookPath` function that works consistently across platforms.
    20
    21Example use:
    22```go
    23import (
    24    "os/exec"
    25    "github.com/cli/safeexec"
    26)
    27
    28func gitStatus() error {
    29    gitBin, err := safeexec.LookPath("git")
    30    if err != nil {
    31        return err
    32    }
    33    cmd := exec.Command(gitBin, "status")
    34    return cmd.Run()
    35}
    36```
    37
    38## TODO
    39
    40Ideally, this module would also provide `exec.Command()` and `exec.CommandContext()` equivalents that delegate to the patched version of `LookPath`. However, this doesn't seem possible since `LookPath` may return an error, while `exec.Command/CommandContext()` themselves do not return an error. In the standard library, the resulting `exec.Cmd` struct stores the LookPath error in a private field, but that functionality isn't available to us.

View as plain text