Web application security · 5 MIN READ

Path traversal: confine file access with os.Root, because Join and Clean only edit strings

Open user-named files through os.Root, use filepath.IsLocal and Localize for early rejection and extract archives without zip-slip.

Path traversal turns a file name from a request into access somewhere else on disk: ../ segments, an absolute path or a symlink that leads out of the intended directory. The classic Go defense, filepath.Join plus Clean plus a prefix check, works on strings while the kernel resolves the real path later, symlinks included. Go 1.24 added os.Root, which opens a directory once and resolves every later name inside it, and Go 1.25 extended it with ReadFile, WriteFile, MkdirAll and other helpers.

security · A MAP OF THE IDEA

  1. Reject non-local names
  2. Open os.Root once
  3. Operate through Root
  4. Refuse links in archives

Useful when

  • Neither .. nor symlinks can lead outside the opened directory.
  • Errors carry only the relative name, so they are safe to log.

Watch out

  • Root does not stop mount points, device files or hard links inside the tree.
  • archive/zip accepts non-local entry names unless zipinsecurepath=0 is set.

Implementation & operation cost: Passing a *os.Root instead of a base-path string and a few checks per archive entry; component-wise resolution adds a little work to each open.

01

Lexical checks cannot see the filesystem

filepath.Clean removes . and .. elements and duplicate separators, and filepath.Join cleans its result. Neither consults the disk. If the base directory contains a symbolic link, whether uploaded by a user, unpacked from an archive or left by a deploy, a clean, local-looking name such as latest.txt can resolve to a file outside the base. Prefix checks add their own bug: strings.HasPrefix(p, "/srv/public") also accepts /srv/public-backup. And code that resolves symlinks first and opens second can be raced by a concurrent rename. The robust design resolves the name relative to an already-open directory, one component at a time, and refuses any step that leaves it.

02

Compare a string join with os.Root

The program builds a small tree under os.TempDir(): a public directory with readme.txt, a secret.txt beside it and a relative symlink inside public that points at the secret. It asks for four names in three ways: the lexical filepath.IsLocal test, a naive Join of the cleaned name, and Root.ReadFile on a root opened at public. The deferred RemoveAll deletes the whole tree afterwards.

go
package main

import (
	"fmt"
	"os"
	"path/filepath"
)

// naiveRead looks careful but only manipulates strings.
func naiveRead(base, name string) string {
	data, err := os.ReadFile(filepath.Join(base, filepath.Clean(name)))
	if err != nil {
		return "error"
	}
	return string(data)
}

// rootRead resolves every component inside the opened directory.
func rootRead(root *os.Root, name string) string {
	data, err := root.ReadFile(name)
	if err != nil {
		return "denied: " + err.Error()
	}
	return string(data)
}

func main() {
	dir, err := os.MkdirTemp("", "traversal-demo-*")
	if err != nil {
		panic(err)
	}
	defer os.RemoveAll(dir)

	public := filepath.Join(dir, "public")
	must(os.Mkdir(public, 0o755))
	must(os.WriteFile(filepath.Join(public, "readme.txt"), []byte("public notes"), 0o644))
	must(os.WriteFile(filepath.Join(dir, "secret.txt"), []byte("SECRET"), 0o600))
	// A relative symlink that a user upload or a bad deploy could leave behind.
	must(os.Symlink("../secret.txt", filepath.Join(public, "latest.txt")))

	root, err := os.OpenRoot(public)
	if err != nil {
		panic(err)
	}
	defer root.Close()

	for _, name := range []string{"readme.txt", "../secret.txt", "/readme.txt", "latest.txt"} {
		fmt.Printf("%-15q IsLocal=%-5t join=%-12s root=%s\n",
			name, filepath.IsLocal(name), naiveRead(public, name), rootRead(root, name))
	}
}

func must(err error) {
	if err != nil {
		panic(err)
	}
}
Read the code

IsLocal rejects ../secret.txt and /readme.txt, but reports latest.txt as local because it never looks at the disk. The naive join leaks the secret twice: once through .., and once through the symlink that no lexical check can see. Join treats /readme.txt as relative, so that request happens to stay inside, which is luck rather than policy. os.Root refuses all three escapes with the same error, path escapes from parent. The error's path is the name you passed, never the root's location, so it is safe to log. Root follows symlinks only while they stay inside the root and rejects absolute link targets outright.

03

IsLocal and Localize are early filters, not boundaries

Rejecting obviously bad names before touching the disk gives clear 400 responses and readable logs. filepath.IsLocal reports whether a path is non-empty, not absolute and still inside its base after lexical cleaning; on Windows it also rejects reserved names such as NUL. When names arrive slash-separated, as in URLs, io/fs paths and archives, filepath.Localize converts them to the OS form and fails for anything that is not a valid io/fs path, so its result is always local. Neither function sees symlinks, so pair them with os.Root. To serve a directory over HTTP, http.FileServerFS(root.FS()) keeps the confinement, whereas http.Dir and os.DirFS document that they follow symlinks wherever they point.

04

Extract archives without zip-slip

Zip-slip is path traversal delivered in bulk: an entry named ../../escape.txt or /etc/cron.d/job is written wherever it points if extraction code joins entry names to a destination. archive/zip still accepts such names by default in Go 1.27; only with GODEBUG=zipinsecurepath=0 does NewReader return ErrInsecurePath, alongside a usable reader. The extractor below validates each name with Localize, refuses symlinks and other non-regular entries, writes through os.Root with O_EXCL so it never follows or overwrites an existing file, and caps each file's size.

go
package main

import (
	"archive/zip"
	"bytes"
	"errors"
	"fmt"
	"io"
	"io/fs"
	"os"
	"path/filepath"
)

const maxFileBytes = 1 << 20

// extract writes regular files from zr beneath root and refuses everything else.
func extract(root *os.Root, zr *zip.Reader) error {
	for _, f := range zr.File {
		if f.FileInfo().IsDir() {
			continue // directories are created on demand below
		}
		// Zip names are slash-separated; Localize rejects absolute names,
		// ".." elements and names the OS cannot represent.
		name, err := filepath.Localize(f.Name)
		if err != nil {
			fmt.Printf("skip %q: not a local path\n", f.Name)
			continue
		}
		if !f.Mode().IsRegular() {
			fmt.Printf("skip %q: not a regular file\n", f.Name)
			continue
		}
		if err := root.MkdirAll(filepath.Dir(name), 0o755); err != nil {
			return err
		}
		if err := copyFile(root, name, f); err != nil {
			return fmt.Errorf("%s: %w", f.Name, err)
		}
		fmt.Printf("wrote %q\n", name)
	}
	return nil
}

func copyFile(root *os.Root, name string, f *zip.File) error {
	src, err := f.Open()
	if err != nil {
		return err
	}
	defer src.Close()
	dst, err := root.OpenFile(name, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o644)
	if err != nil {
		return err
	}
	n, err := io.Copy(dst, io.LimitReader(src, maxFileBytes+1))
	if cerr := dst.Close(); err == nil {
		err = cerr
	}
	if err == nil && n > maxFileBytes {
		err = errors.New("file exceeds size limit")
	}
	return err
}

func hostileArchive() *bytes.Reader {
	var buf bytes.Buffer
	zw := zip.NewWriter(&buf)
	add := func(name string, mode fs.FileMode, body string) {
		h := &zip.FileHeader{Name: name, Method: zip.Deflate}
		h.SetMode(mode)
		w, err := zw.CreateHeader(h)
		if err != nil {
			panic(err)
		}
		if _, err := io.WriteString(w, body); err != nil {
			panic(err)
		}
	}
	add("readme.txt", 0o644, "hello")
	add("docs/guide.txt", 0o644, "guide")
	add("../../escape.txt", 0o644, "zip slip")
	add("/etc/cron.d/job", 0o644, "absolute")
	add("docs/link", fs.ModeSymlink|0o777, "../../../home")
	if err := zw.Close(); err != nil {
		panic(err)
	}
	return bytes.NewReader(buf.Bytes())
}

func main() {
	dir, err := os.MkdirTemp("", "unzip-demo-*")
	if err != nil {
		panic(err)
	}
	defer os.RemoveAll(dir)
	root, err := os.OpenRoot(dir)
	if err != nil {
		panic(err)
	}
	defer root.Close()

	ra := hostileArchive()
	zr, err := zip.NewReader(ra, ra.Size())
	if err != nil && !errors.Is(err, zip.ErrInsecurePath) {
		panic(err)
	}
	if err := extract(root, zr); err != nil {
		fmt.Println("extract failed:", err)
	}
}
Read the code

Directory entries are skipped because Root.MkdirAll creates parents on demand. Localize rejects the two hostile names before any write, and the symlink entry is refused by its mode rather than its name. Writes go through root.OpenFile, so even a name that passed every check cannot follow a link already present in the destination. io.LimitReader allows one byte past the limit so an oversize entry is detected rather than silently truncated. Running the program prints one wrote or skip line per entry and removes its temporary directory. Production extractors also cap the entry count and the total uncompressed size, because a small upload can expand into gigabytes.

05

What os.Root does not promise, and better designs

os.Root guarantees that names resolve beneath the root; it does not make everything beneath the root safe. It does not stop traversal across mount points or bind mounts inside the tree, it does not hide device files or /proc entries reachable within it, and a hard link inside the root to a file elsewhere is simply a file inside the root. On Unix, Root.Chmod, Chown and Chtimes have a documented race with symlink swaps. Prefer designs where users never name paths: store uploads under server-generated IDs, keep the original filename as metadata, and look files up by ID after an authorization check. In tests, keep a table of hostile names, including .., absolute paths, encoded dots if any layer decodes them and a planted symlink, and assert that every one is refused. Run the service as a user that cannot read secrets it does not need.

TAKE THIS WITH YOU

Reject non-local names early with filepath.IsLocal or Localize, then perform every file operation through os.Root so that .. and symlinks cannot leave the directory.

Check your understanding

A handler joins a cleaned file name to its upload directory before opening it. Why can the opened file still be outside that directory?

Go to the source

Progress stays in this browser. No account needed.