Protect filesystem paths and archives
Protect filesystem paths and archives
Untrusted names should never directly select arbitrary filesystem locations. Prefer server-generated identifiers mapped to storage paths. If a toy archive accepts only flat names, accept only ASCII letters, digits, dots, hyphens and underscores, reject trailing dots and enforce the declared local policy. This example validates a narrow name format; it never extracts an archive.
package main
import ( "fmt" "io/fs" "path/filepath" "strings")
func safeName(s string) bool { if len(s) < 1 || len(s) > 80 || s == "." || !fs.ValidPath(s) || !filepath.IsLocal(s) { return false } for _, r := range s { if !(r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9' || r == '.' || r == '-' || r == '_') { return false } } return !strings.HasSuffix(s, ".")}func main() { fmt.Println(safeName("note.txt"), safeName("folder/note.txt"), safeName("."))}fs.ValidPath uses slash-separated virtual paths; filepath.IsLocal is lexical and platform dependent. Neither prevents symlink traversal or races during actual file access. For extraction, use a private controlled destination, reject links and special files, reject collisions and enforce total count and byte limits. On Go versions with os.Root, evaluate its documented containment guarantees before use; it is not available in Go 1.23.
Expected output:
true false falseBound decompressed bytes
package main
import ( "errors" "fmt" "io" "strings")
func readEntry(r io.Reader) ([]byte, error) { b, e := io.ReadAll(io.LimitReader(r, 65)) if e != nil { return nil, e } if len(b) > 64 { return nil, errors.New("entry too large") } return b, nil}func main() { b, e := readEntry(strings.NewReader("note")) fmt.Println(string(b), e == nil) _, e = readEntry(strings.NewReader(strings.Repeat("x", 65))) fmt.Println(e != nil)}Read at most limit+1 bytes to distinguish a complete entry at the limit from an oversized entry. A real archive reader must also check entry count, total decompressed bytes, duplicate names, metadata and decompression errors. Do not trust declared sizes alone. This is a bounded in-memory entry, not a production extractor.
Expected output:
note truetrueTry it locally
Check that exactly 64 bytes are accepted and 65 are rejected.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Security engineering 03: Protect filesystem paths and archives
Check the lesson objective before moving on.
Does filepath.IsLocal resolve symlinks?
Why read one byte beyond the limit?