| 1 |
package pathutil |
| 2 |
|
| 3 |
import ( |
| 4 |
"fmt" |
| 5 |
"path/filepath" |
| 6 |
"strings" |
| 7 |
) |
| 8 |
|
| 9 |
// ErrInvalidPath is returned by ValidTreePath when its argument is |
| 10 |
// not a safe path to materialise into the worktree. |
| 11 |
var ErrInvalidPath = fmt.Errorf("invalid path") |
| 12 |
|
| 13 |
// ValidTreePath rejects path strings that, if materialised into a |
| 14 |
// worktree, would let an attacker-controlled tree entry escape the |
| 15 |
// worktree or rewrite repository metadata. It rejects: |
| 16 |
// |
| 17 |
// - control characters (< 0x20, 0x7f); |
| 18 |
// - empty paths and "." / ".." components; |
| 19 |
// - Windows volume name prefixes (e.g. C:); |
| 20 |
// - .git, its 8.3 NTFS short-name git~1, plus their HFS+ and NTFS |
| 21 |
// variants — at every position, not just the root. |
| 22 |
// |
| 23 |
// HFS+/NTFS variants of `.git` are always rejected at this layer |
| 24 |
// regardless of runtime config: tree paths are canonical UTF-8 with |
| 25 |
// no zero-width characters or NTFS short-name forms, so an entry |
| 26 |
// that looks like a disguised `.git` is suspicious anywhere. Windows |
| 27 |
// reserved device names (CON, NUL, etc.) are not policed here — they |
| 28 |
// are legitimate filenames on non-Windows filesystems and upstream |
| 29 |
// Git accepts them. The wrapper layer (validPath in package git) |
| 30 |
// rejects them at materialisation time when core.protectNTFS is on. |
| 31 |
// |
| 32 |
// Mirrors upstream Git's verify_path_internal at read-cache.c#L987 |
| 33 |
// in tag v2.54.0[1] with protect_hfs / protect_ntfs treated as |
| 34 |
// always-on for `.git`-disguise detection (tree paths are not |
| 35 |
// application-supplied) and is_valid_win32_path left to the wrapper. |
| 36 |
// |
| 37 |
// [1]: https://github.com/git/git/blob/v2.54.0/read-cache.c#L987 |
| 38 |
func ValidTreePath(p string) error { |
| 39 |
for i := 0; i < len(p); i++ { |
| 40 |
if p[i] < 0x20 || p[i] == 0x7f { |
| 41 |
return fmt.Errorf("%w %q: contains control character", ErrInvalidPath, p) |
| 42 |
} |
| 43 |
} |
| 44 |
|
| 45 |
parts := strings.FieldsFunc(p, func(r rune) bool { return r == '\\' || r == '/' }) |
| 46 |
if len(parts) == 0 { |
| 47 |
return fmt.Errorf("%w: %q", ErrInvalidPath, p) |
| 48 |
} |
| 49 |
|
| 50 |
// Volume names are not supported, in both formats: \\ and <DRIVE_LETTER>:. |
| 51 |
if vol := filepath.VolumeName(p); vol != "" { |
| 52 |
return fmt.Errorf("%w: %q", ErrInvalidPath, p) |
| 53 |
} |
| 54 |
|
| 55 |
for _, part := range parts { |
| 56 |
if part == "." || part == ".." { |
| 57 |
return fmt.Errorf("%w %q: cannot use %q", ErrInvalidPath, p, part) |
| 58 |
} |
| 59 |
|
| 60 |
if IsDotGitName(part) || IsHFSDotGit(part) || IsNTFSDotGit(part) { |
| 61 |
return fmt.Errorf("%w component: %q", ErrInvalidPath, p) |
| 62 |
} |
| 63 |
} |
| 64 |
|
| 65 |
return nil |
| 66 |
} |