Skip to content

Commit

Permalink
subprocess: report errors when finding executables
Browse files Browse the repository at this point in the history
On Windows, when spawning a process, Go first looks for an
executable file with the correct name in the current directory, and
only if it fails to find one there does it look in the directories
listed in the PATH environment variable.  We would prefer not to
replicate this behaviour and instead search only in the directories
in PATH.  Therefore, starting with the mitigation of CVE-2020-27955
in commit 74d5f23, we resolve paths
to executables ourselves rather than rely on Go to do so.

The subprocess.LookPath() function we introduced in that change
is adapted from Go's os/exec package.  When it cannot find an
executable in PATH, it returns an empty path string and an
exec.ErrNotFound error.  When that happens, we do not detect the
condition and simply set the command path to the empty string.
This can lead to undesirable behaviour in which a bug in the Go
os/exec library causes it to run another executable other than
the one we intended.

When we set the command path to the empty string and then ask to
execute the command, the native Go version of the LookPath() function
for Windows is run with an empty path because filepath.Base() returns
"." when passed the empty string and because we have left the current
working directory also set to an empty string:

https://github.com/golang/go/blob/1724077b789ad92972ab1ac03788389645306cbb/src/os/exec/exec.go#L348-L353

Since the path string does not contain any path separator
characters the current working directory is searched to try to
find a file with a matching name and executable file extension
(e.g., ".exe" or ".com").  To search the current working directory,
the "." directory name is prepended to the given path with
filepath.Join():

https://github.com/golang/go/blob/1724077b789ad92972ab1ac03788389645306cbb/src/os/exec/lp_windows.go#L84

The filepath.Join() function ignores empty arguments, so this
results in an incorrect filename of ".".  All potential executable
file extensions from the PATHEXT environment variable (or from a
fixed list if that variable is not defined) are then appended to
this filename, including their leading dot separator characters,
thus producing filenames like "..com" and "..exe":

https://github.com/golang/go/blob/1724077b789ad92972ab1ac03788389645306cbb/src/os/exec/lp_windows.go#L46-L50

Should a file with one of these names exist in the current working
directory, its name will be returned, which means that it will be
executed instead of the command we expected to run.  This is
obviously undesirable and presents a risk to users.

(Note that batch files named "..bat" and "..cmd" will also be found
in the same manner, but they will not actually be executed due to an
undocumented feature of the Windows API's family of CreateProcess*()
functions, which are used by Go to spawn processes.  When passed an
lpApplicationName argument ending with a ".bat" or ".cmd" extension,
the CreateProcess*() functions appear to instead execute "cmd.exe"
and construct a "/c" command string from the lpCommandLine argument.
The value of that argument is set using the full command line we are
attempting to execute, and as such its first element is the actual
name of the executable we intended to run; therefore, the command
interpreter attempts to run the executable as a batch script and
fails, and the "..bat" or "..cmd" file is effectively ignored.)

To recap, when Git LFS attempts to execute a program on Windows,
if the executable is not found anywhere in PATH but does exist in
the current working directory, then when we call exec.Command()
Go's internal LookPath() function will find the executable and not
set the internal lookPathErr flag:

https://github.com/golang/go/blob/1724077b789ad92972ab1ac03788389645306cbb/src/os/exec/exec.go#L174-L179

Since we do not want to run executables in the current working
directory, we subsequently run our own LookPath() function, which
we use to reset the cmd.Path field.  However, when our LookPath()
returns an empty string, we do not detect that and instead set
cmd.Path to that value.  Then when we ask Go to run the command,
because lookPathErr is nil, it proceeds, and the empty path causes
it to find and run the first matching file in the working directory
named "..com" or "..exe" (or any similar name with an executable
file extension except for "..bat" and "..cmd").

We can prevent this behaviour by detecting when our LookPath()
function returns an error and propagating it upwards to all
callers of our subprocess.ExecCommand() function.  We also add
checks for this error at appropriate points and log or report
the error as necessary.

One particular circumstance of note occurs when a user has a
Cygwin-installed "uname" in their PATH but not "cygpath",
but "cygpath.exe" does exist in their current working directory.
Then we will attempt to execute "cygpath" because we use the
presence of "uname" as an indication that Cygwin is fully installed.
Should a "..exe" or similar file also be present in the working
directory, then it will be executed instead of "cygpath.exe".

As with all other instances where we call subprocess.ExecCommand(),
in tools.translateCygwinPath() we will now check for a returned
error before trying to actually execute "cygpath".  Unlike many
of the other cases, though, we do not need to report the error in
this one; instead, we simply return the current path from
translateCygwinPath() instead of canonicalizing it, just as we do
already if the "cygpath" executable fails for some reason.

Finally, we add a new test to t/t-path.sh which checks for the
incorrect execution of a "..exe" binary on Windows when "git.exe"
is not found in PATH but does exist in the current working
directory.  This test passes when run with a Git LFS binary that
includes the remediations from this commit, and fails otherwise.
For our "malicious" binary named "..exe" we make use of the
lfstest-badpathcheck test helper we added in a previous commit.
We only run this test on Windows because the underlying bug in
Go is Windows-specific as it depends on path extensions from
PATHEXT being appended to the file name ".".

Co-authored-by: brian m. carlson <bk2204@github.com>
  • Loading branch information
chrisd8088 and bk2204 committed Apr 19, 2022
1 parent 11092ef commit 762ccd4
Show file tree
Hide file tree
Showing 23 changed files with 229 additions and 56 deletions.
5 changes: 4 additions & 1 deletion commands/command_clone.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,8 +118,11 @@ func postCloneSubmodules(args []string) error {
// Use `git submodule foreach --recursive` to cascade into nested submodules
// Also good to call a new instance of git-lfs rather than do things
// inside this instance, since that way we get a clean env in that subrepo
cmd := subprocess.ExecCommand("git", "submodule", "foreach", "--recursive",
cmd, err := subprocess.ExecCommand("git", "submodule", "foreach", "--recursive",
"git lfs pull")
if err != nil {
return err
}
cmd.Stderr = os.Stderr
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
Expand Down
7 changes: 6 additions & 1 deletion commands/command_ls_files.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"os"
"strings"

"github.com/git-lfs/git-lfs/v3/errors"
"github.com/git-lfs/git-lfs/v3/git"
"github.com/git-lfs/git-lfs/v3/lfs"
"github.com/git-lfs/git-lfs/v3/tools/humanize"
Expand Down Expand Up @@ -50,7 +51,11 @@ func lsFilesCommand(cmd *cobra.Command, args []string) {
} else {
fullref, err := git.CurrentRef()
if err != nil {
ref = git.EmptyTree()
ref, err = git.EmptyTree()
if err != nil {
ExitWithError(errors.Wrap(
err, tr.Tr.Get("Could not read empty Git tree object")))
}
} else {
ref = fullref.Sha
}
Expand Down
6 changes: 5 additions & 1 deletion commands/command_status.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,12 @@ func statusCommand(cmd *cobra.Command, args []string) {
ref, _ := git.CurrentRef()

scanIndexAt := "HEAD"
var err error
if ref == nil {
scanIndexAt = git.EmptyTree()
scanIndexAt, err = git.EmptyTree()
if err != nil {
ExitWithError(err)
}
}

scanner, err := lfs.NewPointerScanner(cfg.GitEnv(), cfg.OSEnv())
Expand Down
5 changes: 4 additions & 1 deletion commands/path_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,10 @@ func cleanRootPath(pattern string) string {

if len(winBashPrefix) < 1 {
// cmd.Path is something like C:\Program Files\Git\usr\bin\pwd.exe
cmd := subprocess.ExecCommand("pwd")
cmd, err := subprocess.ExecCommand("pwd")
if err != nil {
return pattern
}
winBashPrefix = strings.Replace(filepath.Dir(filepath.Dir(filepath.Dir(cmd.Path))), `\`, "/", -1) + "/"
}

Expand Down
5 changes: 4 additions & 1 deletion commands/pull.go
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,10 @@ func (i *gitIndexer) Add(path string) error {

if i.cmd == nil {
// Fire up the update-index command
cmd := git.UpdateIndexFromStdin()
cmd, err := git.UpdateIndexFromStdin()
if err != nil {
return err
}
cmd.Stdout = &i.output
cmd.Stderr = &i.output
stdin, err := cmd.StdinPipe()
Expand Down
13 changes: 10 additions & 3 deletions creds/creds.go
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,11 @@ func (a *AskPassCredentialHelper) getFromProgram(valueType credValueType, u *url

// 'cmd' will run the GIT_ASKPASS (or core.askpass) command prompting
// for the desired valueType (`Username` or `Password`)
cmd := subprocess.ExecCommand(a.Program, a.args(fmt.Sprintf("%s for %q", valueString, u))...)
cmd, errVal := subprocess.ExecCommand(a.Program, a.args(fmt.Sprintf("%s for %q", valueString, u))...)
if errVal != nil {
tracerx.Printf("creds: failed to find GIT_ASKPASS command: %s", a.Program)
return "", errVal
}
cmd.Stderr = &err
cmd.Stdout = &value

Expand Down Expand Up @@ -301,7 +305,10 @@ func (h *commandCredentialHelper) Approve(creds Creds) error {

func (h *commandCredentialHelper) exec(subcommand string, input Creds) (Creds, error) {
output := new(bytes.Buffer)
cmd := subprocess.ExecCommand("git", "credential", subcommand)
cmd, err := subprocess.ExecCommand("git", "credential", subcommand)
if err != nil {
return nil, errors.New(tr.Tr.Get("failed to find `git credential %s`: %v", subcommand, err))
}
cmd.Stdin = bufferCreds(input)
cmd.Stdout = output
/*
Expand All @@ -316,7 +323,7 @@ func (h *commandCredentialHelper) exec(subcommand string, input Creds) (Creds, e
*/
cmd.Stderr = os.Stderr

err := cmd.Start()
err = cmd.Start()
if err == nil {
err = cmd.Wait()
}
Expand Down
5 changes: 4 additions & 1 deletion git/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,10 @@ func (c *Configuration) Source() (*ConfigurationSource, error) {

func (c *Configuration) gitConfig(args ...string) (string, error) {
args = append([]string{"config", "--includes"}, args...)
cmd := subprocess.ExecCommand("git", args...)
cmd, err := subprocess.ExecCommand("git", args...)
if err != nil {
return "", err
}
if len(c.GitDir) > 0 {
cmd.Dir = c.GitDir
}
Expand Down
Loading

0 comments on commit 762ccd4

Please # to comment.