Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 12 additions & 5 deletions SECURITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,18 @@ that help us get there are very welcome.

Thanks to the people who've reported security issues in tailcat:

* [Will Frame](https://wpf.nz/) reported that write-only (`:wo`) file
shares, as used by `tailcat recv`, weren't actually write-only in
0.4.0: it let senders enumerate the directory or write over
existing files. Fixed in
[d796f883e](https://github.com/tailscale/tailcat/commit/d796f883e5ec8b17f6c4196276fad65646d101f5).
* [Will Frame](https://wpf.nz/) reported two rounds of issues with
write-only (`:wo`) file shares (drop boxes), as used by
`tailcat recv`:
* In 0.4.0, senders could write over existing files, and could test
whether a guessed filename existed by how opening it behaved.
Fixed in
[d796f883e](https://github.com/tailscale/tailcat/commit/d796f883e5ec8b17f6c4196276fad65646d101f5).
* That fix left narrower ways to test guessed names: exclusive
creation failed on a collision, and directories could be stat'd.
Fixed by storing each upload under a server-chosen name and
making directory support a separate opt-in
(`tailcat recv --accept-dirs`).
* [Matt Andreko](https://www.mattandreko.com/) reported two issues
with how untrusted tailcat addresses are handled. Both are mostly
attacking-yourself issues today, but they matter for automation, or
Expand Down
21 changes: 21 additions & 0 deletions cmd/tailcat/cli_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (

"github.com/peterbourgon/ff/v4"
"github.com/peterbourgon/ff/v4/ffhelp"
"github.com/tailscale/tailcat"
)

func TestClassifyAddrBlobArg(t *testing.T) {
Expand Down Expand Up @@ -97,6 +98,26 @@ func TestServeHelpListsServerFlags(t *testing.T) {
}
}

func TestParseFilesFlagWriteOnlyModes(t *testing.T) {
dir := t.TempDir()
for _, tt := range []struct {
suffix string
wantMode tailcat.FileServeMode
wantName string
}{
{":wo", tailcat.FileServeWO, "flat write-only"},
{":wo+", tailcat.FileServeWOPlus, "recursive write-only"},
} {
fs, modeName, err := parseFilesFlag(dir + tt.suffix)
if err != nil {
t.Fatalf("parseFilesFlag(%q): %v", tt.suffix, err)
}
if fs.Dir != dir || fs.Mode != tt.wantMode || modeName != tt.wantName {
t.Errorf("parseFilesFlag(%q) = {%q, %v}, %q; want {%q, %v}, %q", tt.suffix, fs.Dir, fs.Mode, modeName, dir, tt.wantMode, tt.wantName)
}
}
}

// parseCLI parses args against a fresh command tree and returns the
// root command. It doesn't run anything.
func parseCLI(t *testing.T, args ...string) (root *ff.Command, err error) {
Expand Down
9 changes: 8 additions & 1 deletion cmd/tailcat/cp_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,14 @@ func TestRecvDropBox(t *testing.T) {
if err != nil {
t.Fatalf("cp into recv: %v\n%s", err, out)
}
v, err := os.ReadFile(filepath.Join(recvDir, "gift.txt"))
matches, err := filepath.Glob(filepath.Join(recvDir, "gift.*.txt"))
if err != nil {
t.Fatal(err)
}
if len(matches) != 1 {
t.Fatalf("received files = %q; want one timestamped gift file", matches)
}
v, err := os.ReadFile(matches[0])
if err != nil {
t.Fatal(err)
}
Expand Down
28 changes: 20 additions & 8 deletions cmd/tailcat/tailcat.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,9 +95,10 @@ func newRootCommand() *ff.Command {
serveFS := ff.NewFlagSet("serve").SetParent(rootFS)
flagAllow = serveFS.StringLong("allow", "", "comma-separated list of public keys to allow access to the server, or 'none' to allow no clients. If empty, all clients are allowed.")
flagFullAddress = serveFS.BoolLong("full-address", "print a longer connection address token with embedded DERP server info instead of a reference to a DERP map region ID. This lets clients connect more quickly, without a DERP map fetch.")
flagFiles = serveFS.StringLong("files", "", "directory to serve to SFTP clients (scp, sftp) with the 'files' service, with an optional :ro (read-only, the default), :rw (read-write), or :wo (write-only drop box) suffix. If empty, the current directory is served read-only. Giving --files implies the 'files' service.")
flagFiles = serveFS.StringLong("files", "", "directory to serve to SFTP clients (scp, sftp) with the 'files' service, with an optional :ro (read-only, the default), :rw (read-write), :wo (flat write-only drop box), or :wo+ (recursive write-only drop box) suffix. If empty, the current directory is served read-only. Giving --files implies the 'files' service.")

recvFS := ff.NewFlagSet("recv").SetParent(serveFS)
flagRecvAcceptDirs := recvFS.BoolLong("accept-dirs", "accept directory trees (tailcat cp -r), keeping requested file names when available. The trade-off: senders can then make and stat directories and learn whether some names already exist in the drop box. The default flat mode reveals nothing about existing files, but accepts only single files, each saved under a server-chosen unique name.")

pingFS := ff.NewFlagSet("ping").SetParent(rootFS)
pingUntilDirect := pingFS.BoolLong("until-direct", "keep pinging until a pong arrives over a direct (non-DERP) path; exit non-zero if that doesn't happen before --timeout")
Expand Down Expand Up @@ -182,7 +183,11 @@ func newRootCommand() *ff.Command {
if len(args) == 1 {
dir = args[0]
}
*flagFiles = dir + ":wo"
mode := ":wo"
if *flagRecvAcceptDirs {
mode = ":wo+"
}
*flagFiles = dir + mode
server(getLogf(), "")
return nil
},
Expand Down Expand Up @@ -429,10 +434,12 @@ Serve the current directory read-only to scp and sftp clients:

tailcat serve files

Serve a directory read-write, or another as a write-only drop box:
Serve a directory read-write, as a flat write-only drop box, or as a
recursive write-only drop box:

tailcat serve --files=/pub:rw files
tailcat serve --files=/inbox:wo files
tailcat serve --files=/tree-inbox:wo+ files

Serve with a saved key (see genkey) and restrict clients:

Expand All @@ -453,9 +460,12 @@ The sender copies files in with (see "tailcat cp --help"):

tailcat cp foo.txt <addrblob>:

Write-only means senders can't list the directory, read anything
back, or touch existing files, so the address blob only grants
dropping files off.
Write-only means senders can't make directories, list or read the
directory, touch existing files, or learn whether a requested filename
already exists. Each upload is saved under a new name containing a UTC
timestamp and random suffix, so the address blob only grants dropping
files off. To accept directory trees instead, use the less-private
--accept-dirs flag; see its description for the trade-off.

Receive into the current directory, or into a given one:

Expand Down Expand Up @@ -1337,7 +1347,7 @@ func server(logf logger.Logf, serveSpec string) {
}

// parseFilesFlag parses the --files flag value: a directory with an
// optional :ro, :rw, or :wo suffix. An empty value means the current
// optional :ro, :rw, :wo, or :wo+ suffix. An empty value means the current
// directory, read-only. It returns the file service and the mode's
// human-readable name.
func parseFilesFlag(v string) (*tailcat.FileService, string, error) {
Expand All @@ -1347,8 +1357,10 @@ func parseFilesFlag(v string) (*tailcat.FileService, string, error) {
dir = d
} else if d, ok := strings.CutSuffix(v, ":rw"); ok {
dir, mode, modeName = d, tailcat.FileServeRW, "read-write"
} else if d, ok := strings.CutSuffix(v, ":wo+"); ok {
dir, mode, modeName = d, tailcat.FileServeWOPlus, "recursive write-only"
} else if d, ok := strings.CutSuffix(v, ":wo"); ok {
dir, mode, modeName = d, tailcat.FileServeWO, "write-only"
dir, mode, modeName = d, tailcat.FileServeWO, "flat write-only"
}
if dir == "" {
dir = "."
Expand Down
16 changes: 10 additions & 6 deletions tailcat_files.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,17 @@ const (
// FileServeRW serves files read-write.
FileServeRW

// FileServeWO serves files write-only, as a drop box: clients can
// upload files and make directories, but can't list the directory
// or read anything back. Paths a connection created itself may
// still be stat'd, so upload tools that verify their writes keep
// working; directories may be stat'd too, so upload destinations
// resolve.
// FileServeWO serves files write-only, as a flat drop box. Each upload
// is stored under a new, server-chosen name, so clients can't use name
// collisions to discover existing files. Clients can't make directories,
// list the drop box, or read anything back.
FileServeWO

// FileServeWOPlus serves files write-only, as a recursive drop box.
// Clients can make and stat directories, which necessarily reveals some
// information about existing paths. An upload keeps its requested name
// when available and is stored under a new, server-chosen name otherwise.
FileServeWOPlus
)

// FileService describes a rooted SFTP file service. All client paths
Expand Down
122 changes: 88 additions & 34 deletions tailcat_sftp.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
package tailcat

import (
"crypto/rand"
"encoding/hex"
"errors"
"io"
"os"
Expand Down Expand Up @@ -106,8 +108,11 @@ type rootedFiles struct {
root *os.Root
mode FileServeMode

mu sync.Mutex
wrote map[string]bool // rooted paths this session created or wrote, for FileServeWO stats
mu sync.Mutex
// wrote maps client-visible paths to the paths actually created by this
// session. Drop-box modes use it for post-upload stats and setstats without
// revealing server-chosen names.
wrote map[string]string
}

// rel converts a cleaned absolute SFTP request path ("/foo/bar") to
Expand All @@ -120,28 +125,31 @@ func rel(requestPath string) string {
return p
}

// markOwn records that this session wrote or created the rooted path
// p, allowing later stats of it in write-only mode.
func (h *rootedFiles) markOwn(p string) {
// markOwn records that this session created requestedPath at actualPath.
func (h *rootedFiles) markOwn(requestedPath, actualPath string) {
h.mu.Lock()
defer h.mu.Unlock()
if h.wrote == nil {
h.wrote = make(map[string]bool)
h.wrote = make(map[string]string)
}
h.wrote[p] = true
h.wrote[requestedPath] = actualPath
}

// isOwn reports whether this session wrote or created the rooted
// path p.
func (h *rootedFiles) isOwn(p string) bool {
// ownPath returns the actual path created for client-visible path p.
func (h *rootedFiles) ownPath(p string) (string, bool) {
h.mu.Lock()
defer h.mu.Unlock()
return h.wrote[p]
actual, ok := h.wrote[p]
return actual, ok
}

func (h *rootedFiles) writeOnly() bool {
return h.mode == FileServeWO || h.mode == FileServeWOPlus
}

// Fileread implements [sftp.FileReader] (the SFTP Get method).
func (h *rootedFiles) Fileread(r *sftp.Request) (io.ReaderAt, error) {
if h.mode == FileServeWO {
if h.writeOnly() {
return nil, sftp.ErrSSHFxPermissionDenied
}
return h.root.Open(rel(r.Filepath))
Expand All @@ -154,20 +162,39 @@ func (h *rootedFiles) Filewrite(r *sftp.Request) (io.WriterAt, error) {
return nil, sftp.ErrSSHFxPermissionDenied
}
pflags := r.Pflags()
if h.mode == FileServeWO {
if h.writeOnly() {
// A drop box only accepts creation of new files. Requiring the
// client to ask for creation makes a plain write-only open fail
// the same way whether its path exists or not; forcing exclusive
// creation makes the no-overwrite check atomic.
if pflags.Read || !pflags.Write || !pflags.Creat {
return nil, sftp.ErrSSHFxPermissionDenied
}
p := rel(r.Filepath)
f, err := h.root.OpenFile(p, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0644)
requestedPath := rel(r.Filepath)
if h.mode == FileServeWO && (requestedPath == "." || strings.Contains(requestedPath, "/")) {
return nil, sftp.ErrSSHFxPermissionDenied
}

actualPath := requestedPath
var err error
if h.mode == FileServeWO {
actualPath, err = uniqueUploadPath(requestedPath)
if err != nil {
return nil, err
}
}
f, err := h.root.OpenFile(actualPath, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0644)
if h.mode == FileServeWOPlus && errors.Is(err, os.ErrExist) {
actualPath, err = uniqueUploadPath(requestedPath)
if err != nil {
return nil, err
}
f, err = h.root.OpenFile(actualPath, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0644)
}
if err != nil {
return nil, err
}
h.markOwn(p)
h.markOwn(requestedPath, actualPath)
return f, nil
}
flags := os.O_WRONLY
Expand All @@ -194,30 +221,52 @@ func (h *rootedFiles) Filewrite(r *sftp.Request) (io.WriterAt, error) {
return f, nil
}

// uniqueUploadPath returns a server-chosen sibling of requestedPath. It uses
// enough randomness that OpenFile can make exactly one atomic O_EXCL attempt;
// a collision or random-source failure is returned rather than retried.
func uniqueUploadPath(requestedPath string) (string, error) {
var random [8]byte
if _, err := io.ReadFull(rand.Reader, random[:]); err != nil {
return "", err
}
base := path.Base(requestedPath)
ext := path.Ext(base)
stem := strings.TrimSuffix(base, ext)
uniqueBase := stem + "." + time.Now().UTC().Format("20060102150405") + "." + hex.EncodeToString(random[:]) + ext
if dir := path.Dir(requestedPath); dir != "." {
return path.Join(dir, uniqueBase), nil
}
return uniqueBase, nil
}

// Filecmd implements [sftp.FileCmder] (the SFTP Setstat, Rename,
// Rmdir, Mkdir, Link, Symlink, and Remove methods).
func (h *rootedFiles) Filecmd(r *sftp.Request) error {
p := rel(r.Filepath)
switch h.mode {
case FileServeRO:
return sftp.ErrSSHFxPermissionDenied
case FileServeWO:
// A drop box accepts new files and directories and lets a
// session adjust what it itself wrote (SFTP clients commonly
// follow an upload with Setstat to fix up permissions or
// times), but can't touch anything else.
case FileServeWO, FileServeWOPlus:
// A drop box lets a session adjust what it itself wrote (SFTP
// clients commonly follow an upload with Setstat to fix up
// permissions or times), but can't touch anything else. Only the
// recursive mode accepts directories.
switch r.Method {
case "Mkdir":
if h.mode == FileServeWO {
return sftp.ErrSSHFxPermissionDenied
}
if err := h.root.Mkdir(p, 0755); err != nil {
return err
}
h.markOwn(p)
h.markOwn(p, p)
return nil
case "Setstat":
if !h.isOwn(p) {
actualPath, ok := h.ownPath(p)
if !ok {
return sftp.ErrSSHFxPermissionDenied
}
return h.setstat(r, p)
return h.setstat(r, actualPath)
}
return sftp.ErrSSHFxPermissionDenied
}
Expand Down Expand Up @@ -278,7 +327,7 @@ func (h *rootedFiles) Filelist(r *sftp.Request) (sftp.ListerAt, error) {
p := rel(r.Filepath)
switch r.Method {
case "List":
if h.mode == FileServeWO {
if h.writeOnly() {
return nil, sftp.ErrSSHFxPermissionDenied
}
f, err := h.root.Open(p)
Expand Down Expand Up @@ -312,22 +361,27 @@ func (h *rootedFiles) Lstat(r *sftp.Request) (sftp.ListerAt, error) {

// Readlink implements [sftp.ReadlinkFileLister].
func (h *rootedFiles) Readlink(requestPath string) (string, error) {
if h.mode == FileServeWO {
if h.writeOnly() {
return "", sftp.ErrSSHFxPermissionDenied
}
return h.root.Readlink(rel(requestPath))
}

// stat stats the rooted path p with statf (Stat or Lstat), applying
// the write-only mode's visibility policy: a write-only session may
// stat paths it wrote itself and directories (so upload destinations
// resolve), but everything else reports not-exist, whether or not it
// exists, so filenames can't be probed.
// stat stats the rooted path p with statf, applying the drop-box visibility
// policy. Both modes expose paths this session created. Strict write-only mode
// otherwise exposes only the root; write-only-plus also exposes directories so
// recursive upload destinations can resolve.
func (h *rootedFiles) stat(p string, statf func(string) (os.FileInfo, error)) (os.FileInfo, error) {
fi, err := statf(p)
if h.mode != FileServeWO || h.isOwn(p) {
return fi, err
if !h.writeOnly() {
return statf(p)
}
if actualPath, ok := h.ownPath(p); ok {
return statf(actualPath)
}
if h.mode == FileServeWO && p != "." {
return nil, sftp.ErrSSHFxNoSuchFile
}
fi, err := statf(p)
if err != nil || !fi.IsDir() {
return nil, sftp.ErrSSHFxNoSuchFile
}
Expand Down
Loading