Debian Codegraph @

worktree_fs_test.go

raw
1 package git
2
3 import (
4 "bytes"
5 "fmt"
6 "os"
7 "path/filepath"
8 "sort"
9 "strings"
10 "testing"
11
12 billy "github.com/go-git/go-billy/v5"
13 "github.com/go-git/go-billy/v5/memfs"
14 "github.com/go-git/go-billy/v5/osfs"
15 "github.com/go-git/go-billy/v5/util"
16 "github.com/stretchr/testify/assert"
17 "github.com/stretchr/testify/require"
18
19 "github.com/go-git/go-git/v5/plumbing"
20 "github.com/go-git/go-git/v5/plumbing/filemode"
21 "github.com/go-git/go-git/v5/plumbing/object"
22 "github.com/go-git/go-git/v5/plumbing/storer"
23 )
24
25 // TestForceCheckoutReplacesLeadingSymlink covers the symlink-mask bypass
26 // (CVE-2021-21300 class). A symlink "s" pointing at a dangerous directory
27 // is present in the worktree, planted by an attacker or left by an earlier
28 // checkout step, and the commit being force-checked-out writes a file at
29 // "s/<leaf>". That path string is innocent (no ".git" or ".." component),
30 // so string validation alone lets it through. Following the symlink would
31 // let the write escape the worktree.
32 //
33 // Matching upstream Git's create_directories, a force checkout must remove
34 // the blocking symlink and materialise a real directory, writing the file
35 // safely inside the worktree. Each case asserts the checkout succeeds, the
36 // dangerous target is untouched, and the file lands in the worktree
37 // instead.
38 func TestForceCheckoutReplacesLeadingSymlink(t *testing.T) {
39 if testing.Short() {
40 t.Skip("skipping symlink-mask path validation test in short mode")
41 }
42 t.Parallel()
43
44 const exploit = "exploit"
45
46 cases := []struct {
47 name string
48 // setup returns the symlink target (the on-disk contents of the
49 // planted symlink "s"), the tree path the attack commit writes,
50 // and the on-disk location that path resolves to if "s" is
51 // followed.
52 setup func(t *testing.T, repoDir string) (linkTarget, entryPath, escapePath string)
53 }{
54 {
55 name: "masks .git config",
56 setup: func(_ *testing.T, repoDir string) (string, string, string) {
57 return ".git", "s/config", filepath.Join(repoDir, ".git", "config")
58 },
59 },
60 {
61 name: "masks .git hook",
62 setup: func(_ *testing.T, repoDir string) (string, string, string) {
63 return ".git", "s/hooks/pre-commit", filepath.Join(repoDir, ".git", "hooks", "pre-commit")
64 },
65 },
66 {
67 name: "masks parent dir",
68 setup: func(_ *testing.T, repoDir string) (string, string, string) {
69 return "..", "s/escape", filepath.Join(filepath.Dir(repoDir), "escape")
70 },
71 },
72 {
73 name: "masks absolute external dir",
74 setup: func(t *testing.T, _ string) (string, string, string) {
75 escape := t.TempDir()
76 return escape, "s/escape", filepath.Join(escape, "escape")
77 },
78 },
79 }
80
81 for _, tc := range cases {
82 t.Run(tc.name, func(t *testing.T) {
83 t.Parallel()
84
85 dir := t.TempDir()
86
87 r, err := PlainInit(dir, false)
88 require.NoError(t, err)
89
90 w, err := r.Worktree()
91 require.NoError(t, err)
92
93 require.NoError(t, util.WriteFile(w.Filesystem, "README", []byte("init"), 0o644))
94 _, err = w.Add("README")
95 require.NoError(t, err)
96
97 initHash, err := w.Commit("initial commit\n", &CommitOptions{Author: defaultSignature()})
98 require.NoError(t, err)
99 initCommit, err := r.CommitObject(initHash)
100 require.NoError(t, err)
101
102 linkTarget, entryPath, escapePath := tc.setup(t, dir)
103
104 attack := buildCommitWithEntry(t, r.Storer, initCommit, initHash, entryPath, filemode.Regular)
105
106 // Plant the masking symlink in the worktree. This models the
107 // pre-existing symlink an attacker relies on.
108 if err := w.Filesystem.Symlink(linkTarget, "s"); err != nil {
109 if isSymlinkWindowsNonAdmin(err) {
110 t.Skipf("symlink creation requires elevated privileges: %v", err)
111 }
112 require.NoError(t, err)
113 }
114
115 // Upstream git checkout -f succeeds here by replacing "s".
116 require.NoError(t, w.Checkout(&CheckoutOptions{Hash: attack.Hash, Force: true}),
117 "force checkout should replace symlink %q -> %q, not fail", entryPath, linkTarget)
118
119 // The dangerous target must not have been followed.
120 if data, readErr := os.ReadFile(escapePath); readErr == nil {
121 require.NotEqual(t, exploit, string(data),
122 "force checkout wrote through symlink %q -> %q to %s", entryPath, linkTarget, escapePath)
123 }
124
125 // The blocking symlink is gone and the file lands safely in the
126 // worktree instead.
127 fi, err := os.Lstat(filepath.Join(dir, "s"))
128 require.NoError(t, err)
129 require.Zero(t, fi.Mode()&os.ModeSymlink, "leading symlink %q must be replaced by a real directory", "s")
130
131 data, err := os.ReadFile(filepath.Join(dir, filepath.FromSlash(entryPath)))
132 require.NoError(t, err, "checked-out file must exist inside the worktree")
133 require.Equal(t, exploit, string(data))
134 })
135 }
136 }
137
138 // TestWorktreeFilesystemRejectsSymlinkTraversal pins the leading-path
139 // symlink invariant at the wrapper boundary. Every operation on "s/<name>"
140 // must be refused while "s" is an existing symlink, so no worktree code
141 // path, read or write, can follow the link out of the worktree. The path
142 // string is innocent, so validPath alone would allow it. validNoLeadingSymlink
143 // is what catches it. Chroot is additionally refused when the final
144 // component is itself a symlink, the "valid path, wrong target" case that
145 // Submodule.Repository relies on.
146 //
147 // It runs against both memfs and osfs so real on-disk symlink semantics
148 // are exercised alongside the pure abstraction.
149 func TestWorktreeFilesystemRejectsSymlinkTraversal(t *testing.T) {
150 t.Parallel()
151
152 const wantSubstr = "is a symlink"
153
154 backends := []struct {
155 name string
156 makeFS func(t *testing.T) billy.Filesystem
157 }{
158 {"memfs", func(*testing.T) billy.Filesystem { return memfs.New() }},
159 {"osfs", func(t *testing.T) billy.Filesystem { return osfs.New(t.TempDir()) }},
160 }
161
162 // symlinkFS wraps a fresh backend filesystem with "s" and "a/b/s"
163 // planted as symlinks. Each subtest gets its own, so the parallel
164 // subtests never share filesystem state.
165 symlinkFS := func(t *testing.T, makeFS func(*testing.T) billy.Filesystem) *worktreeFilesystem {
166 t.Helper()
167 base := makeFS(t)
168 require.NoError(t, base.MkdirAll("elsewhere", 0o755))
169 require.NoError(t, base.MkdirAll("a/b", 0o755))
170 if err := base.Symlink("elsewhere", "s"); err != nil {
171 if isSymlinkWindowsNonAdmin(err) {
172 t.Skipf("symlink creation requires elevated privileges: %v", err)
173 }
174 require.NoError(t, err)
175 }
176 require.NoError(t, base.Symlink("elsewhere", "a/b/s"))
177 return newWorktreeFilesystem(base, false, false)
178 }
179
180 for _, bk := range backends {
181 t.Run(bk.name, func(t *testing.T) {
182 t.Parallel()
183
184 for _, p := range []string{"s/file", "s/deeper/file", "a/b/s/file"} {
185 t.Run(p, func(t *testing.T) {
186 t.Parallel()
187 fs := symlinkFS(t, bk.makeFS)
188
189 _, err := fs.Create(p)
190 assert.ErrorContains(t, err, wantSubstr, "Create should reject %q", p)
191
192 _, err = fs.OpenFile(p, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o644)
193 assert.ErrorContains(t, err, wantSubstr, "OpenFile should reject %q", p)
194
195 _, err = fs.Open(p)
196 assert.ErrorContains(t, err, wantSubstr, "Open should reject read through symlink %q", p)
197
198 err = fs.MkdirAll(p, 0o755)
199 assert.ErrorContains(t, err, wantSubstr, "MkdirAll should reject %q", p)
200
201 err = fs.Symlink("target", p)
202 assert.ErrorContains(t, err, wantSubstr, "Symlink should reject %q", p)
203
204 err = fs.Rename("readme.md", p)
205 assert.ErrorContains(t, err, wantSubstr, "Rename should reject destination %q", p)
206
207 err = fs.Remove(p)
208 assert.ErrorContains(t, err, wantSubstr, "Remove should reject %q", p)
209 })
210 }
211
212 t.Run("Chroot through leading symlink", func(t *testing.T) {
213 t.Parallel()
214 fs := symlinkFS(t, bk.makeFS)
215 _, err := fs.Chroot("s/sub")
216 assert.ErrorContains(t, err, wantSubstr, "Chroot should reject a leading symlink")
217 })
218
219 // The submodule-scoping case: Submodule.Repository chroots into
220 // the tree-controlled submodule path. A symlink as the final
221 // component must not redirect the scope out of the worktree.
222 t.Run("Chroot onto symlink target", func(t *testing.T) {
223 t.Parallel()
224 fs := symlinkFS(t, bk.makeFS)
225 _, err := fs.Chroot("s")
226 assert.ErrorContains(t, err, wantSubstr, "Chroot should reject a symlink as the final component")
227 })
228 })
229 }
230 }
231
232 // TestCheckoutReplacesBlockingFinalSymlink pins the final-component case at
233 // the checkout materialisation boundary: writing a tracked regular file at
234 // a path that already exists as a symlink must replace the symlink, not
235 // follow it and overwrite the link's target. Runs on both memfs and osfs.
236 func TestCheckoutReplacesBlockingFinalSymlink(t *testing.T) {
237 t.Parallel()
238
239 run := func(t *testing.T, base billy.Filesystem) {
240 t.Helper()
241
242 w := &Worktree{
243 Filesystem: newWorktreeFilesystem(base, defaultProtectNTFS(), defaultProtectHFS()),
244 }
245
246 require.NoError(t, util.WriteFile(base, "target.txt", []byte("keep"), 0o644))
247 if err := base.Symlink("target.txt", "tracked.txt"); err != nil {
248 if isSymlinkWindowsNonAdmin(err) {
249 t.Skipf("symlink creation requires elevated privileges: %v", err)
250 }
251 require.NoError(t, err)
252 }
253
254 blobObj := &plumbing.MemoryObject{}
255 blobObj.SetType(plumbing.BlobObject)
256 _, err := blobObj.Write([]byte("replacement"))
257 require.NoError(t, err)
258 blob, err := object.DecodeBlob(blobObj)
259 require.NoError(t, err)
260
261 require.NoError(t, w.checkoutFile(object.NewFile("tracked.txt", filemode.Regular, blob)))
262
263 got, err := util.ReadFile(base, "tracked.txt")
264 require.NoError(t, err)
265 assert.Equal(t, "replacement", string(got))
266
267 // The symlink target must be untouched.
268 target, err := util.ReadFile(base, "target.txt")
269 require.NoError(t, err)
270 assert.Equal(t, "keep", string(target))
271
272 fi, err := base.Lstat("tracked.txt")
273 require.NoError(t, err)
274 assert.Zero(t, fi.Mode()&os.ModeSymlink, "tracked.txt must be a regular file, not a symlink")
275 }
276
277 t.Run("memfs", func(t *testing.T) { t.Parallel(); run(t, memfs.New()) })
278 t.Run("osfs", func(t *testing.T) { t.Parallel(); run(t, osfs.New(t.TempDir())) })
279 }
280
281 // writeBlob stores content as a blob object and returns its hash.
282 func writeBlob(t *testing.T, s storer.Storer, content []byte) plumbing.Hash {
283 t.Helper()
284
285 obj := s.NewEncodedObject()
286 obj.SetType(plumbing.BlobObject)
287 obj.SetSize(int64(len(content)))
288 w, err := obj.Writer()
289 require.NoError(t, err)
290 _, err = w.Write(content)
291 require.NoError(t, err)
292 require.NoError(t, w.Close())
293
294 hash, err := s.SetEncodedObject(obj)
295 require.NoError(t, err)
296 return hash
297 }
298
299 // storeRawTree writes a tree object to s by assembling the raw
300 // `<mode> SP <name> NUL <hash>` bytes for each entry, bypassing
301 // Tree.Encode's validation so tests can plant otherwise-refused names.
302 func storeRawTree(t *testing.T, s storer.Storer, entries []object.TreeEntry) plumbing.Hash {
303 t.Helper()
304
305 var buf bytes.Buffer
306 for _, e := range entries {
307 fmt.Fprintf(&buf, "%o %s", e.Mode, e.Name)
308 buf.WriteByte(0)
309 buf.Write(e.Hash[:])
310 }
311
312 obj := s.NewEncodedObject()
313 obj.SetType(plumbing.TreeObject)
314 w, err := obj.Writer()
315 require.NoError(t, err)
316 _, err = w.Write(buf.Bytes())
317 require.NoError(t, err)
318 require.NoError(t, w.Close())
319
320 hash, err := s.SetEncodedObject(obj)
321 require.NoError(t, err)
322 return hash
323 }
324
325 // buildCommitWithEntry builds a commit on top of parent whose tree is the
326 // parent tree plus a single entry at filePath (nested trees are created
327 // for each intermediate directory), with "exploit" as the blob content.
328 func buildCommitWithEntry(t *testing.T, s storer.Storer, parent *object.Commit, parentHash plumbing.Hash, filePath string, leafMode filemode.FileMode) *object.Commit {
329 t.Helper()
330
331 leafHash := writeBlob(t, s, []byte("exploit"))
332
333 parts := strings.Split(filePath, "/")
334 for i := len(parts) - 1; i >= 1; i-- {
335 entry := object.TreeEntry{Name: parts[i], Mode: leafMode, Hash: leafHash}
336 leafHash = storeRawTree(t, s, []object.TreeEntry{entry})
337 leafMode = filemode.Dir
338 }
339
340 return buildCommitWithEntries(t, s, parent, parentHash,
341 []object.TreeEntry{{Name: parts[0], Mode: leafMode, Hash: leafHash}},
342 "bad path: "+filePath+"\n")
343 }
344
345 // buildCommitWithEntries builds a commit on top of parent whose tree is
346 // the parent tree plus the given extra entries.
347 func buildCommitWithEntries(t *testing.T, s storer.Storer, parent *object.Commit, parentHash plumbing.Hash, extra []object.TreeEntry, message string) *object.Commit {
348 t.Helper()
349
350 parentTree, err := parent.Tree()
351 require.NoError(t, err)
352
353 entries := make([]object.TreeEntry, len(parentTree.Entries), len(parentTree.Entries)+len(extra))
354 copy(entries, parentTree.Entries)
355 entries = append(entries, extra...)
356 sort.Sort(object.TreeEntrySorter(entries))
357 rootHash := storeRawTree(t, s, entries)
358
359 commit := &object.Commit{
360 Author: *defaultSignature(),
361 Committer: *defaultSignature(),
362 Message: message,
363 TreeHash: rootHash,
364 ParentHashes: []plumbing.Hash{parentHash},
365 }
366 commitObj := s.NewEncodedObject()
367 require.NoError(t, commit.Encode(commitObj))
368 commitHash, err := s.SetEncodedObject(commitObj)
369 require.NoError(t, err)
370
371 result, err := object.GetCommit(s, commitHash)
372 require.NoError(t, err)
373 return result
374 }