ValidateAbsolutePath validates that a file path is absolute and safe to use. It performs the following security checks: - Cleans the path using filepath.Clean to normalize . and .. components - Verifies the path is absolute to prevent relative path traversal attacks Returns the cleaned absolute pat
(path string)
| 35 | // |
| 36 | // content, err := os.ReadFile(cleanPath) |
| 37 | func ValidateAbsolutePath(path string) (string, error) { |
| 38 | // Check for empty path |
| 39 | if path == "" { |
| 40 | fileutilLog.Print("ValidateAbsolutePath: rejected empty path") |
| 41 | return "", errors.New("path cannot be empty") |
| 42 | } |
| 43 | |
| 44 | // Sanitize the filepath to prevent path traversal attacks |
| 45 | cleanPath := filepath.Clean(path) |
| 46 | |
| 47 | // Verify the path is absolute to prevent relative path traversal |
| 48 | if !filepath.IsAbs(cleanPath) { |
| 49 | fileutilLog.Printf("ValidateAbsolutePath: rejected relative path: %s", path) |
| 50 | return "", fmt.Errorf("path must be absolute, got: %s", path) |
| 51 | } |
| 52 | |
| 53 | fileutilLog.Printf("ValidateAbsolutePath: validated path: %s", cleanPath) |
| 54 | return cleanPath, nil |
| 55 | } |
| 56 | |
| 57 | // ValidatePathWithinBase checks that candidate is located within the base directory tree. |
| 58 | // Both paths are resolved via filepath.EvalSymlinks (with filepath.Abs as |