git-lfs/lfshttp/standalone/standalone.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

306 lines
8.1 KiB
Go

package standalone
import (
"bufio"
"encoding/json"
"fmt"
"io/ioutil"
"net/url"
"os"
"path/filepath"
"regexp"
"runtime"
"strings"
"github.com/git-lfs/git-lfs/v3/config"
"github.com/git-lfs/git-lfs/v3/errors"
"github.com/git-lfs/git-lfs/v3/lfs"
"github.com/git-lfs/git-lfs/v3/lfsapi"
"github.com/git-lfs/git-lfs/v3/subprocess"
"github.com/git-lfs/git-lfs/v3/tools"
"github.com/git-lfs/git-lfs/v3/tr"
"github.com/rubyist/tracerx"
)
// inputMessage represents a message from Git LFS to the standalone transfer
// agent. Not all fields will be filled in on all requests.
type inputMessage struct {
Event string `json:"event"`
Operation string `json:"operation"`
Remote string `json:"remote"`
Oid string `json:"oid"`
Size int64 `json:"size"`
Path string `json:"path"`
}
// errorMessage represents an optional error message that may occur in a
// completion response.
type errorMessage struct {
Message string `json:"message"`
}
// completeMessage represents a completion response.
type completeMessage struct {
Event string `json:"event"`
Oid string `json:"oid"`
Path string `json:"path,omitempty"`
Error *errorMessage `json:"error,omitempty"`
}
type fileHandler struct {
remotePath string
remoteConfig *config.Configuration
output *os.File
config *config.Configuration
tempdir string
}
// fileUrlFromRemote looks up the URL depending on the remote. The remote can be
// a literal URL or the name of a remote.
//
// In this situation, we only accept file URLs.
func fileUrlFromRemote(cfg *config.Configuration, name string, direction string) (*url.URL, error) {
if strings.HasPrefix(name, "file://") {
if url, err := url.Parse(name); err == nil {
return url, nil
}
}
apiClient, err := lfsapi.NewClient(cfg)
if err != nil {
return nil, err
}
for _, remote := range cfg.Remotes() {
if remote != name {
continue
}
remoteEndpoint := apiClient.Endpoints.Endpoint(direction, remote)
if !strings.HasPrefix(remoteEndpoint.Url, "file://") {
return nil, nil
}
return url.Parse(remoteEndpoint.Url)
}
return nil, nil
}
// gitDirAtPath finds the .git directory corresponding to the given path, which
// may be the .git directory itself, the working tree, or the root of a bare
// repository.
//
// We filter out the GIT_DIR environment variable to ensure we get the expected
// result, and we change directories to ensure that we can make use of
// filepath.Abs. Using --absolute-git-dir instead of --git-dir is not an option
// because we support Git versions that don't have --absolute-git-dir.
func gitDirAtPath(path string) (string, error) {
// Filter out all the GIT_* environment variables.
env := os.Environ()
n := 0
for _, val := range env {
if !strings.HasPrefix(val, "GIT_") {
env[n] = val
n++
}
}
env = env[:n]
// Trim any trailing .git path segment.
if filepath.Base(path) == ".git" {
path = filepath.Dir(path)
}
curdir, err := os.Getwd()
if err != nil {
return "", err
}
err = os.Chdir(path)
if err != nil {
return "", err
}
cmd, err := subprocess.ExecCommand("git", "rev-parse", "--git-dir")
if err != nil {
return "", errors.Wrap(err, tr.Tr.Get("failed to find `git rev-parse --git-dir`"))
}
cmd.Cmd.Env = env
out, err := cmd.Output()
if err != nil {
return "", errors.Wrap(err, tr.Tr.Get("failed to call `git rev-parse --git-dir`"))
}
gitdir, err := tools.TranslateCygwinPath(strings.TrimRight(string(out), "\n"))
if err != nil {
return "", errors.Wrap(err, tr.Tr.Get("unable to translate path"))
}
gitdir, err = filepath.Abs(gitdir)
if err != nil {
return "", errors.Wrap(err, tr.Tr.Get("unable to canonicalize path"))
}
err = os.Chdir(curdir)
if err != nil {
return "", err
}
return tools.CanonicalizeSystemPath(gitdir)
}
func fixUrlPath(path string) string {
if runtime.GOOS != "windows" {
return path
}
// When parsing a file URL, Go produces a path starting with a slash. If
// it looks like there's a Windows drive letter at the beginning, strip
// off the beginning slash. If this is a Unix-style path from a
// Cygwin-like environment, we'll canonicalize it later.
re := regexp.MustCompile("/[A-Za-z]:/")
if re.MatchString(path) {
return path[1:]
}
return path
}
// newHandler creates a new handler for the protocol.
func newHandler(cfg *config.Configuration, output *os.File, msg *inputMessage) (*fileHandler, error) {
url, err := fileUrlFromRemote(cfg, msg.Remote, msg.Operation)
if err != nil {
return nil, err
}
if url == nil {
return nil, errors.New(tr.Tr.Get("no valid file:// URLs found"))
}
path, err := tools.TranslateCygwinPath(fixUrlPath(url.Path))
if err != nil {
return nil, err
}
gitdir, err := gitDirAtPath(path)
if err != nil {
return nil, err
}
tempdir, err := ioutil.TempDir(cfg.TempDir(), "lfs-standalone-file-*")
if err != nil {
return nil, err
}
tracerx.Printf("using %q as remote git directory", gitdir)
return &fileHandler{
remotePath: path,
remoteConfig: config.NewIn(gitdir, gitdir),
output: output,
config: cfg,
tempdir: tempdir,
}, nil
}
// dispatch dispatches the event depending on the message type.
func (h *fileHandler) dispatch(msg *inputMessage) bool {
switch msg.Event {
case "init":
fmt.Fprintln(h.output, "{}")
case "upload":
h.respond(h.upload(msg.Oid, msg.Size, msg.Path))
case "download":
h.respond(h.download(msg.Oid, msg.Size))
case "terminate":
return false
default:
standaloneFailure(tr.Tr.Get("unknown event %q", msg.Event), nil)
}
return true
}
// respond sends a response to an upload or download command, using the return
// values from those functions.
func (h *fileHandler) respond(oid string, path string, err error) {
response := &completeMessage{
Event: "complete",
Oid: oid,
Path: path,
}
if err != nil {
response.Error = &errorMessage{Message: err.Error()}
}
json.NewEncoder(h.output).Encode(response)
}
// upload performs the upload action for the given OID, size, and path. It
// returns arguments suitable for the respond method.
func (h *fileHandler) upload(oid string, size int64, path string) (string, string, error) {
if h.remoteConfig.LFSObjectExists(oid, size) {
// Already there, nothing to do.
return oid, "", nil
}
dest, err := h.remoteConfig.Filesystem().ObjectPath(oid)
if err != nil {
return oid, "", err
}
return oid, "", lfs.LinkOrCopy(h.remoteConfig, path, dest)
}
// download performs the download action for the given OID and size. It returns
// arguments suitable for the respond method.
func (h *fileHandler) download(oid string, size int64) (string, string, error) {
if !h.remoteConfig.LFSObjectExists(oid, size) {
tracerx.Printf("missing object in %q (%s)", h.remotePath, oid)
return oid, "", errors.Errorf(tr.Tr.Get("remote missing object %s", oid))
}
src, err := h.remoteConfig.Filesystem().ObjectPath(oid)
if err != nil {
return oid, "", err
}
tmp, err := ioutil.TempFile(h.tempdir, "download")
if err != nil {
return oid, "", err
}
tmp.Close()
os.Remove(tmp.Name())
path := tmp.Name()
return oid, path, lfs.LinkOrCopy(h.config, src, path)
}
// standaloneFailure reports a fatal error.
func standaloneFailure(msg string, err error) {
fmt.Fprintf(os.Stderr, "%s: %s\n", msg, err)
os.Exit(2)
}
// ProcessStandaloneData is the primary endpoint for processing data with a
// standalone transfer agent. It reads input from the specified input file and
// produces output to the specified output file.
func ProcessStandaloneData(cfg *config.Configuration, input *os.File, output *os.File) error {
var handler *fileHandler
scanner := bufio.NewScanner(input)
for scanner.Scan() {
var msg inputMessage
if err := json.NewDecoder(strings.NewReader(scanner.Text())).Decode(&msg); err != nil {
return errors.Wrapf(err, tr.Tr.Get("error decoding JSON"))
}
if handler == nil {
var err error
handler, err = newHandler(cfg, output, &msg)
if err != nil {
return errors.Wrapf(err, tr.Tr.Get("error creating handler"))
}
}
if !handler.dispatch(&msg) {
break
}
}
if handler != nil {
os.RemoveAll(handler.tempdir)
}
if err := scanner.Err(); err != nil {
return errors.Wrapf(err, tr.Tr.Get("error reading input"))
}
return nil
}