ipn/ipnlocal: don't follow symlinks out of served directories (#22215)

When a Serve or Funnel handler serves a path, serveFileOrDirectory
used os.Stat and os.Open on it, and http.FileServer(http.Dir(dir)) for
a directory. All of these follow symlinks, so a symlink in place of a
served file or directory, or inside a served directory, could make
tailscaled serve any file it can read from elsewhere on the host.
Those directories may be writable by local users who can't configure
Serve, and a symlink placed there is followed at request time.

Resolve the configured path through an os.Root of its parent
directory, and serve a directory through an os.Root of its own.
os.Root refuses symlinks whose target leaves the root, and absolute
symlinks, and still follows relative symlinks that stay inside it. A
refused path inside a served directory is reported as not found, like
a missing file. A refused configured path is logged and reported as a
server error, like other errors reading it.

This changes behavior for setups that serve such symlinks on purpose,
including absolute symlinks and Windows junctions: a configured file
or directory that is one, or that points out of its parent directory,
now fails, and such links inside a served directory now return 404.
Symlinks higher up the configured path are still followed, and a
filesystem root can still be served. Opening the parent directory
needs read permission on it, where os.Stat only needed search
permission. Hardlinks are not covered, since os.Root can't tell them
apart from regular files.

RELNOTE: tailscale serve stops following symlinks out of served directories

Updates tailscale/corp#51116

Signed-off-by: Aditya Merchant <adityamerchant08@gmail.com>
This commit is contained in:
Aditya Merchant authored and GitHub committed 2026-11-09 12:15:34 -07:00
1 parent d1570617f6
commit c38365bcff
2 files changed
+238 -3

No files matched your search

+76 -3
View File
@@ -25,6 +25,7 @@ import (
"net/url"
"os"
"path"
"path/filepath"
"slices"
"strconv"
"strings"
@@ -1322,7 +1323,20 @@ func (b *LocalBackend) serveWebHandler(w http.ResponseWriter, r *http.Request) {
}
func (b *LocalBackend) serveFileOrDirectory(w http.ResponseWriter, r *http.Request, fileOrDir, mountPoint string) {
fi, err := os.Stat(fileOrDir)
// The directory that contains fileOrDir, and fileOrDir itself if it's a
// directory, may be writable by users who can't configure Serve.
// os.Stat, os.Open and http.Dir all follow symlinks, so such a user could
// make tailscaled serve any file it can read. Instead, resolve fileOrDir
// through an os.Root of its parent directory, and serve a directory
// through an os.Root of its own. An os.Root refuses symlinks whose target
// leaves the root, and absolute symlinks, but still follows relative
// symlinks that stay inside it.
parent, name, err := openParentRoot(fileOrDir)
var fi os.FileInfo
if err == nil {
defer parent.Close()
fi, err = parent.Stat(name)
}
if err != nil {
if os.IsNotExist(err) {
http.NotFound(w, r)
@@ -1337,7 +1351,7 @@ func (b *LocalBackend) serveFileOrDirectory(w http.ResponseWriter, r *http.Reque
http.NotFound(w, r)
return
}
f, err := os.Open(fileOrDir)
f, err := parent.Open(name)
if err != nil {
b.logf("error opening %s: %v", fileOrDir, err)
http.Error(w, "an error occurred reading the file or directory", 500)
@@ -1356,7 +1370,15 @@ func (b *LocalBackend) serveFileOrDirectory(w http.ResponseWriter, r *http.Reque
return
}
var fs http.Handler = http.FileServer(http.Dir(fileOrDir))
root, err := parent.OpenRoot(name)
if err != nil {
b.logf("error opening %s: %v", fileOrDir, err)
http.Error(w, "an error occurred reading the file or directory", 500)
return
}
defer root.Close()
var fs http.Handler = http.FileServer(confinedDir{root})
if mountPoint != "/" {
fs = http.StripPrefix(strings.TrimSuffix(mountPoint, "/"), fs)
}
@@ -1367,6 +1389,57 @@ func (b *LocalBackend) serveFileOrDirectory(w http.ResponseWriter, r *http.Reque
}, r)
}
// openParentRoot opens the directory that contains p as an os.Root, and
// returns it with the name of p's last element inside it. A filesystem root
// has no parent, so for one it returns an os.Root of p itself, and ".".
func openParentRoot(p string) (parent *os.Root, name string, err error) {
p = filepath.Clean(p)
dir := filepath.Dir(p)
name = filepath.Base(p)
if dir == p {
name = "."
}
parent, err = os.OpenRoot(dir)
return parent, name, err
}
// confinedDir is an http.FileSystem like http.Dir, except that it opens files
// through an os.Root, so a symlink whose target leaves the root, or an
// absolute symlink, is refused instead of followed.
//
// It isn't http.FS(root.FS()) because that would report a refused symlink as
// a server error rather than as not found.
type confinedDir struct {
root *os.Root
}
// Open implements http.FileSystem.
func (d confinedDir) Open(name string) (http.File, error) {
// Turn the name into a path relative to the root the same way http.Dir
// does, including its check for names that aren't valid local paths.
rel := path.Clean("/" + name)[1:]
if rel == "" {
rel = "."
}
rel, err := filepath.Localize(rel)
if err != nil {
// http.Dir reports these as not found, too.
return nil, os.ErrNotExist
}
f, err := d.root.Open(rel)
if err != nil {
// os.Root reports a path that leaves the root with an error that is
// neither ErrNotExist nor ErrPermission. Report that, and any other
// unexpected error, as not found, so a refused path is neither
// served nor confirmed to exist.
if !errors.Is(err, os.ErrNotExist) && !errors.Is(err, os.ErrPermission) {
return nil, os.ErrNotExist
}
return nil, err
}
return f, nil
}
// fixLocationHeaderResponseWriter is an http.ResponseWriter wrapper that, upon
// flushing HTTP headers, rewrites any Location header to be under the mount
// point. http.FileServer sends redirects relative to the (prefix-stripped)
+162
View File
@@ -23,6 +23,7 @@ import (
"os"
"path/filepath"
"reflect"
"runtime"
"slices"
"strconv"
"strings"
@@ -1517,6 +1518,167 @@ func TestServeFileOrDirectory(t *testing.T) {
}
}
// newSymlinkServeTree creates a directory to serve, webroot, next to a
// directory, outside, whose file secret.txt must never be served, and
// returns the path to webroot. Besides a file and a subdirectory, webroot
// holds symlinks that lead out of it and symlinks that stay inside it.
func newSymlinkServeTree(t *testing.T) (root string) {
t.Helper()
base := t.TempDir()
root = filepath.Join(base, "webroot")
outside := filepath.Join(base, "outside")
for _, d := range []string{root, outside, filepath.Join(root, "sub")} {
if err := os.MkdirAll(d, 0o755); err != nil {
t.Fatal(err)
}
}
mustWrite := func(p, s string) {
t.Helper()
if err := os.WriteFile(p, []byte(s), 0o600); err != nil {
t.Fatal(err)
}
}
mustWrite(filepath.Join(root, "inside.txt"), "INSIDE-OK")
mustWrite(filepath.Join(root, "sub", "nested.txt"), "NESTED-OK")
mustWrite(filepath.Join(outside, "secret.txt"), "TOP-SECRET")
mustSymlink := func(target, linkName string) {
t.Helper()
if err := os.Symlink(target, filepath.Join(root, linkName)); err != nil {
if runtime.GOOS == "windows" {
t.Skipf("can't create symlinks: %v", err)
}
t.Fatal(err)
}
}
// os.Root refuses symlinks whose target leaves the root, and absolute
// symlinks even when they point inside the root, but follows relative
// symlinks that stay inside it.
mustSymlink("../outside", "escape-rel-dir")
mustSymlink("../outside/secret.txt", "escape-rel-file")
mustSymlink(filepath.Join(outside, "secret.txt"), "escape-abs")
mustSymlink(filepath.Join(root, "sub", "nested.txt"), "inroot-abs")
mustSymlink("sub/nested.txt", "inroot-rel")
mustSymlink("sub", "inroot-rel-dir")
return root
}
// TestServeFileOrDirectoryConfinesSymlinks verifies that a served directory
// doesn't follow symlinks that lead out of it, while files, subdirectories
// and relative symlinks that stay inside it are still served.
func TestServeFileOrDirectoryConfinesSymlinks(t *testing.T) {
root := newSymlinkServeTree(t)
b := &LocalBackend{
logf: t.Logf,
health: health.NewTracker(eventbustest.NewBus(t)),
}
mounts := []struct {
name string
mount string
}{
{"root-mount", "/"},
{"sub-mount", "/files/"},
}
tests := []struct {
name string
path string // request path, relative to the mount point
wantStatus int
wantBody string
}{
{"file", "inside.txt", 200, "INSIDE-OK"},
{"nested-file", "sub/nested.txt", 200, "NESTED-OK"},
{"relative-in-root-symlink", "inroot-rel", 200, "NESTED-OK"},
{"relative-in-root-dir-symlink", "inroot-rel-dir/nested.txt", 200, "NESTED-OK"},
{"escaping-dir-symlink", "escape-rel-dir/secret.txt", 404, ""},
{"escaping-file-symlink", "escape-rel-file", 404, ""},
{"absolute-symlink", "escape-abs", 404, ""},
{"absolute-in-root-symlink", "inroot-abs", 404, ""},
}
for _, m := range mounts {
t.Run(m.name, func(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
rec := httptest.NewRecorder()
req := httptest.NewRequest("GET", m.mount+tt.path, nil)
b.serveFileOrDirectory(rec, req, root, m.mount)
checkServeResponse(t, rec, req, tt.wantStatus, tt.wantBody)
})
}
})
}
}
// TestServeFileOrDirectoryConfinesTarget verifies that the configured path
// itself, a single file or a directory, is resolved inside the directory
// that contains it: a symlink there that leads out of that directory, or an
// absolute one, is refused, while a relative symlink that stays inside it
// is still served.
func TestServeFileOrDirectoryConfinesTarget(t *testing.T) {
root := newSymlinkServeTree(t)
b := &LocalBackend{
logf: t.Logf,
health: health.NewTracker(eventbustest.NewBus(t)),
}
tests := []struct {
name string
target string // configured path, relative to root
mount string
req string
wantStatus int
wantBody string
}{
{"file", "inside.txt", "/f", "/f", 200, "INSIDE-OK"},
{"relative-in-parent-file-symlink", "inroot-rel", "/f", "/f", 200, "NESTED-OK"},
{"escaping-file-symlink", "escape-rel-file", "/f", "/f", 500, ""},
{"absolute-file-symlink", "escape-abs", "/f", "/f", 500, ""},
{"absolute-in-parent-file-symlink", "inroot-abs", "/f", "/f", 500, ""},
{"dir", "sub", "/files/", "/files/nested.txt", 200, "NESTED-OK"},
{"relative-in-parent-dir-symlink", "inroot-rel-dir", "/files/", "/files/nested.txt", 200, "NESTED-OK"},
{"escaping-dir-symlink", "escape-rel-dir", "/files/", "/files/secret.txt", 500, ""},
// A single file swapped for a symlink to a directory must not turn
// its mount point into a listing of that directory.
{"file-mount-escaping-dir-symlink", "escape-rel-dir", "/f", "/f/secret.txt", 500, ""},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
rec := httptest.NewRecorder()
req := httptest.NewRequest("GET", tt.req, nil)
b.serveFileOrDirectory(rec, req, filepath.Join(root, tt.target), tt.mount)
checkServeResponse(t, rec, req, tt.wantStatus, tt.wantBody)
})
}
// A filesystem root has no parent directory to resolve it in, so it is
// opened as is.
t.Run("filesystem-root", func(t *testing.T) {
rec := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/", nil)
b.serveFileOrDirectory(rec, req, string(filepath.Separator), "/")
if rec.Code != 200 {
t.Errorf("GET %s: status = %d; want 200 (body: %q)", req.URL.Path, rec.Code, rec.Body.String())
}
})
}
// checkServeResponse reports an error if rec, the response to req, doesn't
// have the status wantStatus and a body containing wantBody, or if it served
// the secret file from outside the tree made by newSymlinkServeTree.
func checkServeResponse(t *testing.T, rec *httptest.ResponseRecorder, req *http.Request, wantStatus int, wantBody string) {
t.Helper()
body := rec.Body.String()
if rec.Code != wantStatus {
t.Errorf("GET %s: status = %d; want %d (body: %q)", req.URL.Path, rec.Code, wantStatus, body)
}
if !strings.Contains(body, wantBody) {
t.Errorf("GET %s: body = %q; want it to contain %q", req.URL.Path, body, wantBody)
}
if strings.Contains(body, "TOP-SECRET") {
t.Errorf("GET %s: served a file from outside the root", req.URL.Path)
}
}
func Test_isGRPCContentType(t *testing.T) {
tests := []struct {
contentType string