fix: harden agentctl bind, git clone args, and powershell sound escaping (#1811)
* fix: harden agentctl bind, git clone args, and powershell sound escaping Three LOW-severity defense-in-depth hardening fixes with PoC + regression tests: - notifications: escapePowerShell now neutralizes backtick and `$` in addition to `"`, defusing `$(...)` sub-expression and `$var` injection through an operator-supplied SoundFile path interpolated into the powershell `-c` script. - office/skills: git clone for git-sourced skills now passes a `--` end-of-options separator before the source locator (matching configloader), so a `-`-prefixed locator can never be parsed as a git flag. - agentctl: new Config.ListenHost() binds the control server and per-instance listeners to loopback only when no AuthToken is configured (auth disabled), so the unauthenticated command/shell/process routes are never reachable beyond localhost. The normal nonce-handshake flow (incl. Docker) always has a token and keeps binding all interfaces. * test: make PoC tests flip and drop indexOf coupling Address review feedback on the security-hardening PoCs: - system_provider PoC now demonstrates the PowerShell sub-expression injection against a legacyEscapePowerShell copy of the unfixed function and asserts the current escaper defuses it, so the PoC genuinely flips instead of passing trivially against fixed code (a substring match on `$(` matched the escaped form too). - materialization PoC + regression test use stdlib slices.Index instead of a custom indexOf defined in the PoC file, removing the coupling where deleting the PoC file would break the regression test. --------- Co-authored-by: Kandev Agent <agent@kandev.dev>
This commit is contained in:
@@ -115,8 +115,10 @@ func run(cfg *config.Config, log *logger.Logger) {
|
||||
// Create control server
|
||||
controlServer := api.NewControlServer(cfg, instMgr, log)
|
||||
|
||||
// Start HTTP server
|
||||
addr := fmt.Sprintf(":%d", cfg.Port)
|
||||
// Start HTTP server. When no auth token is configured (auth disabled),
|
||||
// ListenHost binds to loopback only so the unauthenticated command/shell/
|
||||
// process routes are never reachable beyond the local host.
|
||||
addr := fmt.Sprintf("%s:%d", cfg.ListenHost(), cfg.Port)
|
||||
httpServer := &http.Server{
|
||||
Addr: addr,
|
||||
Handler: controlServer.Router(),
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// TestBearerTokenAuth_EmptyToken_ExposesCommandRoutes_PoC demonstrates the
|
||||
// LOW-severity defense-in-depth gap: when AuthToken is empty the bearer-token
|
||||
// middleware becomes a pass-through, so a request with NO Authorization header
|
||||
// reaches command-execution routes such as /api/v1/processes/start (which runs
|
||||
// `sh -lc <command>`), git, and /api/v1/shell/*.
|
||||
//
|
||||
// This is by design for standalone loopback mode (no nonce → no token), but is
|
||||
// a real risk if the listener is ever bound beyond loopback. The fix does NOT
|
||||
// change this middleware behavior (that would need a product decision); it
|
||||
// enforces loopback-only binding when no token is configured, so this
|
||||
// pass-through is only ever reachable from localhost. See the ListenHost guard
|
||||
// (config package) and the open question noted in the task report.
|
||||
func TestBearerTokenAuth_EmptyToken_ExposesCommandRoutes_PoC(t *testing.T) {
|
||||
r := gin.New()
|
||||
r.Use(bearerTokenAuth("" /* no token → auth disabled */))
|
||||
r.POST("/api/v1/processes/start", func(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"status": "command executed"})
|
||||
})
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
req := httptest.NewRequest("POST", "/api/v1/processes/start", nil)
|
||||
// Note: no Authorization header at all.
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("PoC expected unauthenticated request to reach protected command route (200), got %d", w.Code)
|
||||
}
|
||||
t.Log("PoC: with empty AuthToken, an unauthenticated POST reaches /api/v1/processes/start")
|
||||
}
|
||||
@@ -269,6 +269,24 @@ func Load() *Config {
|
||||
return cfg
|
||||
}
|
||||
|
||||
// ListenHost returns the interface agentctl should bind its HTTP listeners to.
|
||||
//
|
||||
// When no AuthToken is configured the bearer-token middleware is a pass-through
|
||||
// (auth disabled), which would otherwise expose command/shell/process routes
|
||||
// unauthenticated. In that case we bind to loopback only so the surface is
|
||||
// never reachable beyond the local host. This does not affect the normal flow:
|
||||
// the launcher always injects AGENTCTL_BOOTSTRAP_NONCE, so a token is generated
|
||||
// and auth is enforced — including Docker, where the backend must reach agentctl
|
||||
// across the container boundary and an all-interfaces bind is required.
|
||||
//
|
||||
// An empty return means "all interfaces" (the historical ":port" form).
|
||||
func (c *Config) ListenHost() string {
|
||||
if c.AuthToken == "" {
|
||||
return "127.0.0.1"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// ConsumeNonce atomically validates and burns the bootstrap nonce.
|
||||
// Returns the auth token if the nonce matches, empty string otherwise.
|
||||
// The nonce is invalidated after a single successful call (one-shot).
|
||||
|
||||
@@ -144,3 +144,21 @@ func TestApplyOverrides_BaseBranches(t *testing.T) {
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestListenHost pins the loopback-only bind guard: when auth is disabled
|
||||
// (empty AuthToken) the server must bind loopback only; when a token is
|
||||
// configured it binds all interfaces (empty host → ":port").
|
||||
func TestListenHost(t *testing.T) {
|
||||
t.Run("no token binds loopback only", func(t *testing.T) {
|
||||
cfg := &Config{AuthToken: ""}
|
||||
if got := cfg.ListenHost(); got != "127.0.0.1" {
|
||||
t.Fatalf("ListenHost() = %q, want 127.0.0.1 when auth disabled", got)
|
||||
}
|
||||
})
|
||||
t.Run("token binds all interfaces", func(t *testing.T) {
|
||||
cfg := &Config{AuthToken: "secret"}
|
||||
if got := cfg.ListenHost(); got != "" {
|
||||
t.Fatalf("ListenHost() = %q, want \"\" (all interfaces) when auth enabled", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -176,7 +176,9 @@ func (m *Manager) allocatePortAndListener(id string) (int, net.Listener, error)
|
||||
if err != nil {
|
||||
return 0, nil, fmt.Errorf("failed to allocate port: %w", err)
|
||||
}
|
||||
ln, err := net.Listen("tcp", fmt.Sprintf(":%d", allocated))
|
||||
// Bind loopback-only when auth is disabled (no token); otherwise bind
|
||||
// all interfaces so Docker/remote executors can reach the instance.
|
||||
ln, err := net.Listen("tcp", fmt.Sprintf("%s:%d", m.config.ListenHost(), allocated))
|
||||
if err != nil {
|
||||
if errors.Is(err, syscall.EADDRINUSE) || strings.Contains(err.Error(), "address already in use") {
|
||||
m.portAlloc.MarkUnavailable(allocated)
|
||||
|
||||
@@ -362,8 +362,17 @@ func osascriptNotifyArgs(title, body string) []string {
|
||||
}
|
||||
}
|
||||
|
||||
// escapePowerShell neutralizes PowerShell double-quoted-string metacharacters
|
||||
// so an operator-supplied sound path cannot inject code into the `-c` script.
|
||||
// Inside a double-quoted string PowerShell treats the backtick as the escape
|
||||
// character and expands `$(...)` sub-expressions and `$var` references, so all
|
||||
// three must be neutralized. Order matters: the backtick is doubled first,
|
||||
// otherwise the escapes added for `$` and `"` would themselves be corrupted.
|
||||
func escapePowerShell(value string) string {
|
||||
return strings.ReplaceAll(value, `"`, "`\"")
|
||||
value = strings.ReplaceAll(value, "`", "``")
|
||||
value = strings.ReplaceAll(value, "$", "`$")
|
||||
value = strings.ReplaceAll(value, `"`, "`\"")
|
||||
return value
|
||||
}
|
||||
|
||||
func runCommand(ctx context.Context, name string, args ...string) error {
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
package providers
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// legacyEscapePowerShell reproduces the vulnerable pre-fix implementation
|
||||
// (quote-only escaping) so the PoC below can demonstrate the injection against
|
||||
// the unfixed function, mirroring how legacyBuildAppleScript documents the
|
||||
// AppleScript exploit in system_provider_test.go.
|
||||
func legacyEscapePowerShell(value string) string {
|
||||
return strings.ReplaceAll(value, `"`, "`\"")
|
||||
}
|
||||
|
||||
// TestEscapePowerShell_SubExpressionInjection_PoC demonstrates the
|
||||
// LOW-severity PowerShell sub-expression injection in playWindowsSound and
|
||||
// proves the fix closes it.
|
||||
//
|
||||
// escapePowerShell used to only backtick-escape the double-quote character; it
|
||||
// did NOT neutralize the `$(...)` sub-expression syntax, which PowerShell
|
||||
// evaluates inside a double-quoted string. Because playWindowsSound
|
||||
// interpolates the (operator-influenced) SoundFile path into a `-c` script
|
||||
// string, a `$(...)` payload in the path was evaluated as code.
|
||||
//
|
||||
// The PoC uses a live-sub-expression detector (a `$(` with no escaping backtick
|
||||
// in front) so it correctly FLIPS: it fires against the legacy escaper and is
|
||||
// silenced by the current one.
|
||||
func TestEscapePowerShell_SubExpressionInjection_PoC(t *testing.T) {
|
||||
// A sound path carrying a PowerShell sub-expression payload.
|
||||
payload := `C:\sounds\a$(Remove-Item -Recurse C:\important).wav`
|
||||
|
||||
// Legacy escaping leaves a LIVE sub-expression — the vulnerability.
|
||||
legacy := legacyEscapePowerShell(payload)
|
||||
if !hasLiveSubExpression(legacy) {
|
||||
t.Fatalf("PoC expected legacy escaper to leave a live sub-expression, got %q", legacy)
|
||||
}
|
||||
legacyScript := fmt.Sprintf(`(New-Object Media.SoundPlayer "%s").PlaySync()`, legacy)
|
||||
t.Logf("PoC (legacy): playWindowsSound would run: powershell.exe -c %s", legacyScript)
|
||||
|
||||
// The current escaper neutralizes it — the fix.
|
||||
fixed := escapePowerShell(payload)
|
||||
if hasLiveSubExpression(fixed) {
|
||||
t.Fatalf("current escaper still leaves a live sub-expression: %q", fixed)
|
||||
}
|
||||
}
|
||||
|
||||
// hasLiveSubExpression reports whether s contains a `$(` that PowerShell would
|
||||
// evaluate — i.e. a `$(` not defused by a preceding escaping backtick.
|
||||
func hasLiveSubExpression(s string) bool {
|
||||
// Remove every escaped occurrence, then look for any remaining `$(`.
|
||||
return strings.Contains(strings.ReplaceAll(s, "`$(", ""), "$(")
|
||||
}
|
||||
@@ -248,3 +248,64 @@ func TestOsascriptNotifyArgs_OptionTerminator(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestEscapePowerShell_NeutralizesSubExpression is the regression guard for the
|
||||
// PowerShell sub-expression injection fix. It asserts that escapePowerShell
|
||||
// backtick-escapes `$` (killing `$(...)` sub-expressions and `$var` expansion),
|
||||
// doubles bare backticks, and escapes `"` — so a hostile SoundFile path can no
|
||||
// longer inject code into the playWindowsSound `-c` script.
|
||||
func TestEscapePowerShell_NeutralizesSubExpression(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
input string
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "sub-expression is defused",
|
||||
input: `a$(Remove-Item C:\x).wav`,
|
||||
want: "a`$(Remove-Item C:\\x).wav",
|
||||
},
|
||||
{
|
||||
name: "variable expansion is defused",
|
||||
input: `$env:TEMP\s.wav`,
|
||||
want: "`$env:TEMP\\s.wav",
|
||||
},
|
||||
{
|
||||
name: "backtick doubled before other escapes",
|
||||
input: "a`$(x).wav",
|
||||
want: "a```$(x).wav",
|
||||
},
|
||||
{
|
||||
name: "double quote escaped",
|
||||
input: `a".wav`,
|
||||
want: "a`\".wav",
|
||||
},
|
||||
{
|
||||
name: "plain path unchanged",
|
||||
input: `C:\Users\me\sound.wav`,
|
||||
want: `C:\Users\me\sound.wav`,
|
||||
},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if got := escapePowerShell(tc.input); got != tc.want {
|
||||
t.Fatalf("escapePowerShell(%q) = %q, want %q", tc.input, got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestPlayWindowsSoundScript_NoLiveSubExpression asserts the reconstructed
|
||||
// `-c` script contains no live `$(` sub-expression once the path is escaped.
|
||||
func TestPlayWindowsSoundScript_NoLiveSubExpression(t *testing.T) {
|
||||
payload := `C:\sounds\a$(Remove-Item -Recurse C:\important).wav`
|
||||
script := fmt.Sprintf(`(New-Object Media.SoundPlayer "%s").PlaySync()`, escapePowerShell(payload))
|
||||
// A live sub-expression would appear as `$(` with no escaping backtick in
|
||||
// front. After escaping, the only `$(` occurrence must be the escaped form.
|
||||
if strings.Contains(script, "$(") && !strings.Contains(script, "`$(") {
|
||||
t.Fatalf("script still contains a live sub-expression: %q", script)
|
||||
}
|
||||
if strings.Contains(strings.ReplaceAll(script, "`$(", ""), "$(") {
|
||||
t.Fatalf("script contains an unescaped sub-expression: %q", script)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -127,7 +127,7 @@ func materializeGit(skill *models.Skill, cacheDir string) (SkillDir, error) {
|
||||
if err := runGit(repoDir, "pull", "--ff-only"); err != nil {
|
||||
return SkillDir{}, err
|
||||
}
|
||||
} else if err := runGit("", "clone", "--depth=1", skill.SourceLocator, repoDir); err != nil {
|
||||
} else if err := runGit("", gitCloneArgs(skill.SourceLocator, repoDir)...); err != nil {
|
||||
return SkillDir{}, err
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(repoDir, "SKILL.md")); err != nil {
|
||||
@@ -136,6 +136,15 @@ func materializeGit(skill *models.Skill, cacheDir string) (SkillDir, error) {
|
||||
return SkillDir{Slug: skill.Slug, Path: repoDir}, nil
|
||||
}
|
||||
|
||||
// gitCloneArgs builds the argv for the shallow skill clone. The `--`
|
||||
// end-of-options separator (matching internal/office/configloader/git.go)
|
||||
// ensures the source locator is always treated as a positional URL, never as a
|
||||
// flag — defense-in-depth in case validateGitLocator is ever relaxed enough to
|
||||
// admit a `-`-prefixed locator such as `--upload-pack=...`.
|
||||
func gitCloneArgs(locator, repoDir string) []string {
|
||||
return []string{"clone", "--depth=1", "--", locator, repoDir}
|
||||
}
|
||||
|
||||
func validateGitLocator(locator string) error {
|
||||
trimmed := strings.TrimSpace(locator)
|
||||
if trimmed == "" {
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
package skills
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestGitClone_MissingEndOfOptionsSeparator_PoC demonstrates the LOW-severity
|
||||
// defense-in-depth gap that materializeGit used to have: it invoked
|
||||
//
|
||||
// runGit("", "clone", "--depth=1", skill.SourceLocator, repoDir)
|
||||
//
|
||||
// with NO `--` end-of-options separator before the locator (the sibling
|
||||
// configloader/git.go correctly appends `"--", repoURL, wsPath`). It was
|
||||
// unreachable because validateGitLocator requires an https/ssh/git scheme or a
|
||||
// `git@host:` SCP prefix and rejects `..`, so a leading `-` couldn't get
|
||||
// through. But if that validator were ever relaxed, a locator like
|
||||
// `--upload-pack=...` would be handed to git as a FLAG rather than a positional
|
||||
// URL.
|
||||
//
|
||||
// This test contrasts the old argv (no separator) with the fixed builder
|
||||
// (gitCloneArgs, which inserts `--`) so it genuinely FLIPS: the unsafe shape
|
||||
// lacks `--`, the fixed shape has it before the locator.
|
||||
func TestGitClone_MissingEndOfOptionsSeparator_PoC(t *testing.T) {
|
||||
// A hostile locator that only matters if validateGitLocator were relaxed.
|
||||
locator := "--upload-pack=touch /tmp/pwned;"
|
||||
repoDir := "/cache/git/deadbeef"
|
||||
|
||||
// The argv materializeGit used to pass to runGit — no `--` guard.
|
||||
unsafe := []string{"clone", "--depth=1", locator, repoDir}
|
||||
if slices.Index(unsafe, "--") != -1 {
|
||||
t.Fatalf("PoC expected the pre-fix argv to omit the -- separator, got %v", unsafe)
|
||||
}
|
||||
// In the unsafe argv the locator sits in option position (right after
|
||||
// --depth=1) with nothing telling git to stop parsing flags.
|
||||
if got := slices.Index(unsafe, locator); got != 2 {
|
||||
t.Fatalf("PoC expected locator in flag position (index 2), got %d in %v", got, unsafe)
|
||||
}
|
||||
|
||||
// The fixed builder places `--` immediately before the locator.
|
||||
fixed := gitCloneArgs(locator, repoDir)
|
||||
sep := slices.Index(fixed, "--")
|
||||
if sep == -1 || fixed[sep+1] != locator {
|
||||
t.Fatalf("PoC expected fixed argv to guard the locator with --, got %v", fixed)
|
||||
}
|
||||
t.Logf("PoC: pre-fix argv %v parses %q as a git flag; fixed argv %v does not", unsafe, locator, fixed)
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"github.com/kandev/kandev/internal/office/models"
|
||||
@@ -115,6 +116,31 @@ func TestValidateLocalPathUnderRoot_EmptyRootSkipsGuard(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestGitCloneArgs_HasEndOfOptionsSeparator is the regression guard for the
|
||||
// missing `--` fix: the clone argv must place `--` immediately before the
|
||||
// source locator so a `-`-prefixed locator can never be parsed as a git flag.
|
||||
func TestGitCloneArgs_HasEndOfOptionsSeparator(t *testing.T) {
|
||||
locator := "https://github.com/user/repo.git"
|
||||
repoDir := "/cache/git/deadbeef"
|
||||
args := gitCloneArgs(locator, repoDir)
|
||||
|
||||
sep := slices.Index(args, "--")
|
||||
loc := slices.Index(args, locator)
|
||||
if sep == -1 {
|
||||
t.Fatalf("expected -- separator in clone args, got %v", args)
|
||||
}
|
||||
if loc == -1 {
|
||||
t.Fatalf("expected locator in clone args, got %v", args)
|
||||
}
|
||||
if sep >= loc {
|
||||
t.Fatalf("expected -- (index %d) to precede locator (index %d) in %v", sep, loc, args)
|
||||
}
|
||||
// The locator must be the argument directly after `--`.
|
||||
if args[sep+1] != locator {
|
||||
t.Fatalf("expected locator directly after --, got %q in %v", args[sep+1], args)
|
||||
}
|
||||
}
|
||||
|
||||
func runGitCmd(t *testing.T, dir string, args ...string) {
|
||||
t.Helper()
|
||||
cmd := exec.CommandContext(context.Background(), "git", args...)
|
||||
|
||||
Reference in New Issue
Block a user