Skip to content

The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu

Harden rule pack extraction and install against path traversal

Justin D'Souza2cdbef2b34dd
diff --git a/cli/beacon/cmd/rules.go b/cli/beacon/cmd/rules.go
index 37210d88..e2de48ec 100644
--- a/cli/beacon/cmd/rules.go
+++ b/cli/beacon/cmd/rules.go
@@ -172,10 +172,7 @@ func extractRuleTarball(r io.Reader, dir string) error {
return fmt.Errorf("gzip: %w", err)
}
defer gz.Close()
- dirAbs, err := filepath.Abs(dir)
- if err != nil {
- return fmt.Errorf("resolve destination dir: %w", err)
- }
+ cleanDir := filepath.Clean(dir)
tr := tar.NewReader(gz)
count := 0
for {
@@ -189,16 +186,12 @@ func extractRuleTarball(r io.Reader, dir string) error {
if hdr.Typeflag != tar.TypeReg || !strings.HasSuffix(hdr.Name, ".rule.yaml") {
continue
}
- // Flatten to the base name (archive directory structure is ignored) and confirm
- // the resolved destination stays inside dir before writing — defense in depth
- // against archive path traversal ("Zip Slip").
- name := filepath.Base(filepath.ToSlash(hdr.Name))
- dest := filepath.Join(dir, name)
- destAbs, err := filepath.Abs(dest)
- if err != nil {
- return fmt.Errorf("resolve destination path: %w", err)
- }
- if destAbs != dirAbs && !strings.HasPrefix(destAbs, dirAbs+string(os.PathSeparator)) {
+ // Flatten archive directory structure to a base name, then confirm the joined
+ // destination stays within cleanDir before any file operation. The same `dest`
+ // value is both validated and written, guarding against archive path traversal
+ // ("Zip Slip").
+ dest := filepath.Join(cleanDir, filepath.Base(filepath.ToSlash(hdr.Name)))
+ if dest != cleanDir && !strings.HasPrefix(dest, cleanDir+string(os.PathSeparator)) {
return fmt.Errorf("archive entry %q resolves outside the destination directory", hdr.Name)
}
if err := writeReaderToFile(io.LimitReader(tr, 1<<20), dest); err != nil {
diff --git a/cli/beacon/cmd/scan.go b/cli/beacon/cmd/scan.go
index 4ea53bd2..a9e82cf2 100644
--- a/cli/beacon/cmd/scan.go
+++ b/cli/beacon/cmd/scan.go
@@ -110,6 +110,13 @@ func runScan(cmd *cobra.Command, args []string) error {
if err != nil {
return fmt.Errorf("scan: %w", err)
}
+ // The --fail-on gate is a CI signal that must reflect every detection in the
+ // scan, so count it before --min-severity (a display-only filter) drops
+ // findings from the output slice.
+ failCount := 0
+ if failRank >= 0 {
+ failCount = countAtOrAbove(findings, failRank)
+ }
if minRank > 0 {
findings = filterBySeverity(findings, minRank)
}
@@ -136,12 +143,8 @@ func runScan(cmd *cobra.Command, args []string) error {
printFindings(cmd, findings, len(events), runtimeLog.EffectiveLogPath)
}
- if failRank >= 0 {
- for _, f := range findings {
- if severityRank[f.Severity] >= failRank {
- return fmt.Errorf("scan found %d finding(s) at or above %q", countAtOrAbove(findings, failRank), scanOpts.failOn)
- }
- }
+ if failRank >= 0 && failCount > 0 {
+ return fmt.Errorf("scan found %d finding(s) at or above %q", failCount, scanOpts.failOn)
}
return nil
}
diff --git a/cli/beacon/cmd/scan_test.go b/cli/beacon/cmd/scan_test.go
index 605f2cb0..c35b2745 100644
--- a/cli/beacon/cmd/scan_test.go
+++ b/cli/beacon/cmd/scan_test.go
@@ -122,6 +122,26 @@ func TestScanFailOn(t *testing.T) {
}
}
+// TestScanFailOnIgnoresMinSeverityFilter guards the CI gate: --min-severity is a
+// display-only filter, so a detection at or above --fail-on must still fail the
+// scan even when --min-severity hides it from the printed output.
+func TestScanFailOnIgnoresMinSeverityFilter(t *testing.T) {
+ scanFixture(t, []string{evSecretRead})
+ scanOpts.minSeverity = "critical" // high finding filtered out of output
+ scanOpts.failOn = "high" // ...but still meets the fail gate
+ cmd, buf := newCmd()
+ err := runScan(cmd, nil)
+ if err == nil {
+ t.Fatalf("expected non-zero exit: a high finding meets --fail-on high even when --min-severity critical hides it; output:\n%s", buf.String())
+ }
+ if !strings.Contains(err.Error(), "1 finding") {
+ t.Fatalf("expected fail gate to count the filtered finding, got: %v", err)
+ }
+ if !strings.Contains(buf.String(), "No findings") {
+ t.Fatalf("expected the high finding hidden from output by --min-severity critical, got:\n%s", buf.String())
+ }
+}
+
func TestScanMinSeverityFilters(t *testing.T) {
scanFixture(t, []string{evSecretRead})
scanOpts.minSeverity = "critical" // finding is high -> filtered out
diff --git a/cli/beacon/internal/endpoint/detect/detect.go b/cli/beacon/internal/endpoint/detect/detect.go
index e522f653..95571d13 100644
--- a/cli/beacon/internal/endpoint/detect/detect.go
+++ b/cli/beacon/internal/endpoint/detect/detect.go
@@ -198,6 +198,11 @@ func InstallFiles(userMode bool, src string, force bool) ([]Installed, error) {
return nil, fmt.Errorf("%s: fixture %s", p, res.String())
}
}
+ // rule.ID passed CheckRule (id-grammar) above; re-assert it explicitly so the
+ // store path join below can never be driven outside the store by rule content.
+ if !threatrules.ValidID(rule.ID) {
+ return nil, fmt.Errorf("%s: invalid rule id %q", p, rule.ID)
+ }
if (existing[rule.ID] || staged[rule.ID]) && !force {
return nil, fmt.Errorf("rule %q already installed (use --force to overwrite)", rule.ID)
}
@@ -215,8 +220,13 @@ func InstallFiles(userMode bool, src string, force bool) ([]Installed, error) {
return installed, nil
}
-// Remove deletes a rule by id from the store. Returns the removed path.
+// Remove deletes a rule by id from the store. Returns the removed path. The id
+// is validated against the rule-id grammar before use so it can never contain
+// path separators or ".." segments that would resolve outside the store.
func Remove(userMode bool, id string) (string, error) {
+ if !threatrules.ValidID(id) {
+ return "", fmt.Errorf("invalid rule id %q", id)
+ }
path := filepath.Join(StoreDir(userMode), id+ruleFileSuffix)
if err := os.Remove(path); err != nil {
if os.IsNotExist(err) {
diff --git a/cli/beacon/internal/endpoint/detect/detect_test.go b/cli/beacon/internal/endpoint/detect/detect_test.go
index d7329eda..353d42c8 100644
--- a/cli/beacon/internal/endpoint/detect/detect_test.go
+++ b/cli/beacon/internal/endpoint/detect/detect_test.go
@@ -150,6 +150,32 @@ func TestRemove(t *testing.T) {
}
}
+func TestRemoveRejectsPathTraversal(t *testing.T) {
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+
+ // A rule file outside the store that a traversal id could resolve to.
+ victimDir := t.TempDir()
+ victim := filepath.Join(victimDir, "victim.rule.yaml")
+ if err := os.WriteFile(victim, []byte("id: victim\n"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+
+ // id crafted so id+suffix == "<victimDir>/victim.rule.yaml" after Join+Clean.
+ rel, err := filepath.Rel(StoreDir(true), filepath.Join(victimDir, "victim"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, id := range []string{rel, "../../etc/passwd", "a/b", "."} {
+ if _, err := Remove(true, id); err == nil {
+ t.Fatalf("expected Remove to reject unsafe id %q", id)
+ }
+ }
+ if _, err := os.Stat(victim); err != nil {
+ t.Fatalf("victim file must not be deleted: %v", err)
+ }
+}
+
func srcOf(l []LoadedRule) []Source {
s := make([]Source, len(l))
for i := range l {
diff --git a/pkg/asymptoteobserve/threatrules/rule.go b/pkg/asymptoteobserve/threatrules/rule.go
index 684f2df3..2fe0cdfc 100644
--- a/pkg/asymptoteobserve/threatrules/rule.go
+++ b/pkg/asymptoteobserve/threatrules/rule.go
@@ -21,6 +21,11 @@ import (
// idPattern constrains rule ids to a stable kebab slug.
var idPattern = regexp.MustCompile(`^[a-z0-9][a-z0-9-]*$`)
+// ValidID reports whether id is a well-formed rule id. The pattern admits no
+// path separators or "." segments, so a valid id is always a safe single
+// filename component when joined with the store directory.
+func ValidID(id string) bool { return idPattern.MatchString(id) }
+
// Status is a rule's maturity level; it drives the conformance gates (see lint.go).
type Status string