Ver Fonte

fix(agent): verify AdGuard artifacts and tar contents (#1621)

Require a SHA-256 digest for every download op and verify it with sha256sum before the artifact is used. AdGuard binary plans embed the official v0.107.62 checksums per Linux suffix.

List tar entries and types before extracting and reject absolute paths, parent traversal, symlinks, hard links and device nodes.

Closes #1619
Nacho há 1 mês atrás
pai
commit
290d497640

+ 72 - 6
agent/executor/executor.go

@@ -99,6 +99,7 @@ var (
 	// Allowlist de dominios de descarga: SOLO releases oficiales de AdGuard.
 	// Cualquier otra URL (incluida un attacker que controle el plan) se rechaza.
 	reDownloadURL = regexp.MustCompile(`^https://github\.com/AdguardTeam/AdGuardHome/releases/download/v[0-9]+\.[0-9]+\.[0-9]+/AdGuardHome_linux_[a-z0-9]+\.tar\.gz$`)
+	reSHA256      = regexp.MustCompile(`^[0-9a-fA-F]{64}$`)
 	reMode        = regexp.MustCompile(`^[0-7]{3,4}$`)
 	// base64 estándar (sin newlines). La validación final la hace base64.Decode.
 	reBase64 = regexp.MustCompile(`^[A-Za-z0-9+/]+={0,2}$`)
@@ -115,6 +116,8 @@ var (
 type opSpec struct {
 	required map[string]*regexp.Regexp
 	build    func(args map[string]string) (cmd string, cmdArgs []string)
+	pre      func(run Runner, args map[string]string) int
+	post     func(run Runner, args map[string]string) int
 	// exec, si está presente, reemplaza a build. Para Kinds que no son un
 	// simple exec.Command (p. ej. write_file escribe el fichero en Go).
 	exec func(run Runner, args map[string]string) int
@@ -252,11 +255,22 @@ var allowlist = map[string]opSpec{
 	// estricta de URL (solo releases oficiales de AdGuard).  El dest se valida
 	// con reFilePath. No shell libre: la URL va como arg, no interpolada.
 	"download": {
-		required: map[string]*regexp.Regexp{"url": reDownloadURL, "dest": reFilePath},
+		required: map[string]*regexp.Regexp{"url": reDownloadURL, "dest": reFilePath, "sha256": reSHA256},
 		pathArgs: []string{"dest"},
 		build: func(a map[string]string) (string, []string) {
 			return "uclient-fetch", []string{a["url"], "-O", a["dest"]}
 		},
+		post: func(run Runner, a map[string]string) int {
+			out, code := run.Run("sha256sum", a["dest"])
+			if code != 0 {
+				return code
+			}
+			fields := strings.Fields(strings.TrimSpace(out))
+			if len(fields) == 0 || !strings.EqualFold(fields[0], a["sha256"]) {
+				return 1
+			}
+			return 0
+		},
 		configs: func(a map[string]string) []string { return nil },
 	},
 	// write_file: escribe contenido base64 a path. Se hace en Go (no shell)
@@ -303,6 +317,17 @@ var allowlist = map[string]opSpec{
 	"extract_tarball": {
 		required: map[string]*regexp.Regexp{"src": reFilePath, "dest": reDirPath},
 		pathArgs: []string{"src", "dest"},
+		pre: func(run Runner, a map[string]string) int {
+			names, code := run.Run("tar", "-tzf", a["src"])
+			if code != 0 || unsafeTarNames(names) {
+				return 1
+			}
+			verbose, code := run.Run("tar", "-tvzf", a["src"])
+			if code != 0 || unsafeTarTypes(verbose) {
+				return 1
+			}
+			return 0
+		},
 		build: func(a map[string]string) (string, []string) {
 			return "tar", []string{"-xzf", a["src"], "-C", a["dest"]}
 		},
@@ -440,6 +465,39 @@ func (e *Executor) SetRunner(r Runner) { e.run = r }
 func (e *Executor) SetClock(f func() time.Time) { e.now = f }
 
 // Validate comprueba que una Op pasa el allowlist sin ejecutarla.
+func unsafeTarNames(out string) bool {
+	for _, line := range strings.Split(out, "\n") {
+		name := strings.TrimSpace(line)
+		if name == "" {
+			continue
+		}
+		if filepath.IsAbs(name) {
+			return true
+		}
+		for _, part := range strings.FieldsFunc(name, func(r rune) bool { return r == '/' || r == '\\' }) {
+			if part == ".." {
+				return true
+			}
+		}
+	}
+	return false
+}
+
+func unsafeTarTypes(out string) bool {
+	for _, line := range strings.Split(out, "\n") {
+		line = strings.TrimSpace(line)
+		if line == "" {
+			continue
+		}
+		switch line[0] {
+		case '-', 'd':
+		default:
+			return true
+		}
+	}
+	return false
+}
+
 func Validate(op Op) error {
 	spec, ok := allowlist[op.Kind]
 	if !ok {
@@ -564,11 +622,19 @@ func (e *Executor) Apply(ops []Op) ApplyResult {
 
 		spec := allowlist[op.Kind]
 		var code int
-		if spec.exec != nil {
-			code = spec.exec(e.run, op.Args)
-		} else {
-			cmd, cmdArgs := spec.build(op.Args)
-			_, code = e.run.Run(cmd, cmdArgs...)
+		if spec.pre != nil {
+			code = spec.pre(e.run, op.Args)
+		}
+		if code == 0 {
+			if spec.exec != nil {
+				code = spec.exec(e.run, op.Args)
+			} else {
+				cmd, cmdArgs := spec.build(op.Args)
+				_, code = e.run.Run(cmd, cmdArgs...)
+			}
+		}
+		if code == 0 && spec.post != nil {
+			code = spec.post(e.run, op.Args)
 		}
 		if code != 0 {
 			if op.Kind == "wg_check" || op.Kind == "dawn_check" || op.Kind == "usteer_check" {

+ 102 - 4
agent/executor/executor_test.go

@@ -179,12 +179,28 @@ func TestValidateSectionWithDigits(t *testing.T) {
 func TestValidateDownloadURLAllowlist(t *testing.T) {
 	// URL oficial válida
 	valid := Op{Kind: "download", Args: map[string]string{
-		"url":  "https://github.com/AdguardTeam/AdGuardHome/releases/download/v0.107.52/AdGuardHome_linux_arm64.tar.gz",
-		"dest": "/tmp/AdGuardHome.tar.gz",
+		"url":    "https://github.com/AdguardTeam/AdGuardHome/releases/download/v0.107.52/AdGuardHome_linux_arm64.tar.gz",
+		"dest":   "/tmp/AdGuardHome.tar.gz",
+		"sha256": strings.Repeat("a", 64),
 	}}
 	if err := Validate(valid); err != nil {
 		t.Fatalf("valid download URL rejected: %v", err)
 	}
+	missingSum := Op{Kind: "download", Args: map[string]string{
+		"url":  "https://github.com/AdguardTeam/AdGuardHome/releases/download/v0.107.52/AdGuardHome_linux_arm64.tar.gz",
+		"dest": "/tmp/AdGuardHome.tar.gz",
+	}}
+	if err := Validate(missingSum); err == nil {
+		t.Fatal("download without sha256 should be rejected")
+	}
+	badSum := Op{Kind: "download", Args: map[string]string{
+		"url":    "https://github.com/AdguardTeam/AdGuardHome/releases/download/v0.107.52/AdGuardHome_linux_arm64.tar.gz",
+		"dest":   "/tmp/AdGuardHome.tar.gz",
+		"sha256": "no-es-un-sha",
+	}}
+	if err := Validate(badSum); err == nil {
+		t.Fatal("download with malformed sha256 should be rejected")
+	}
 	// URL maliciosa (dominio distinto) → rechazo
 	bad := Op{Kind: "download", Args: map[string]string{
 		"url":  "https://evil.example.com/AdGuardHome.tar.gz",
@@ -363,12 +379,15 @@ func TestApplyPlanConDownloadWriteChmod(t *testing.T) {
 	// (escribe de verdad en /tmp). service via fakeRunner.
 	tmpFile := "/tmp/netpulse-plan-test-" + t.Name()
 	defer os.Remove(tmpFile)
+	sha := strings.Repeat("b", 64)
+	fr.outputs["sha256sum"] = sha + "  " + tmpFile
 
 	e := &Executor{run: fr, now: time.Now, gwTarget: "192.168.1.1"}
 	ops := []Op{
 		{Kind: "download", Args: map[string]string{
-			"url":  "https://github.com/AdguardTeam/AdGuardHome/releases/download/v0.107.52/AdGuardHome_linux_arm64.tar.gz",
-			"dest": tmpFile,
+			"url":    "https://github.com/AdguardTeam/AdGuardHome/releases/download/v0.107.52/AdGuardHome_linux_arm64.tar.gz",
+			"dest":   tmpFile,
+			"sha256": sha,
 		}, Desc: "Download AdGuard tarball"},
 		{Kind: "write_file", Args: map[string]string{
 			"path":        "/tmp/netpulse-plan-test-cfg.yaml",
@@ -396,6 +415,85 @@ func TestApplyPlanConDownloadWriteChmod(t *testing.T) {
 	}
 }
 
+func TestApplyDownloadChecksumMismatch(t *testing.T) {
+	fr := newFakeRunner()
+	fr.outputs["sha256sum"] = strings.Repeat("c", 64) + "  /tmp/netpulse-plan-test-download"
+	e := &Executor{run: fr, now: time.Now, gwTarget: "192.168.1.1"}
+	res := e.Apply([]Op{{
+		Kind: "download",
+		Args: map[string]string{
+			"url":    "https://github.com/AdguardTeam/AdGuardHome/releases/download/v0.107.52/AdGuardHome_linux_arm64.tar.gz",
+			"dest":   "/tmp/netpulse-plan-test-download",
+			"sha256": strings.Repeat("d", 64),
+		},
+		Desc: "Download with wrong digest",
+	}})
+	if res.Status != "failed" {
+		t.Fatalf("expected failed, got %s", res.Status)
+	}
+}
+
+func TestUnsafeTarNames(t *testing.T) {
+	for _, name := range []string{"../etc/passwd", "/etc/passwd", `a\..\b`, "a/../../b"} {
+		if !unsafeTarNames(name) {
+			t.Errorf("unsafe name accepted: %q", name)
+		}
+	}
+	for _, name := range []string{"AdGuardHome/AdGuardHome", "dir/file", ""} {
+		if unsafeTarNames(name) {
+			t.Errorf("safe name rejected: %q", name)
+		}
+	}
+}
+
+func TestUnsafeTarTypes(t *testing.T) {
+	for _, line := range []string{"lrwxrwxrwx 0 0 0 0 Jan 1 00:00 link", "hrw-r--r-- 0 0 0 0 Jan 1 00:00 hard", "brw-r--r-- 0 0 0 0 Jan 1 00:00 dev"} {
+		if !unsafeTarTypes(line) {
+			t.Errorf("unsafe tar type accepted: %q", line)
+		}
+	}
+	for _, line := range []string{"-rw-r--r-- 0 0 0 0 Jan 1 00:00 file", "drwxr-xr-x 0 0 0 0 Jan 1 00:00 dir"} {
+		if unsafeTarTypes(line) {
+			t.Errorf("safe tar type rejected: %q", line)
+		}
+	}
+}
+
+func TestApplyExtractRejectsUnsafeTarNames(t *testing.T) {
+	fr := newFakeRunner()
+	fr.outputs["tar -tzf"] = "../escape\n"
+	e := &Executor{run: fr, now: time.Now, gwTarget: "192.168.1.1"}
+	res := e.Apply([]Op{{
+		Kind: "extract_tarball",
+		Args: map[string]string{"src": "/tmp/netpulse-extract-test.tar.gz", "dest": "/tmp/netpulse-extract-test"},
+		Desc: "Extract unsafe tarball",
+	}})
+	if res.Status != "failed" {
+		t.Fatalf("expected failed, got %s", res.Status)
+	}
+	if strings.Contains(strings.Join(fr.calls, "\n"), "tar -xzf") {
+		t.Fatal("unsafe tarball must not be extracted")
+	}
+}
+
+func TestApplyExtractRejectsUnsafeTarTypes(t *testing.T) {
+	fr := newFakeRunner()
+	fr.outputs["tar -tzf"] = "ok\n"
+	fr.outputs["tar -tvzf"] = "lrwxrwxrwx 0 0 0 0 Jan 1 00:00 link\n"
+	e := &Executor{run: fr, now: time.Now, gwTarget: "192.168.1.1"}
+	res := e.Apply([]Op{{
+		Kind: "extract_tarball",
+		Args: map[string]string{"src": "/tmp/netpulse-extract-test.tar.gz", "dest": "/tmp/netpulse-extract-test"},
+		Desc: "Extract symlink tarball",
+	}})
+	if res.Status != "failed" {
+		t.Fatalf("expected failed, got %s", res.Status)
+	}
+	if strings.Contains(strings.Join(fr.calls, "\n"), "tar -xzf") {
+		t.Fatal("tarball with symlink must not be extracted")
+	}
+}
+
 func TestApplySuccess(t *testing.T) {
 	fr := newFakeRunner()
 	e := &Executor{run: fr, now: time.Now, gwTarget: "192.168.1.1"}

+ 30 - 1
server-go/internal/orchestr/modules.go

@@ -122,6 +122,35 @@ func adGuardDisableOps() []executor.Op {
 //
 // La estructura del tarball oficial es `AdGuardHome/AdGuardHome` (binario) +
 // README/LICENSE/homepage; por eso se extrae a /tmp y se mueve solo el binario.
+func adguardSHA256(suffix string) string {
+	switch suffix {
+	case "386":
+		return "617958e1423e300fe199bccce610c95d589ba1511dc2ffacfb9336146c1d39b6"
+	case "amd64":
+		return "b07c392732ac63c4f79eb374cacec002be4bd9105a47dced0c5c41d8e34e3ade"
+	case "arm64":
+		return "98404a4ab26c71a59d5b7fc9d24c061cd5d4439a77822cfb73909f8e39fefd46"
+	case "armv5":
+		return "382f02fc746d67dc5d3ec1d172e22185b30bd9f6a1b7fa836e12e16683a5c47f"
+	case "armv6":
+		return "5df2b92f9c3869d93310f8ab19f7eee8988f510f3e5cecd239c8fe7bbb442ac8"
+	case "armv7":
+		return "aac52acd7932297f6120f999ea70bd49fefc3c22c7c461d734c5248edf35878c"
+	case "mips":
+		return "e2332387d2d8e5df4f9da3fe4321e067f781aba63eb31790e38cc29d223f6900"
+	case "mipsle":
+		return "9ab35c8d04167fc473d5b81df5b69f5be91a56652b4445e76755a07c6ab5a8e3"
+	case "mips64":
+		return "29e72436c015f8c5f6acbefb070ffb275cbd02c2f986426abb797ef54707be9f"
+	case "mips64le":
+		return "4edefe4eb49ef1a88e72c7845482a38ee1b400dd69875b3972ca38b9c075c6b4"
+	case "ppc64le":
+		return "9ec1a95db8d7ca43e0fccfb826e8706059898791ef16a6c3ccdf2b620cb0b2d2"
+	default:
+		return ""
+	}
+}
+
 func adGuardBinaryOps(sc AdGuardScenario, port, dns string) []executor.Op {
 	suffix := sc.AdguardSuffix
 	if suffix == "" {
@@ -130,7 +159,7 @@ func adGuardBinaryOps(sc AdGuardScenario, port, dns string) []executor.Op {
 	url := fmt.Sprintf("https://github.com/AdguardTeam/AdGuardHome/releases/download/%s/AdGuardHome_linux_%s.tar.gz", adguardVersion, suffix)
 	config := fmt.Sprintf(adGuardConfigTemplate, port, dns)
 	return []executor.Op{
-		{Kind: "download", Args: map[string]string{"url": url, "dest": "/tmp/AdGuardHome.tar.gz"}, Desc: "Download AdGuard Home " + adguardVersion + " (" + suffix + ")"},
+		{Kind: "download", Args: map[string]string{"url": url, "dest": "/tmp/AdGuardHome.tar.gz", "sha256": adguardSHA256(suffix)}, Desc: "Download AdGuard Home " + adguardVersion + " (" + suffix + ")"},
 		{Kind: "extract_tarball", Args: map[string]string{"src": "/tmp/AdGuardHome.tar.gz", "dest": "/tmp/agh-inst"}, Desc: "Extract tarball to /tmp/agh-inst"},
 		{Kind: "mv", Args: map[string]string{"src": "/tmp/agh-inst/AdGuardHome/AdGuardHome", "dest": "/usr/bin/AdGuardHome"}, Desc: "Install AdGuardHome binary to /usr/bin"},
 		{Kind: "chmod", Args: map[string]string{"mode": "0755", "path": "/usr/bin/AdGuardHome"}, Desc: "Make binary executable"},