Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
111 changes: 111 additions & 0 deletions desktop/internal/buildprocess/batch.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
package buildprocess

import (
"errors"
"path/filepath"
"strings"
)

// Windows runs a .cmd or .bat file through cmd.exe, which parses the whole command line again
// by its own rules. When Windows starts the script itself (os/exec on Windows does), the line
// becomes `cmd.exe /c <line>`, and cmd removes the first and the last quote of a line that holds
// more than two. A script under a directory with a space (C:\Program Files\...\mvn.cmd) then
// fails as soon as one argument is quoted too: cmd runs `C:\Program` (#2032). cmd also expands
// %VAR% and acts on & | < > ^ in an argument that is not quoted, so an argument can run a
// command (BatBadBut, CVE-2024-24576).
//
// batchCommandLine builds the line the host gives cmd.exe instead: the script and its arguments
// wrapped in one more pair of quotes, which cmd's /c removes, so the quotes inside stay as
// written. Arguments are quoted and escaped as Rust's standard library does since that
// advisory: every argument with a character other than letters, digits and #$*+-./:?@\_ is
// quoted, a quote is doubled, backslashes before a quote are doubled, and % is broken up so
// cmd never sees a variable.

// errBatchArgument is a script path or argument that cmd.exe cannot be given safely.
var errBatchArgument = errors.New("buildprocess: a batch file cannot be given this argument")

// isBatchFile says whether Windows would run executable through cmd.exe.
func isBatchFile(executable string) bool {
switch strings.ToLower(filepath.Ext(executable)) {
case ".cmd", ".bat":
return true
}
return false
}

// batchCommandLine is the command line for cmd.exe that runs script with arguments, each of
// which the script receives exactly as given.
func batchCommandLine(script string, arguments []string) (string, error) {
// A Windows file name holds no quote and does not end in a separator; either would end
// the script's quotes early.
if script == "" || strings.ContainsAny(script, "\"\x00\r\n") || strings.HasSuffix(script, `\`) {
return "", errBatchArgument
}
var line strings.Builder
// /d skips AutoRun commands, /e:ON keeps the %cd:~,% expansion below working and /v:OFF
// keeps ! literal, whatever the user's registry defaults are.
line.WriteString(`cmd.exe /e:ON /v:OFF /d /c ""`)
line.WriteString(script)
line.WriteByte('"')
for _, argument := range arguments {
// A line break ends cmd's command, so the rest would be a second command.
if strings.ContainsAny(argument, "\x00\r\n") {
return "", errBatchArgument
}
line.WriteByte(' ')
appendBatchArgument(&line, argument)
}
line.WriteByte('"')
return line.String(), nil
}

func appendBatchArgument(line *strings.Builder, argument string) {
// An empty argument would vanish unquoted, and a trailing backslash would otherwise
// escape the closing quote of a script that quotes "%~1".
quote := argument == "" || strings.HasSuffix(argument, `\`)
for _, r := range argument {
if r < 0x80 {
if !isUnquotedBatchByte(byte(r)) {
quote = true
}
} else if r < 0xa0 {
// C1 control characters.
quote = true
}
}
if quote {
line.WriteByte('"')
}
backslashes := 0
for _, r := range argument {
if r == '\\' {
backslashes++
line.WriteRune(r)
continue
}
switch r {
case '"':
// Backslashes before a quote are doubled, and the quote itself is doubled.
line.WriteString(strings.Repeat(`\`, backslashes))
line.WriteByte('"')
case '%':
// %cd:~,% is an empty substring of a variable that always exists, so cmd expands it
// to nothing and the % that follows can no longer start a variable name.
line.WriteString(`%%cd:~,`)
}
backslashes = 0
line.WriteRune(r)
}
if quote {
line.WriteString(strings.Repeat(`\`, backslashes))
line.WriteByte('"')
}
}

func isUnquotedBatchByte(c byte) bool {
switch {
case c >= 'a' && c <= 'z', c >= 'A' && c <= 'Z', c >= '0' && c <= '9':
return true
}
return strings.IndexByte(`#$*+-./:?@\_`, c) >= 0
}
73 changes: 73 additions & 0 deletions desktop/internal/buildprocess/batch_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
package buildprocess

import (
"errors"
"testing"
)

func TestBatchCommandLineQuotesTheWholeLineOnce(t *testing.T) {
// The shape of Maven's model load (#2032): a script and an argument that both hold a space.
line, err := batchCommandLine(`C:\Program Files\maven\bin\mvn.cmd`, []string{
"-B", `-Dmaven.ext.class.path=C:\Users\me\AppData\Local\Lithe Desktop\x.jar`, "pre-clean",
})
if err != nil {
t.Fatal(err)
}
want := `cmd.exe /e:ON /v:OFF /d /c ""C:\Program Files\maven\bin\mvn.cmd" -B "-Dmaven.ext.class.path=C:\Users\me\AppData\Local\Lithe Desktop\x.jar" pre-clean"`
if line != want {
t.Fatalf("line =\n%s\nwant\n%s", line, want)
}
}

func TestBatchArgumentsCannotReachCmdSyntax(t *testing.T) {
for _, tc := range []struct{ argument, want string }{
{"plain-arg_1.0", `plain-arg_1.0`},
{"", `""`},
{`trailing\`, `"trailing\\"`},
{`a&b`, `"a&b"`},
{`x|y<z>^`, `"x|y<z>^"`},
{`%PATH%`, `"%%cd:~,%PATH%%cd:~,%"`},
{`say "hi"`, `"say ""hi"""`},
{`back\"slash`, `"back\\""slash"`},
{`(group)!`, `"(group)!"`},
{`ünïcode`, `ünïcode`},
} {
line, err := batchCommandLine(`C:\s.cmd`, []string{tc.argument})
if err != nil {
t.Fatalf("%q: %v", tc.argument, err)
}
want := `cmd.exe /e:ON /v:OFF /d /c ""C:\s.cmd" ` + tc.want + `"`
if line != want {
t.Fatalf("%q:\n got %s\nwant %s", tc.argument, line, want)
}
}
}

func TestBatchCommandLineRefusesWhatWouldEndTheCommand(t *testing.T) {
for _, tc := range []struct {
script string
arguments []string
}{
{`C:\s.cmd`, []string{"one\ntwo"}},
{`C:\s.cmd`, []string{"one\rtwo"}},
{`C:\s.cmd`, []string{"nul\x00"}},
{`C:\dir\`, nil},
{`C:\a"b.cmd`, nil},
{"", nil},
} {
if _, err := batchCommandLine(tc.script, tc.arguments); !errors.Is(err, errBatchArgument) {
t.Fatalf("%q %q: err = %v", tc.script, tc.arguments, err)
}
}
}

func TestIsBatchFile(t *testing.T) {
for name, want := range map[string]bool{
`C:\m\mvn.cmd`: true, `C:\m\MVN.CMD`: true, `C:\g\gradlew.bat`: true,
`C:\j\java.exe`: false, `/usr/bin/mvn`: false, `C:\m\mvn.cmd.exe`: false,
} {
if got := isBatchFile(name); got != want {
t.Fatalf("isBatchFile(%q) = %v", name, got)
}
}
}
97 changes: 97 additions & 0 deletions desktop/internal/buildprocess/batch_windows_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
//go:build windows

package buildprocess

import (
"context"
"encoding/json"
"fmt"
"os"
"path/filepath"
"slices"
"strings"
"sync"
"testing"
"time"
)

const batchArgumentsMode = "LITHE_TEST_BATCH_ARGUMENTS"

// TestBatchArgumentsHelper prints the arguments after "--" as JSON. A test script passes its
// own arguments on to it with %*, as mvn.cmd passes them to Java.
func TestBatchArgumentsHelper(t *testing.T) {
if os.Getenv(batchArgumentsMode) != "1" {
return
}
index := slices.Index(os.Args, "--")
if index < 0 {
os.Exit(21)
}
data, err := json.Marshal(os.Args[index+1:])
if err != nil {
os.Exit(22)
}
fmt.Println(string(data))
os.Exit(0)
}

// A script under a directory with a space receives every argument as written, including ones
// with spaces, quotes and cmd syntax, the way Maven's model load runs mvn.cmd (#2032).
func TestBatchFileUnderASpacedDirectoryReceivesItsArguments(t *testing.T) {
directory := filepath.Join(t.TempDir(), "Program Files", "tool home")
if err := os.MkdirAll(filepath.Join(directory, "bin"), 0o755); err != nil {
t.Fatal(err)
}
script := filepath.Join(directory, "bin", "tool.cmd")
body := "@echo off\r\n\"" + os.Args[0] + "\" \"-test.run=^TestBatchArgumentsHelper$\" -- %*\r\nexit /b %ERRORLEVEL%\r\n"
if err := os.WriteFile(script, []byte(body), 0o644); err != nil {
t.Fatal(err)
}
marker := filepath.Join(t.TempDir(), "injected")
arguments := []string{
"-B",
`-Dmaven.ext.class.path=C:\Users\me\AppData\Local\Lithe Desktop\plugins\x.jar`,
"-Dlithe.modelOutput=" + filepath.Join(directory, "model out.json"),
"",
`trailing\`,
`say "hi"`,
"%" + batchArgumentsMode + "%",
"a&echo injected>" + marker,
`x|y<z>^`,
"pre-clean",
}
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
var output strings.Builder
var mu sync.Mutex
process, err := Start(ctx, Spec{
Executable: script,
Arguments: arguments,
WorkingDirectory: directory,
Environment: map[string]string{batchArgumentsMode: "1"},
}, func(_ Stream, text string) {
mu.Lock()
output.WriteString(text)
mu.Unlock()
})
if err != nil {
t.Fatal(err)
}
waitErr := process.Wait()
mu.Lock()
text := output.String()
mu.Unlock()
if waitErr != nil {
t.Fatalf("script failed: %v\n%s", waitErr, text)
}
var got []string
if err := json.Unmarshal([]byte(strings.TrimSpace(text)), &got); err != nil {
t.Fatalf("output is not the helper's JSON: %v\n%s", err, text)
}
if !slices.Equal(got, arguments) {
t.Fatalf("arguments =\n%q\nwant\n%q", got, arguments)
}
if _, err := os.Stat(marker); err == nil {
t.Fatal("an argument ran a command")
}
}
7 changes: 5 additions & 2 deletions desktop/internal/buildprocess/process.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,8 +108,11 @@ func Start(ctx context.Context, spec Spec, observe func(Stream, string)) (*Proce
command.Stdout = stdoutWrite
command.Stderr = stderrWrite
platform := &processPlatform{}
platform.configure(command)
if err := command.Start(); err != nil {
err = platform.configure(command)
if err == nil {
err = command.Start()
}
if err != nil {
for _, file := range []*os.File{stdoutRead, stdoutWrite, stderrRead, stderrWrite} {
_ = file.Close()
}
Expand Down
3 changes: 2 additions & 1 deletion desktop/internal/buildprocess/process_unix.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,9 @@ type processPlatform struct {

// configure puts the process in its own group so Stop can end the whole build
// tree, including wrappers that start child compilers.
func (*processPlatform) configure(command *exec.Cmd) {
func (*processPlatform) configure(command *exec.Cmd) error {
command.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
return nil
}

func (p *processPlatform) adopt(process *os.Process) error {
Expand Down
20 changes: 19 additions & 1 deletion desktop/internal/buildprocess/process_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"errors"
"os"
"os/exec"
"path/filepath"
"sync"
"syscall"
"unsafe"
Expand All @@ -29,10 +30,27 @@ type processPlatform struct {
active bool
}

func (p *processPlatform) configure(command *exec.Cmd) {
func (p *processPlatform) configure(command *exec.Cmd) error {
command.SysProcAttr = &syscall.SysProcAttr{
CreationFlags: windows.CREATE_NO_WINDOW | windows.CREATE_SUSPENDED | windows.CREATE_NEW_PROCESS_GROUP,
}
// A program that was not found keeps its lookup error for Start to report.
if command.Err != nil || !isBatchFile(command.Path) {
return nil
}
// A script runs through cmd.exe; the host starts cmd.exe itself with a line it built, so
// the script's path and arguments reach it as written (batch.go).
line, err := batchCommandLine(command.Path, command.Args[1:])
if err != nil {
return err
}
system, err := windows.GetSystemDirectory()
if err != nil {
return err
}
command.Path = filepath.Join(system, "cmd.exe")
command.SysProcAttr.CmdLine = line
return nil
}

func (p *processPlatform) adopt(process *os.Process) error {
Expand Down
13 changes: 9 additions & 4 deletions desktop/internal/core/toolchain.go
Original file line number Diff line number Diff line change
Expand Up @@ -207,14 +207,19 @@ type ToolchainCandidatesRequest struct {
SystemInstallations []ToolchainSystemInstallation `json:"systemInstallations,omitempty"`
ProviderInstallations []ToolchainProviderInstallation `json:"providerInstallations,omitempty"`
Environment map[string]string `json:"environment,omitempty"`
Fixed *ToolchainFixed `json:"fixed,omitempty"`
ProjectCodeAllowed bool `json:"projectCodeAllowed,omitempty"`
// CommandHomes maps each declared command found on the PATH to its home, as for
// toolchains.resolve; Core lists those homes as shell candidates too.
CommandHomes map[string]string `json:"commandHomes,omitempty"`
Fixed *ToolchainFixed `json:"fixed,omitempty"`
ProjectCodeAllowed bool `json:"projectCodeAllowed,omitempty"`
}

// ToolchainShellCandidate is one login-shell home variable candidate.
// ToolchainShellCandidate is one login-shell home: a declared variable's value, or
// where a declared command was found on the PATH (Command set, Variable empty).
type ToolchainShellCandidate struct {
CandidateID string `json:"candidateID"`
Variable string `json:"variable"`
Variable string `json:"variable,omitempty"`
Command string `json:"command,omitempty"`
Home string `json:"home"`
Executable string `json:"executable,omitempty"`
Version *string `json:"version,omitempty"`
Expand Down
9 changes: 7 additions & 2 deletions desktop/internal/settingswindow/toolchains_view.go
Original file line number Diff line number Diff line change
Expand Up @@ -500,14 +500,19 @@ func (w *window) toolchainTool(c ui.C, language i18n.Language, tool toolchain.To
})
}
for _, shell := range tool.Shell {
version := shell.Variable
// A variable's name, or the command found on the PATH: both are the user's own words.
source := shell.Variable
if source == "" {
source = shell.Command
}
version := source
if shell.Version != nil {
version += " " + *shell.Version
} else if shell.Reason != "" {
version += " " + shell.Reason
}
ui.Text(c, i18n.SharedFormat(language, "desktop.toolchains.installation", map[string]string{
"home": shell.Home, "version": version, "provider": shell.Variable,
"home": shell.Home, "version": version, "provider": source,
})).FontSize(11).Color(w.pal.muted)
}
if tool.ProviderQueriesUnsupported {
Expand Down
1 change: 1 addition & 0 deletions desktop/internal/toolchain/load.go
Original file line number Diff line number Diff line change
Expand Up @@ -366,6 +366,7 @@ func prepareTool(ctx context.Context, kernel Kernel, workspace *workspace, regis
MinimumVersion: options.MinimumVersion,
SystemInstallations: prepared.installations,
Environment: prepared.environment,
CommandHomes: prepared.commandHomes,
Fixed: prepared.fixed,
}
candidates, err := kernel.ToolchainCandidatesOf(ctx, request)
Expand Down
Loading
Loading