ValidatePathWithinBase checks that candidate is located within the base directory tree. Both paths are resolved via filepath.EvalSymlinks (with filepath.Abs as fallback when a path does not yet exist) before comparison, so neither ".." components nor symlinks pointing outside base can be used to esc
(base, candidate string)
| 63 | // - Either path cannot be resolved to an absolute form. |
| 64 | // - The resolved candidate path starts outside the resolved base directory. |
| 65 | func ValidatePathWithinBase(base, candidate string) error { |
| 66 | fileutilLog.Printf("ValidatePathWithinBase: checking candidate=%q within base=%q", candidate, base) |
| 67 | // EvalSymlinks resolves both symlinks and ".." components. |
| 68 | // Fall back to Abs when a path does not exist on disk yet. |
| 69 | absBase, err := filepath.EvalSymlinks(base) |
| 70 | if err != nil { |
| 71 | absBase, err = filepath.Abs(base) |
| 72 | if err != nil { |
| 73 | return fmt.Errorf("failed to resolve base path %q: %w", base, err) |
| 74 | } |
| 75 | } |
| 76 | absCand, err := filepath.EvalSymlinks(candidate) |
| 77 | if err != nil { |
| 78 | absCand, err = filepath.Abs(candidate) |
| 79 | if err != nil { |
| 80 | return fmt.Errorf("failed to resolve candidate path %q: %w", candidate, err) |
| 81 | } |
| 82 | } |
| 83 | rel, err := filepath.Rel(absBase, absCand) |
| 84 | if err != nil || !filepath.IsLocal(rel) { |
| 85 | fileutilLog.Printf("ValidatePathWithinBase: path escape detected: candidate=%q base=%q", candidate, base) |
| 86 | return fmt.Errorf("path %q escapes base directory %q", candidate, base) |
| 87 | } |
| 88 | fileutilLog.Printf("ValidatePathWithinBase: path is safe: candidate=%q (rel=%s) within base=%q", candidate, rel, base) |
| 89 | return nil |
| 90 | } |
| 91 | |
| 92 | // EnsureParentDir ensures the parent directory for path exists, creating it recursively when needed. |
| 93 | func EnsureParentDir(path string, perm os.FileMode) error { |