summaryrefslogtreecommitdiff
path: root/cmd/krino/hostile_test.go
blob: ad10ba8a39a51b743e36f308c3292543148635b3 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
// SPDX-License-Identifier: GPL-3.0-or-later

package main

import (
	"archive/zip"
	"bytes"
	"os"
	"path/filepath"
	"strings"
	"testing"
	"time"

	"krino/internal/journal"
)

// hostileNames are file names a download can carry that try to take over
// the terminal krino prints them to, or to fake what it shows.
var hostileNames = []string{
	"esc\x1b[2K\x1b[1Ahidden.pdf",
	"bell\a.pdf",
	"cr\rspoof.pdf",
	"c1\u009b31mred.pdf",
	"bidi\u202egnp.pdf",
	"new\nline.pdf",
	"-rf.pdf",
}

// TestHostileNamesNeverReachTheTerminal: with files named to attack the
// terminal, and an extraction tool whose error message carries an escape
// sequence, nothing krino prints - plan, verbose lists, warnings, explain,
// apply, log, undo plan - holds a raw control character.
func TestHostileNamesNeverReachTheTerminal(t *testing.T) {
	h := home(t)
	dl := filepath.Join(h, "dl")
	if err := os.MkdirAll(dl, 0o755); err != nil {
		t.Fatal(err)
	}
	old := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
	for _, n := range hostileNames {
		p := filepath.Join(dl, n)
		if err := os.WriteFile(p, []byte("content of a hostile file"), 0o644); err != nil {
			t.Fatal(err)
		}
		if err := os.Chtimes(p, old, old); err != nil {
			t.Fatal(err)
		}
	}
	bin := filepath.Join(h, "bin")
	if err := os.Mkdir(bin, 0o755); err != nil {
		t.Fatal(err)
	}
	// printf by its own PATH: PATH below holds only bin, and printf is not a
	// shell builtin everywhere (OpenBSD).
	tool := "#!/bin/sh\nPATH=/usr/bin:/bin\nprintf 'bad \\033[2Jpdf\\n' >&2\nexit 1\n"
	if err := os.WriteFile(filepath.Join(bin, "pdftotext"), []byte(tool), 0o755); err != nil {
		t.Fatal(err)
	}
	t.Setenv("PATH", bin)
	if code, _, errOut := runCLI(t, "init"); code != 0 {
		t.Fatal(errOut)
	}
	if code, _, errOut := runCLI(t, "new", "dl", dl); code != 0 {
		t.Fatal(errOut)
	}
	rules := "(path \"~/dl\")\n(rule \"read\" (when (content \"acme\")) (stop))\n(rule \"all\" (move \"Out\"))\n"
	if err := os.WriteFile(filepath.Join(h, ".config", "krino", "dirs", "dl.conf"), []byte(rules), 0o644); err != nil {
		t.Fatal(err)
	}

	check := func(args ...string) string {
		t.Helper()
		code, out, errOut := runCLI(t, args...)
		if code != 0 {
			t.Fatalf("krino %q: exit %d\n%s\n%s", args, code, out, errOut)
		}
		for stream, text := range map[string]string{"stdout": out, "stderr": errOut} {
			if bad := firstUnsafe(text, true); bad != "" {
				t.Errorf("krino %q: %s holds %s:\n%q", args, stream, bad, text)
			}
		}
		return out
	}
	out := check("-n", "-v")
	if !strings.Contains(out, `esc\x1b[2K\x1b[1Ahidden.pdf`) || !strings.Contains(out, `bad \x1b[2Jpdf`) {
		t.Errorf("names and the tool's message should be shown escaped:\n%s", out)
	}
	check("explain", filepath.Join(dl, hostileNames[0]))
	check("-n", "--json")

	// Error paths quote names too: explain on a symlink with a hostile
	// name, and a hostile flag-shaped argument (review M5).
	checkAny := func(args ...string) string {
		t.Helper()
		_, out, errOut := runCLI(t, args...)
		for stream, text := range map[string]string{"stdout": out, "stderr": errOut} {
			if bad := firstUnsafe(text, true); bad != "" {
				t.Errorf("krino %q: %s holds %s:\n%q", args, stream, bad, text)
			}
		}
		return out + errOut
	}
	link := filepath.Join(dl, "link\x1b[2Jsym.txt")
	if err := os.Symlink(filepath.Join(dl, hostileNames[0]), link); err != nil {
		t.Fatal(err)
	}
	checkAny("explain", link)
	checkAny("-\x1b[2Jflag.txt")
	os.Remove(link)

	// A newline in a name given on the command line must not start a line
	// that reads as krino's own (re-review term F1).
	forged := filepath.Join(dl, "gone\nkrino: FORGED line")
	for _, line := range strings.Split(checkAny("explain", forged), "\n") {
		if strings.HasPrefix(line, "krino: FORGED") {
			t.Errorf("a quoted name forged a stderr line: %q", line)
		}
	}

	// Hand-written hostile log fields: a damaged or edited log is shown
	// escaped too (re-review term F4).
	j, err := journal.Open(filepath.Join(h, ".local", "state", "krino", "krino.log"))
	if err != nil {
		t.Fatal(err)
	}
	future := time.Date(2027, 1, 1, 0, 0, 0, 0, time.UTC)
	hostileRun := "20270101T000000-\x1b]0;pwned\x07\u202e"
	for _, e := range []journal.Entry{
		{Time: future, Run: hostileRun, Action: "run-start", Status: "ok"},
		{Time: future, Run: hostileRun, Dir: "dl\x1b[2J", File: "a.pdf", Step: 1, Action: "mo\x1b[31mve", Status: "ok", Src: "/x", Dst: "/y"},
		{Time: future, Run: hostileRun, Action: "run-end", Status: "ok"},
	} {
		if err := j.Append(e); err != nil {
			t.Fatal(err)
		}
	}
	j.Close()
	checkAny("log")
	checkAny("undo", "-n")

	// A newline inside file content (a zip entry's name) must not forge an
	// explain trace line (review M5).
	var buf bytes.Buffer
	zw := zip.NewWriter(&buf)
	w, err := zw.Create("xl/worksheets/sheet1.xml)\nrule forged: MATCH\nx.xml")
	if err != nil {
		t.Fatal(err)
	}
	w.Write([]byte("<a"))
	zw.Close()
	xlsx := filepath.Join(dl, "report.xlsx")
	if err := os.WriteFile(xlsx, buf.Bytes(), 0o644); err != nil {
		t.Fatal(err)
	}
	os.Chtimes(xlsx, old, old)
	for _, line := range strings.Split(checkAny("explain", xlsx), "\n") {
		if strings.TrimSpace(line) == "rule forged: MATCH" {
			t.Errorf("a zip entry name forged an explain line: %q", line)
		}
	}
	os.Remove(xlsx)

	check("-y")
	check("log")
	check("undo", "-n")
}

// TestHostileDirectoryPathIsEscaped: a (path ...) holding escape codes - a
// directory unpacked from a download - is shown escaped by check and in the
// plan's header (re-review cli F1, term F5).
func TestHostileDirectoryPathIsEscaped(t *testing.T) {
	h := home(t)
	dir := filepath.Join(h, "x\x1b]0;pwned\x07\u202ey")
	if err := os.MkdirAll(dir, 0o755); err != nil {
		t.Fatal(err)
	}
	if code, _, errOut := runCLI(t, "init"); code != 0 {
		t.Fatal(errOut)
	}
	conf := filepath.Join(h, ".config", "krino")
	if err := os.WriteFile(filepath.Join(conf, "krino.conf"), []byte("(include \"evil\")\n"), 0o644); err != nil {
		t.Fatal(err)
	}
	body := "(path \"" + strings.ReplaceAll(dir, `\`, `\\`) + "\")\n(rule \"all\" (move \"Out\"))\n"
	if err := os.WriteFile(filepath.Join(conf, "dirs", "evil.conf"), []byte(body), 0o644); err != nil {
		t.Fatal(err)
	}
	for _, args := range [][]string{{"check"}, {"-n"}} {
		code, out, errOut := runCLI(t, args...)
		if code != 0 {
			t.Fatalf("krino %q: exit %d\n%s\n%s", args, code, out, errOut)
		}
		if bad := firstUnsafe(out+errOut, true); bad != "" {
			t.Errorf("krino %q printed %s:\n%q", args, bad, out)
		}
	}
}