Safe file access with os.Root
suggest changeMany programs work with file names they didn't choose: names of uploaded files, entries in a ZIP archive, a path in a URL, a file name in a config file written by someone else. The obvious code is a security hole:
// DON'T: name comes from the user
data, err := os.ReadFile(filepath.Join(baseDir, name))
filepath.Join cleans .., so a name like ../../etc/passwd walks out of baseDir. Checking the name first helps, but it isn't enough: a symbolic link inside baseDir can point anywhere, and a directory can be replaced by a symlink between your check and the open (a TOCTOU race, "time of check, time of use").
os.Root (Go 1.24) solves this in the standard library. It opens a directory once, and every operation through it is confined to that directory tree. It checks every path component as it opens it, so neither .., absolute paths nor symlinks can escape.
Go 1.24 added the basic operations (Open, Create, OpenFile, OpenRoot, Mkdir, Remove, Stat, Lstat, FS). Go 1.25 added MkdirAll, RemoveAll, Rename, Link, Symlink, Readlink, ReadFile, WriteFile, Chmod, Chown, Lchown and Chtimes. All examples here need Go 1.25 or later.
Opening a root: os.OpenRoot
os.OpenRoot(dir) opens a directory and returns an *os.Root. Methods on Root take names relative to that directory and mirror the functions in package os:
| package os | os.Root |
|---|---|
os.Open(name) |
root.Open(name) |
os.Create(name) |
root.Create(name) |
os.OpenFile(name, flag, perm) |
root.OpenFile(name, flag, perm) |
os.ReadFile(name) |
root.ReadFile(name) |
os.WriteFile(name, data, perm) |
root.WriteFile(name, data, perm) |
os.Mkdir, os.MkdirAll |
root.Mkdir, root.MkdirAll |
os.Remove, os.RemoveAll |
root.Remove, root.RemoveAll |
os.Stat, os.Lstat |
root.Stat, root.Lstat |
os.Rename, os.Link, os.Symlink, os.Readlink |
root.Rename, root.Link, root.Symlink, root.Readlink |
os.Chmod, os.Chown, os.Lchown, os.Chtimes |
root.Chmod, root.Chown, root.Lchown, root.Chtimes |
package main
import (
"fmt"
"os"
)
func main() {
dir, err := os.MkdirTemp("", "data-*")
if err != nil {
fmt.Println("error:", err)
return
}
defer os.RemoveAll(dir)
root, err := os.OpenRoot(dir)
if err != nil {
fmt.Println("error:", err)
return
}
defer root.Close()
// all names are relative to the root directory
if err := root.Mkdir("notes", 0o755); err != nil {
fmt.Println("error:", err)
return
}
f, err := root.Create("notes/todo.txt")
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Fprintln(f, "buy milk")
f.Close()
data, err := root.ReadFile("notes/todo.txt")
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Printf("content: %q\n", data)
fi, err := root.Stat("notes")
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Println("notes is dir:", fi.IsDir())
}
content: "buy milk\n"
notes is dir: true
A Root holds an open file descriptor (a handle on Windows), so Close it when you're done. root.Name() returns the directory name passed to OpenRoot. The files returned by root.Open and root.Create are ordinary *os.File values: read, write and close them as usual. A Root is safe to use from multiple goroutines, so a server can open it once at startup and share it between handlers.
What counts as escaping
Any name that would end up outside the root is rejected. Names that only wander around inside are fine:
package main
import (
"fmt"
"os"
"path/filepath"
)
func main() {
dir, err := os.MkdirTemp("", "root-*")
if err != nil {
fmt.Println("error:", err)
return
}
defer os.RemoveAll(dir)
os.MkdirAll(filepath.Join(dir, "docs"), 0o755)
os.WriteFile(filepath.Join(dir, "docs", "readme.txt"), []byte("hello"), 0o644)
root, err := os.OpenRoot(dir)
if err != nil {
fmt.Println("error:", err)
return
}
defer root.Close()
names := []string{
"docs/readme.txt",
"./docs/readme.txt",
"docs/../docs/readme.txt",
"docs//readme.txt",
"../secret.txt",
"docs/../../secret.txt",
"/etc/passwd",
"missing.txt",
}
for _, name := range names {
data, err := root.ReadFile(name)
if err != nil {
fmt.Printf("%-25s error: %v\n", name, err)
continue
}
fmt.Printf("%-25s %q\n", name, data)
}
}
docs/readme.txt "hello"
./docs/readme.txt "hello"
docs/../docs/readme.txt "hello"
docs//readme.txt "hello"
../secret.txt error: openat ../secret.txt: path escapes from parent
docs/../../secret.txt error: openat docs/../../secret.txt: path escapes from parent
/etc/passwd error: openat /etc/passwd: path escapes from parent
missing.txt error: openat missing.txt: no such file or directory
The rules:
.refers to the root itself, and./,//and..that stays inside the tree work as you'd expect..that goes above the root is an error, even when it's in the middle of the path- absolute paths are always rejected
- other errors (file not found, permission denied) are reported as usual and work with
errors.Is(err, fs.ErrNotExist)
The escape error is a *fs.PathError wrapping an unexported error with the text path escapes from parent. There is no exported sentinel to compare against, so treat it like any other failure: log it and return an error to the caller.
Symbolic links
Methods on Root follow symbolic links, but only when the link and its target stay inside the root. This is the part a lexical check can't do. In the example below an attacker planted three links inside the directory we serve (for example by uploading an archive, or through a shared directory). We compare four approaches:
package main
import (
"fmt"
"io/fs"
"os"
"path/filepath"
)
func main() {
base, err := os.MkdirTemp("", "base-*")
if err != nil {
fmt.Println("error:", err)
return
}
defer os.RemoveAll(base)
// base/secret.txt is outside of the directory we want to expose
os.WriteFile(filepath.Join(base, "secret.txt"), []byte("password"), 0o600)
// base/public is the directory users are allowed to read
dir := filepath.Join(base, "public")
os.MkdirAll(filepath.Join(dir, "docs"), 0o755)
os.WriteFile(filepath.Join(dir, "docs", "readme.txt"), []byte("hello"), 0o644)
// an attacker managed to plant symlinks inside public
os.Symlink("docs/readme.txt", filepath.Join(dir, "alias.txt"))
os.Symlink("../secret.txt", filepath.Join(dir, "up.txt"))
os.Symlink(filepath.Join(base, "secret.txt"), filepath.Join(dir, "abs.txt"))
root, err := os.OpenRoot(dir)
if err != nil {
fmt.Println("error:", err)
return
}
defer root.Close()
dirFS := os.DirFS(dir)
for _, name := range []string{"alias.txt", "up.txt", "abs.txt"} {
fmt.Printf("%s\n", name)
fmt.Printf(" filepath.IsLocal: %v\n", filepath.IsLocal(name))
data, err := os.ReadFile(filepath.Join(dir, name))
show(" os.ReadFile(Join): ", data, err)
data, err = fs.ReadFile(dirFS, name)
show(" os.DirFS: ", data, err)
data, err = root.ReadFile(name)
show(" os.Root: ", data, err)
}
}
func show(label string, data []byte, err error) {
if err != nil {
fmt.Printf("%s error: %v\n", label, err)
return
}
fmt.Printf("%s %q\n", label, data)
}
alias.txt
filepath.IsLocal: true
os.ReadFile(Join): "hello"
os.DirFS: "hello"
os.Root: "hello"
up.txt
filepath.IsLocal: true
os.ReadFile(Join): "password"
os.DirFS: "password"
os.Root: error: openat up.txt: path escapes from parent
abs.txt
filepath.IsLocal: true
os.ReadFile(Join): "password"
os.DirFS: "password"
os.Root: error: openat abs.txt: path escapes from parent
All three names look harmless to filepath.IsLocal, because it only looks at the string. os.ReadFile on a joined path and os.DirFS both follow the links and leak secret.txt. Only os.Root refuses them.
Note that os.DirFS is not a security boundary. It rejects names with .., but it follows symbolic links anywhere. Its documentation says so explicitly. Use root.FS(), described below, when you need an fs.FS that can't escape.
A few more details about symlinks:
package main
import (
"fmt"
"os"
"path/filepath"
)
func main() {
dir, err := os.MkdirTemp("", "root-*")
if err != nil {
fmt.Println("error:", err)
return
}
defer os.RemoveAll(dir)
root, err := os.OpenRoot(dir)
if err != nil {
fmt.Println("error:", err)
return
}
defer root.Close()
root.MkdirAll("releases/v2", 0o755)
root.WriteFile("releases/v2/app.txt", []byte("version 2"), 0o644)
// relative links that stay inside the root are fine
root.Symlink("releases/v2", "current")
data, err := root.ReadFile("current/app.txt")
fmt.Printf("current/app.txt: %q %v\n", data, err)
// absolute links are rejected, even when they point inside the root
abs := filepath.Join(dir, "releases", "v2")
root.Symlink(abs, "current-abs")
_, err = root.ReadFile("current-abs/app.txt")
fmt.Println("current-abs/app.txt:", err)
// Symlink doesn't validate the target; following it is what fails
err = root.Symlink("/etc/passwd", "passwd")
fmt.Println("Symlink to /etc/passwd:", err)
_, err = root.ReadFile("passwd")
fmt.Println("ReadFile(passwd):", err)
// the link itself can still be inspected and removed
target, err := root.Readlink("passwd")
fmt.Println("Readlink(passwd):", target, err)
fi, err := root.Lstat("passwd")
fmt.Println("Lstat(passwd) is symlink:", fi.Mode()&os.ModeSymlink != 0, err)
err = root.Remove("passwd")
fmt.Println("Remove(passwd):", err)
}
current/app.txt: "version 2" <nil>
current-abs/app.txt: openat current-abs/app.txt: path escapes from parent
Symlink to /etc/passwd: <nil>
ReadFile(passwd): openat passwd: path escapes from parent
Readlink(passwd): /etc/passwd <nil>
Lstat(passwd) is symlink: true <nil>
Remove(passwd): <nil>
- relative symlinks whose target is inside the root work, including for directories in the middle of a path
- absolute symlinks are always rejected, even when they point inside the root
root.Symlinkdoesn't validate the target, so you can create a dangling or escaping link. It's following the link that fails.Lstat,ReadlinkandRemoveact on the link itself, so you can still inspect and delete a bad link
One file in one call: os.OpenInRoot
When you only need to open a single file, os.OpenInRoot(dir, name) is a shortcut for OpenRoot followed by root.Open:
package main
import (
"fmt"
"io"
"os"
"path/filepath"
)
func main() {
dir, err := os.MkdirTemp("", "site-*")
if err != nil {
fmt.Println("error:", err)
return
}
defer os.RemoveAll(dir)
os.WriteFile(filepath.Join(dir, "index.html"), []byte("<h1>Hi</h1>"), 0o644)
for _, name := range []string{"index.html", "../../etc/passwd"} {
f, err := os.OpenInRoot(dir, name)
if err != nil {
fmt.Println("error:", err)
continue
}
data, _ := io.ReadAll(f)
f.Close()
fmt.Printf("%s: %s\n", name, data)
}
}
index.html: <h1>Hi</h1>
error: openat ../../etc/passwd: path escapes from parent
If you open many files under the same directory, keep one Root instead, so the directory is opened only once.
Creating, renaming and removing files
Writing goes through the root too. Both names of Rename and Link must be inside it:
package main
import (
"errors"
"fmt"
"io/fs"
"os"
"time"
)
func main() {
dir, err := os.MkdirTemp("", "store-*")
if err != nil {
fmt.Println("error:", err)
return
}
defer os.RemoveAll(dir)
root, err := os.OpenRoot(dir)
if err != nil {
fmt.Println("error:", err)
return
}
defer root.Close()
check := func(what string, err error) {
if err != nil {
fmt.Printf("%-28s error: %v\n", what, err)
return
}
fmt.Printf("%-28s ok\n", what)
}
check("MkdirAll users/42/photos", root.MkdirAll("users/42/photos", 0o755))
check("WriteFile profile.json", root.WriteFile("users/42/profile.json", []byte(`{"name":"ann"}`), 0o644))
// O_EXCL: fail instead of overwriting an existing file
f, err := root.OpenFile("users/42/profile.json", os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o644)
if err == nil {
f.Close()
}
check("OpenFile O_EXCL", err)
fmt.Println(" is fs.ErrExist:", errors.Is(err, fs.ErrExist))
// atomic replace: write a temporary file, then rename over the old one
check("WriteFile profile.json.tmp", root.WriteFile("users/42/profile.json.tmp", []byte(`{"name":"anna"}`), 0o644))
check("Rename tmp -> profile.json", root.Rename("users/42/profile.json.tmp", "users/42/profile.json"))
data, _ := root.ReadFile("users/42/profile.json")
fmt.Printf(" profile.json: %s\n", data)
// both names of Rename and Link must stay inside the root
check("Rename to ../stolen.json", root.Rename("users/42/profile.json", "../stolen.json"))
check("Link backup.json", root.Link("users/42/profile.json", "users/42/backup.json"))
check("Chmod 0600", root.Chmod("users/42/profile.json", 0o600))
mtime := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC)
check("Chtimes", root.Chtimes("users/42/profile.json", mtime, mtime))
fi, _ := root.Stat("users/42/profile.json")
fmt.Printf(" mode: %v, modified: %v\n", fi.Mode(), fi.ModTime().UTC())
check("Remove users/42", root.Remove("users/42"))
check("RemoveAll users/42", root.RemoveAll("users/42"))
check("RemoveAll ..", root.RemoveAll(".."))
_, err = root.Stat("users/42")
fmt.Println(" users/42 exists:", !errors.Is(err, fs.ErrNotExist))
}
MkdirAll users/42/photos ok
WriteFile profile.json ok
OpenFile O_EXCL error: openat users/42/profile.json: file exists
is fs.ErrExist: true
WriteFile profile.json.tmp ok
Rename tmp -> profile.json ok
profile.json: {"name":"anna"}
Rename to ../stolen.json error: renameat users/42/profile.json ../stolen.json: path escapes from parent
Link backup.json ok
Chmod 0600 ok
Chtimes ok
mode: -rw-------, modified: 2026-01-02 03:04:05 +0000 UTC
Remove users/42 error: removeat users/42: directory not empty
RemoveAll users/42 ok
RemoveAll .. error: RemoveAll ..: path escapes from parent
users/42 exists: false
Some patterns worth noticing:
root.OpenFilewithos.O_CREATE|os.O_EXCLfails withfs.ErrExistinstead of overwriting an existing file, which is what you want when names come from users (see File uploads)- writing to a temporary name and then calling
root.Renamereplaces a file atomically, so readers never see a half-written file root.RemoveAll("..")is an error, so a bug in your code can't delete the parent directory
On Unix, Chmod, Chown and Chtimes are not fully race-free: if a regular file is swapped for a symlink while the call is in progress, the change may apply to the link itself. The target still has to be inside the root.
Sub-roots: Root.OpenRoot
root.OpenRoot(name) opens a subdirectory as a new, narrower Root. That's handy for per-user or per-tenant directories:
package main
import (
"fmt"
"os"
)
func main() {
dir, err := os.MkdirTemp("", "tenants-*")
if err != nil {
fmt.Println("error:", err)
return
}
defer os.RemoveAll(dir)
all, err := os.OpenRoot(dir)
if err != nil {
fmt.Println("error:", err)
return
}
defer all.Close()
all.MkdirAll("acme/invoices", 0o755)
all.MkdirAll("globex/invoices", 0o755)
all.WriteFile("globex/invoices/1.txt", []byte("globex invoice"), 0o644)
// each tenant only sees its own directory
acme, err := all.OpenRoot("acme")
if err != nil {
fmt.Println("error:", err)
return
}
defer acme.Close()
err = acme.WriteFile("invoices/1.txt", []byte("acme invoice"), 0o644)
fmt.Println("acme write:", err)
_, err = acme.ReadFile("../globex/invoices/1.txt")
fmt.Println("acme reads globex:", err)
_, err = all.OpenRoot("../")
fmt.Println("OpenRoot(\"../\"):", err)
}
acme write: <nil>
acme reads globex: openat ../globex/invoices/1.txt: path escapes from parent
OpenRoot("../"): openat ../: path escapes from parent
The two roots are independent: closing one doesn't close the other.
An fs.FS view: Root.FS
root.FS() returns an fs.FS for the tree, so the root works with everything that accepts a file system: fs.WalkDir, fs.ReadFile, fs.Glob, template.ParseFS, http.FileServerFS. The result also implements fs.StatFS, fs.ReadFileFS, fs.ReadDirFS and fs.ReadLinkFS.
package main
import (
"fmt"
"io/fs"
"os"
"path/filepath"
)
func main() {
dir, err := os.MkdirTemp("", "fs-*")
if err != nil {
fmt.Println("error:", err)
return
}
defer os.RemoveAll(dir)
os.WriteFile(filepath.Join(filepath.Dir(dir), "outside.txt"), []byte("secret"), 0o644)
defer os.Remove(filepath.Join(filepath.Dir(dir), "outside.txt"))
root, err := os.OpenRoot(dir)
if err != nil {
fmt.Println("error:", err)
return
}
defer root.Close()
root.MkdirAll("css", 0o755)
root.WriteFile("index.html", []byte("<h1>Hi</h1>"), 0o644)
root.WriteFile("css/site.css", []byte("body{}"), 0o644)
root.Symlink("../outside.txt", "leak.txt")
fsys := root.FS()
fs.WalkDir(fsys, ".", func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
fmt.Printf("%-14s dir=%v\n", path, d.IsDir())
return nil
})
data, err := fs.ReadFile(fsys, "css/site.css")
fmt.Printf("css/site.css: %q %v\n", data, err)
_, err = fs.ReadFile(fsys, "leak.txt")
fmt.Println("leak.txt:", err)
// fs.FS rules: names must be unrooted, slash-separated, without ..
_, err = fs.ReadFile(fsys, "css/../index.html")
fmt.Println("css/../index.html:", err)
target, err := fs.ReadLink(fsys, "leak.txt")
fmt.Println("ReadLink leak.txt:", target, err)
}
. dir=true
css dir=true
css/site.css dir=false
index.html dir=false
leak.txt dir=false
css/site.css: "body{}" <nil>
leak.txt: openat leak.txt: path escapes from parent
css/../index.html: readfile css/../index.html: invalid argument
ReadLink leak.txt: ../outside.txt <nil>
fs.WalkDir lists the escaping symlink (it doesn't follow links), but reading it fails. Names passed to the fs.FS must follow the fs.ValidPath rules: slash-separated, no leading /, no . or .. elements. So css/../index.html is rejected by the fs.FS even though root.ReadFile would accept it.
Serving user-supplied paths over HTTP
http.FileServer and http.FileServerFS already reject .. in URLs, but they follow symlinks if the file system does. Compare os.DirFS with root.FS():
package main
import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
)
func main() {
base, err := os.MkdirTemp("", "web-*")
if err != nil {
fmt.Println("error:", err)
return
}
defer os.RemoveAll(base)
os.WriteFile(filepath.Join(base, "config.env"), []byte("DB_PASSWORD=hunter2"), 0o600)
public := filepath.Join(base, "public")
os.Mkdir(public, 0o755)
os.WriteFile(filepath.Join(public, "hello.txt"), []byte("hello"), 0o644)
// a symlink planted by a user who can upload or unpack files
os.Symlink("../config.env", filepath.Join(public, "leak.txt"))
root, err := os.OpenRoot(public)
if err != nil {
fmt.Println("error:", err)
return
}
defer root.Close()
mux := http.NewServeMux()
mux.Handle("/dirfs/", http.StripPrefix("/dirfs", http.FileServerFS(os.DirFS(public))))
mux.Handle("/root/", http.StripPrefix("/root", http.FileServerFS(root.FS())))
srv := httptest.NewServer(mux)
defer srv.Close()
for _, p := range []string{"/dirfs/hello.txt", "/dirfs/leak.txt", "/root/hello.txt", "/root/leak.txt"} {
resp, err := http.Get(srv.URL + p)
if err != nil {
fmt.Println("error:", err)
return
}
body, _ := io.ReadAll(resp.Body)
resp.Body.Close()
fmt.Printf("%-17s %d %q\n", p, resp.StatusCode, body)
}
}
/dirfs/hello.txt 200 "hello"
/dirfs/leak.txt 200 "DB_PASSWORD=hunter2"
/root/hello.txt 200 "hello"
/root/leak.txt 500 "500 Internal Server Error\n"
With os.DirFS the planted link leaks the config file. With root.FS() the request fails. The file server answers 500 rather than 404 because the escape error isn't fs.ErrNotExist or fs.ErrPermission. If you want a 404, wrap the handler or use your own handler that calls root.Open and maps any error to http.NotFound.
Extracting archives
Archive extraction is the classic case ("zip slip"): an entry named ../../.bashrc or /etc/cron.d/evil writes outside the target directory. ZIP archives shows how to guard against it with filepath.IsLocal. Doing every file operation through an os.Root gives the same protection, and also covers symlinks that already exist in the target directory:
package main
import (
"archive/zip"
"bytes"
"fmt"
"io"
"os"
"path"
)
const maxFileSize = 10 << 20 // 10 MB per file
// extract unpacks the archive into dir. Every file operation goes
// through os.Root, so no entry can write outside dir.
func extract(r *zip.Reader, dir string) error {
root, err := os.OpenRoot(dir)
if err != nil {
return err
}
defer root.Close()
for _, f := range r.File {
if err := extractEntry(root, f); err != nil {
fmt.Printf(" skip %-22s %v\n", f.Name, err)
continue
}
fmt.Printf(" ok %s\n", f.Name)
}
return nil
}
func extractEntry(root *os.Root, f *zip.File) error {
if f.FileInfo().IsDir() {
return root.MkdirAll(f.Name, 0o755)
}
if !f.Mode().IsRegular() {
return fmt.Errorf("not a regular file")
}
if err := root.MkdirAll(path.Dir(f.Name), 0o755); err != nil {
return err
}
src, err := f.Open()
if err != nil {
return err
}
defer src.Close()
// O_EXCL: never overwrite, and never write through an existing symlink
dst, err := root.OpenFile(f.Name, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o644)
if err != nil {
return err
}
n, err := io.Copy(dst, io.LimitReader(src, maxFileSize+1))
if cerr := dst.Close(); err == nil {
err = cerr
}
if err == nil && n > maxFileSize {
err = fmt.Errorf("file too large")
}
if err != nil {
root.Remove(f.Name)
}
return err
}
// makeZip builds an archive with a few hostile entries.
func makeZip() []byte {
var buf bytes.Buffer
w := zip.NewWriter(&buf)
for _, name := range []string{
"site/index.html",
"site/img/",
"site/img/logo.png",
"../../evil.txt",
"/etc/cron.d/evil",
"site/../../evil2.txt",
} {
fw, _ := w.Create(name)
fw.Write([]byte("data for " + name))
}
w.Close()
return buf.Bytes()
}
func main() {
dir, err := os.MkdirTemp("", "extract-*")
if err != nil {
fmt.Println("error:", err)
return
}
defer os.RemoveAll(dir)
data := makeZip()
r, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Println("extracting:")
extract(r, dir)
}
extracting:
ok site/index.html
ok site/img/
ok site/img/logo.png
skip ../../evil.txt mkdirat ../..: path escapes from parent
skip /etc/cron.d/evil mkdirat /etc/cron.d: path escapes from parent
skip site/../../evil2.txt mkdirat ..: path escapes from parent
ZIP entry names always use /, so the code uses path.Dir, not filepath.Dir. os.Root accepts / as a separator on every platform, including Windows.
Using os.Root doesn't make the other checks unnecessary:
- skip symlinks and other special entries in untrusted archives (
f.Mode().IsRegular()) - limit the size of each file and the total size, to defend against zip bombs
- limit the number of entries
os.Root vs filepath.IsLocal
Both deal with untrusted paths, but they work on different levels:
filepath.IsLocal |
os.Root |
|
|---|---|---|
| what it checks | the string only | each path component on disk |
.. and absolute paths |
rejected | rejected |
reserved Windows names (NUL, COM1) |
rejected | rejected |
| symlinks pointing outside | not detected | rejected |
| race between check and use | possible | no |
| touches the file system | no | yes |
| available since | Go 1.20 | Go 1.24 (more methods in 1.25) |
filepath.IsLocal is still useful as a cheap first step: it lets you reject an obviously bad name with a clear error message (for example 400 Bad Request) before touching the disk. Then use os.Root for the actual file operations. filepath.Localize (Go 1.23) converts a slash-separated fs.FS style path to a local OS path and returns an error for names that fs.ValidPath rejects, such as ones containing ... See File path operations for the rest of path/filepath and Application security for path traversal among other common vulnerabilities.
Platform notes and limitations
On Linux, macOS and Windows a Root references the open directory, not its name. If the directory is renamed, the root follows it:
package main
import (
"fmt"
"os"
"path/filepath"
)
func main() {
base, err := os.MkdirTemp("", "move-*")
if err != nil {
fmt.Println("error:", err)
return
}
defer os.RemoveAll(base)
oldDir := filepath.Join(base, "old")
os.Mkdir(oldDir, 0o755)
root, err := os.OpenRoot(oldDir)
if err != nil {
fmt.Println("error:", err)
return
}
defer root.Close()
// someone renames the directory and puts a new one in its place
newDir := filepath.Join(base, "new")
os.Rename(oldDir, newDir)
os.Mkdir(oldDir, 0o755)
root.WriteFile("file.txt", []byte("x"), 0o644)
_, err = os.Stat(filepath.Join(newDir, "file.txt"))
fmt.Println("file in new:", err == nil)
_, err = os.Stat(filepath.Join(oldDir, "file.txt"))
fmt.Println("file in old:", err == nil)
fmt.Println("root.Name():", filepath.Base(root.Name()))
}
file in new: true
file in old: false
root.Name(): old
root.Name() still returns the original name, but the file was written to the directory that was renamed, not to the new old directory that took its place.
On Windows, os.Root accepts both \ and / and rejects drive letters and reserved device names:
package main
import (
"fmt"
"os"
)
func main() {
dir, _ := os.MkdirTemp("", "win-*")
defer os.RemoveAll(dir)
root, err := os.OpenRoot(dir)
if err != nil {
fmt.Println(err)
return
}
defer root.Close()
root.Mkdir("docs", 0o755)
for _, name := range []string{`docs\a.txt`, `docs/b.txt`, `..\x.txt`, `C:\Windows\x.txt`, `NUL`} {
err := root.WriteFile(name, []byte("x"), 0o644)
fmt.Printf("%-20s %v\n", name, err)
}
}
docs\a.txt <nil>
docs/b.txt <nil>
..\x.txt openat ..\x.txt: path escapes from parent
C:\Windows\x.txt openat C:\Windows\x.txt: path escapes from parent
NUL openat NUL: path escapes from parent
Things os.Root doesn't protect against:
- crossing file system boundaries: mount points and Linux bind mounts inside the root are followed
- special files:
/procentries and device files inside the root can still be opened - hard links: a hard link inside the root to a file outside it is just a regular file
- on
GOOS=jssymlink checks are racy and onjsandplan9the root tracks the directory by name, not by handle wasip1doesn't supportRoot.Chmod
os.Root is not a sandbox for untrusted code. It's a tool for your own code that handles untrusted names. If the attacker can run code as your user, they don't need path tricks.
Common mistakes
- Joining paths before using the root.
root.Open(filepath.Join(root.Name(), name))passes an absolute path, which the root rejects. Pass the relative name. - Mixing os functions with the root. One stray
os.Remove(filepath.Join(dir, name))reopens the hole. Route every operation on untrusted names through theRoot. - Using os.DirFS as a security boundary. It follows symlinks out of the directory. Use
root.FS(). - Opening the root on every request. Open it once and share it; it's safe for concurrent use.
- Forgetting to close it. A
Rootholds a file descriptor untilClose. - Expecting absolute symlinks to work. Even links that point inside the root must be relative.
Summary
os.OpenRoot(dir)returns a*os.Rootwhose methods only access files underdir..above the root, absolute paths and symlinks pointing outside are rejected withpath escapes from parent- methods mirror package
os:Open,Create,OpenFile,ReadFile,WriteFile,MkdirAll,Rename,RemoveAlland more (most of them since Go 1.25) os.OpenInRoot(dir, name)opens a single file in one callroot.OpenRoot(sub)narrows access to a subdirectoryroot.FS()is anfs.FSthat can't escape, unlikeos.DirFS- use it for uploads, archive extraction and any path that comes from outside your program; combine it with
filepath.IsLocalfor early validation and clear error messages