git-lfs/git/rev_list_scanner.go
Chris Darroch 762ccd4a49 subprocess: report errors when finding executables
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 74d5f2397f9abe4834bf1fe1fa02fd6c141b77ce, 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:

1724077b78/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():

1724077b78/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":

1724077b78/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:

1724077b78/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>
2022-04-19 09:45:20 -07:00

370 lines
11 KiB
Go

package git
import (
"bufio"
"encoding/hex"
"fmt"
"io"
"io/ioutil"
"regexp"
"strings"
"sync"
"github.com/git-lfs/git-lfs/v3/errors"
"github.com/git-lfs/git-lfs/v3/tr"
"github.com/rubyist/tracerx"
)
// ScanningMode is a constant type that allows for variation in the range of
// commits to scan when given to the `*git.RevListScanner` type.
type ScanningMode int
const (
// ScanRefsMode will scan between two refspecs.
ScanRefsMode ScanningMode = iota
// ScanAllMode will scan all history.
ScanAllMode
// ScanRangeToRemoteMode will scan the difference between any included
// SHA1s and a remote tracking ref.
ScanRangeToRemoteMode
)
// RevListOrder is a constant type that allows for variation in the ordering of
// revisions given by the *RevListScanner below.
type RevListOrder int
const (
// DefaultRevListOrder is the zero-value for this type and yields the
// results as given by git-rev-list(1) without any `--<t>-order`
// argument given. By default: reverse chronological order.
DefaultRevListOrder RevListOrder = iota
// DateRevListOrder gives the revisions such that no parents are shown
// before children, and otherwise in commit timestamp order.
DateRevListOrder
// AuthorDateRevListOrder gives the revisions such that no parents are
// shown before children, and otherwise in author date timestamp order.
AuthorDateRevListOrder
// TopoRevListOrder gives the revisions such that they appear in
// topological order.
TopoRevListOrder
)
// Flag returns the command-line flag to be passed to git-rev-list(1) in order
// to order the output according to the given RevListOrder. It returns both the
// flag ("--date-order", "--topo-order", etc) and a bool, whether or not to
// append the flag (for instance, DefaultRevListOrder requires no flag).
//
// Given a type other than those defined above, Flag() will panic().
func (o RevListOrder) Flag() (string, bool) {
switch o {
case DefaultRevListOrder:
return "", false
case DateRevListOrder:
return "--date-order", true
case AuthorDateRevListOrder:
return "--author-date-order", true
case TopoRevListOrder:
return "--topo-order", true
default:
panic(fmt.Sprintf("git/rev_list_scanner: %s", tr.Tr.Get("unknown RevListOrder %d", o)))
}
}
// ScanRefsOptions is an "options" type that is used to configure a scan
// operation on the `*git.RevListScanner` instance when given to the function
// `NewRevListScanner()`.
type ScanRefsOptions struct {
// Mode is the scan mode to apply, see above.
Mode ScanningMode
// Remote is the current remote to scan against, if using
// ScanRangeToRemoteMode.
Remote string
// SkipDeletedBlobs specifies whether or not to traverse into commit
// ancestry (revealing potentially deleted (unreferenced) blobs, trees,
// or commits.
SkipDeletedBlobs bool
// Order specifies the order in which revisions are yielded from the
// output of `git-rev-list(1)`. For more information, see the above
// documentation on the RevListOrder type.
Order RevListOrder
// CommitsOnly specifies whether or not the *RevListScanner should
// return only commits, or all objects in range by performing a
// traversal of the graph. By default, false: show all objects.
CommitsOnly bool
// WorkingDir specifies the working directory in which to run
// git-rev-list(1). If this is an empty string, (has len(WorkingDir) ==
// 0), it is equivalent to running in os.Getwd().
WorkingDir string
// Reverse specifies whether or not to give the revisions in reverse
// order.
Reverse bool
// SkippedRefs provides a list of refs to ignore.
SkippedRefs []string
// Mutex guards names.
Mutex *sync.Mutex
// Names maps Git object IDs (encoded as hex using
// hex.EncodeString()) to their names, i.e., a directory name
// (fully-qualified) for trees, or a pathspec for blob tree entries.
Names map[string]string
}
// GetName returns the name associated with a given blob/tree sha and "true" if
// it exists, or ("", false) if it doesn't.
//
// GetName is guarded by a use of o.Mutex, and is goroutine safe.
func (o *ScanRefsOptions) GetName(sha string) (string, bool) {
o.Mutex.Lock()
defer o.Mutex.Unlock()
name, ok := o.Names[sha]
return name, ok
}
// SetName sets the name associated with a given blob/tree sha.
//
// SetName is guarded by a use of o.Mutex, and is therefore goroutine safe.
func (o *ScanRefsOptions) SetName(sha, name string) {
o.Mutex.Lock()
defer o.Mutex.Unlock()
o.Names[sha] = name
}
// RevListScanner is a Scanner type that parses through results of the `git
// rev-list` command.
type RevListScanner struct {
// s is a buffered scanner feeding from the output (stdout) of
// git-rev-list(1) invocation.
s *bufio.Scanner
// closeFn is an optional type returning an error yielded by closing any
// resources held by an open (running) instance of the *RevListScanner
// type.
closeFn func() error
// name is the name of the most recently read object.
name string
// oid is the oid of the most recently read object.
oid []byte
// err is the most recently encountered error.
err error
}
var (
// ambiguousRegex is a regular expression matching the output of stderr
// when ambiguous refnames are encountered.
ambiguousRegex = regexp.MustCompile(`warning: refname (.*) is ambiguous`)
)
// NewRevListScanner instantiates a new RevListScanner instance scanning all
// revisions reachable by refs contained in "include" and not reachable by any
// refs included in "excluded", using the *ScanRefsOptions "opt" configuration.
//
// It returns a new *RevListScanner instance, or an error if one was
// encountered. Upon returning, the `git-rev-list(1)` instance is already
// running, and Scan() may be called immediately.
func NewRevListScanner(include, excluded []string, opt *ScanRefsOptions) (*RevListScanner, error) {
stdin, args, err := revListArgs(include, excluded, opt)
if err != nil {
return nil, err
}
cmd, err := gitNoLFS(args...)
if err != nil {
return nil, err
}
if len(opt.WorkingDir) > 0 {
cmd.Dir = opt.WorkingDir
}
cmd.Stdin = stdin
stdout, err := cmd.StdoutPipe()
if err != nil {
return nil, err
}
stderr, err := cmd.StderrPipe()
if err != nil {
return nil, err
}
tracerx.Printf("run_command: git %s", strings.Join(args, " "))
if err := cmd.Start(); err != nil {
return nil, err
}
return &RevListScanner{
s: bufio.NewScanner(stdout),
closeFn: func() error {
msg, _ := ioutil.ReadAll(stderr)
// First check if there was a non-zero exit code given
// when Wait()-ing on the command execution.
if err := cmd.Wait(); err != nil {
return errors.New(tr.Tr.Get("Error in `git %s`: %v %s",
strings.Join(args, " "), err, msg))
}
// If the command exited cleanly, but found an ambiguous
// refname, promote that to an error and return it.
//
// `git-rev-list(1)` does not treat ambiguous refnames
// as fatal (non-zero exit status), but we do.
if am := ambiguousRegex.FindSubmatch(msg); len(am) > 1 {
return errors.New(tr.Tr.Get("ref %q is ambiguous", am[1]))
}
return nil
},
}, nil
}
// revListArgs returns the arguments for a given included and excluded set of
// SHA1s, and ScanRefsOptions instance.
//
// In order, it returns the contents of stdin as an io.Reader, the args passed
// to git as a []string, and any error encountered in generating those if one
// occurred.
func revListArgs(include, exclude []string, opt *ScanRefsOptions) (io.Reader, []string, error) {
var stdin io.Reader
args := []string{"rev-list"}
if !opt.CommitsOnly {
args = append(args, "--objects")
}
if opt.Reverse {
args = append(args, "--reverse")
}
if orderFlag, ok := opt.Order.Flag(); ok {
args = append(args, orderFlag)
}
switch opt.Mode {
case ScanRefsMode:
if opt.SkipDeletedBlobs {
args = append(args, "--no-walk")
} else {
args = append(args, "--do-walk")
}
stdin = strings.NewReader(strings.Join(
includeExcludeShas(include, exclude), "\n"))
case ScanAllMode:
args = append(args, "--all")
case ScanRangeToRemoteMode:
args = append(args, "--ignore-missing")
if len(opt.SkippedRefs) == 0 {
args = append(args, "--not", "--remotes="+opt.Remote)
stdin = strings.NewReader(strings.Join(
includeExcludeShas(include, exclude), "\n"))
} else {
stdin = strings.NewReader(strings.Join(
append(includeExcludeShas(include, exclude), opt.SkippedRefs...), "\n"),
)
}
default:
return nil, nil, errors.New(tr.Tr.Get("unknown scan type: %d", opt.Mode))
}
return stdin, append(args, "--stdin", "--"), nil
}
func includeExcludeShas(include, exclude []string) []string {
include = nonZeroShas(include)
exclude = nonZeroShas(exclude)
args := make([]string, 0, len(include)+len(exclude))
for _, i := range include {
args = append(args, i)
}
for _, x := range exclude {
args = append(args, fmt.Sprintf("^%s", x))
}
return args
}
func nonZeroShas(all []string) []string {
nz := make([]string, 0, len(all))
for _, sha := range all {
if len(sha) > 0 && !IsZeroObjectID(sha) {
nz = append(nz, sha)
}
}
return nz
}
var startsWithObjectID = regexp.MustCompile(fmt.Sprintf(`\A%s`, ObjectIDRegex))
// Name is an optional field that gives the name of the object (if the object is
// a tree, blob).
//
// It can be called before or after Scan(), but will return "" if called
// before.
func (s *RevListScanner) Name() string { return s.name }
// OID is the hex-decoded bytes of the object's ID.
//
// It can be called before or after Scan(), but will return "" if called
// before.
func (s *RevListScanner) OID() []byte { return s.oid }
// Err returns the last encountered error (or nil) after a call to Scan().
//
// It SHOULD be called, checked and handled after a call to Scan().
func (s *RevListScanner) Err() error { return s.err }
// Scan scans the next entry given by git-rev-list(1), and returns true/false
// indicating if there are more results to scan.
func (s *RevListScanner) Scan() bool {
var err error
s.oid, s.name, err = s.scan()
if err != nil {
if err != io.EOF {
s.err = err
}
return false
}
return len(s.oid) > 0
}
// Close closes the RevListScanner by freeing any resources held by the
// instance while running, and returns any error encountered while doing so.
func (s *RevListScanner) Close() error {
if s.closeFn == nil {
return nil
}
return s.closeFn()
}
// scan provides the internal implementation of scanning a line of text from the
// output of `git-rev-list(1)`.
func (s *RevListScanner) scan() ([]byte, string, error) {
if !s.s.Scan() {
return nil, "", s.s.Err()
}
line := strings.TrimSpace(s.s.Text())
if len(line) < ObjectIDLengths[0] {
return nil, "", nil
}
oidhex := startsWithObjectID.FindString(line)
if len(oidhex) == 0 {
return nil, "", errors.New(tr.Tr.Get("missing OID in line (got %q)", line))
}
oid, err := hex.DecodeString(oidhex)
if err != nil {
return nil, "", err
}
var name string
if len(line) > len(oidhex) {
name = line[len(oidhex)+1:]
}
return oid, name, nil
}