Skip to content

client: replace custom CPU9P with hugelgupf/p9/fsimpl/localfs - #337

Open
brho wants to merge 3 commits into
u-root:mainfrom
brho:namespace-filter-localfs
Open

brho wants to merge 3 commits into
u-root:mainfrom
brho:namespace-filter-localfs

Conversation

@brho

@brho brho commented Nov 13, 2026 •

Copy link
Copy Markdown
Collaborator

Replaces the client's forked CPU9P implementation with github.com/hugelgupf/p9/fsimpl/localfs, fixes Cmd.Start/Close I/O races, and cleans up static test keys and daemon test races.

The -namespace export filtering (filter9p, NewFilterFS, -unsafe-export, and export-isolation tests) was split out to brho/cpu:namespace-filter while generic 9P server and localfs confinement fixes land upstream in hugelgupf/p9#137 and hugelgupf/p9#138 (once merged, go.mod here can bump to that p9 revision).

Commits (25e47fef..28360906)

  1. 25e47fef — client: replace custom CPU9P with hugelgupf/p9/fsimpl/localfs
    • Drops the local CPU9P copy (client/cpu9p*.go, client/getattr_*.go, client/cpu_*.go) in favor of github.com/hugelgupf/p9/fsimpl/localfs (gaining {dev, ino} QID collision avoidance and SetAttr/WriteAt/Readdir/Lock parity), and bumps go.mod to go 1.26.0.
    • Narrows NewCPU9P(root) to return p9.Attacher (failing closed on empty root, unconditionally setting unix.O_NOCTTY on Unix, translating 9P2000.L wire open flags to host os.OpenFile flags across OSes/architectures, and returning EXDEV on cross-implementation Link/RenameAt), and moves default c.fileServer init from Cmd.Start to Cmd.Dial.
  2. ccb73978 — client: fix Cmd.Start/Close I/O races and stderr close bug
    • Removes duplicate c.SessionIn.Close() closer (fixing x/crypto/ssh sentEOF race), evaluates verbose() synchronously before spawning stdout/stderr goroutines, and fixes !sameFD(c.Stderr, os.Stderr).
  3. 28360906 — server: use ephemeral SSH keys and fix daemon test races
    • Removes embedded static SSH keys (server/key.go) and generates ephemeral Ed25519 keys per test (0600) in server/server_linux_test.go.
    • Fixes TestDaemonSession, TestDaemonConnect, TestMain, and SSH server/handler teardown synchronization (serveTestSSH, setTestVerbose).

Testing

  • GOWORK=off go test -race -count=1 ./client/... ./cmds/... ./mount/... ./server/... ./session/... ./vm/...: PASS (unprivileged/tool-gated subtests skip as expected; untouched ds package has a pre-existing -race issue on upstream/main)
  • GOWORK=off go vet ./...: PASS
  • Cross-OS go vet ./client ./cmds/decpu and go test -c ./client for windows/amd64, darwin/amd64, and freebsd/amd64: PASS

@brho
brho requested a review from rminnich November 13, 2026 22:59
@rminnich
rminnich requested review from ericvh and a balanced review from Copilot November 15, 2026 14:07

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

An organization owner can choose the repository organization as the billing source for reviews requested by members with a paid Copilot license. Learn about Copilot code review billing.

Comment thread client/filter9p.go Resolved
Comment thread client/filter9p.go Resolved
Comment thread client/filter9p.go Resolved
Comment thread client/osnfs.go Resolved
Comment thread client/osnfs.go Resolved
Comment thread client/osnfs.go Resolved
Comment thread client/osnfs.go Resolved

@rminnich rminnich left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we find some way to NOT embed the private key. This is asking for trouble.
Maybe I'm missing something. But they're very easy to generate dynamically.

Comment thread client/osnfs.go Resolved
Comment thread client/union.go Resolved
Comment thread server/key.go Resolved
Barret Rhoden added 3 commits November 23, 2026 18:30
Replace client's forked CPU9P implementation with hugelgupf/p9's
fsimpl/localfs (which includes {dev, ino} QID collision avoidance
and full SetAttr/WriteAt/Readdir/Lock parity).

Note: this removes the exported CPU9P struct and narrows NewCPU9P(root)
to return p9.Attacher. NewCPU9P fails closed on an empty root,
unconditionally sets unix.O_NOCTTY on Unix, translates 9P2000.L wire
open flags (O_APPEND, O_TRUNC, O_SYNC, plus Unix O_NONBLOCK,
O_DIRECTORY, O_NOFOLLOW) into host os.OpenFile flags across OSes and
architectures, and rejects cross-implementation Link/RenameAt with EXDEV.

Also move default c.fileServer initialization from Cmd.Start into
Cmd.Dial before starting the 9P server goroutine, and bump go.mod to
go 1.26.0 as required by the updated hugelgupf/p9 and golang.org/x
dependencies.

Signed-off-by: Barret Rhoden <brho@google.com>
- Remove the duplicate c.SessionIn.Close() closer from c.closers; the
  stdin copy goroutine owns closing SessionIn and c.session.Close()
  already closes the channel, eliminating a data race on
  x/crypto/ssh.channel.sentEOF.
- Call verbose() synchronously before spawning the stdout and stderr
  copy goroutines in Cmd.Start so detached goroutines do not read the
  package-global verbose hook concurrently with client.SetVerbose.
- Fix !sameFD(c.Stdout, os.Stderr) to !sameFD(c.Stderr, os.Stderr) so
  Cmd.Start does not close os.Stderr.

Signed-off-by: Barret Rhoden <brho@google.com>
- Remove embedded static SSH keys (server/key.go) and generate ephemeral
  Ed25519 host and client keys per test in server/server_linux_test.go
  with 0600 permissions.
- Move the Linux-only SSH key/config test helpers from server_test.go
  into server_linux_test.go.
- Fix broken/racy daemon tests in server/server_linux_test.go and
  server/server_test.go: pass TestDaemonConnectHelper flags cleanly to
  client.Command, set c.Stdin and c.Env in both TestDaemonSession and
  TestDaemonConnect (plus WithNameSpace("") and GOMAXPROCS/SetVerbose
  cleanup in TestDaemonSession), remove racy c.SessionIn.Close() calls,
  register -remote and -port9p in TestMain, synchronize SSH server and
  handler shutdown with serveTestSSH, and save/restore package-global v
  via setTestVerbose in the verbose-logging server tests.

Signed-off-by: Barret Rhoden <brho@google.com>
@brho
brho force-pushed the namespace-filter-localfs branch from fc7f231 to 64ac4aa Compare November 23, 2026 20:13
@brho

brho commented Nov 23, 2026

Copy link
Copy Markdown
Collaborator Author

(from gemini) @rminnich Addressed all review feedback and force-pushed a clean 7-commit stack (64ac4aa4b0c1):

  • Deleted server/key.go and switched daemon tests to generate ephemeral Ed25519 host/client keys per test (0600).
  • Renamed canRemovePath -> canMutatePath (client/osnfs.go).
  • Documented why fsCPIO.Root() returns f.mnts[0].fs.Root() (matching hasMount so COS's os.OpenRoot(fs.Root()) targets -root).
  • Also hardened NewOSFS/COS/filterFS (using os.OpenRoot for COS and osFS.{Lstat,Readlink}, blocking BoundOS path dedup / TempFile fallback / missing mount-root auto-creation / FIFO lock-blocking / Windows NTFS junctions) and filter9PFile (synchronized checkPath from a cloned root fid closing stale-fid intermediate-symlink, TOCTOU, and FIFO lock-blocking bugs), and fixed the Cmd.Start/Close and serveTestSSH test races under -race.

@rminnich rminnich left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ok, here we go ...

Comment thread client/client.go
// or variants. This lets us use a listen deadline.
if c.Ninep {
if c.fileServer == nil {
c.fileServer = NewCPU9P(c.Root)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

where is NewCPU9P defined? somewhere in the client package?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(from gemini) It's defined in the same client package at client/cpu9p.go:46 (added in commit 1). It wraps hugelgupf/p9/fsimpl/localfs.Attacher(root) to fail closed on root == "" (instead of exporting "/") and translate Linux 9P2000.L wire open flags (O_APPEND, O_TRUNC, O_SYNC, O_NONBLOCK, etc.) to host OS flags.

Comment thread client/filter9p.go Outdated
return attr.Mode.FileType(), nil
}

// checkPath walks from the attached root one component at a time to ensure no

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can you explain more about this and the need for the extra root FID?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(from gemini) Because upstream localfs stores only a path string l.path (not a pinned dirfd), a fid walked while /export/d was a directory silently follows /export/d if it is later unlinked and replaced with a symlink to /etc. checkPath re-walks every component of f.relPath from "/" one step at a time and verifies all intermediates are TypeDir (plus the leaf type). The extra cloned root FID (filter9PRoot via f.Walk(nil) at Attach time) is needed because (a) filter9PFile only speaks p9.File (no host paths), (b) the client can clunk its own root fid while keeping descendant fids open, and (c) re-calling localfs.Attacher.Attach() on every op calls syscall.Umask(0). Downside: O(depth) Lstat syscalls per unopened path-based op; fixed at the root in hugelgupf/p9#138.

Comment thread client/filter9p.go Outdated
type filter9PAttacher struct {
p9.Attacher
allow allowList
mu sync.RWMutex

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i see this mutex used a lot - what exactly does it protect?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(from gemini) filter9PAttacher.mu protects three things: (1) check-then-use atomicity between checkPath and backing localfs path-based syscalls against concurrent 9P mutations (upstream p9.Server's per-pathNode opMu and renameMu don't cover target locking in Tlink, descendant locking in Tunlinkat, or xattr clunks), (2) f.relPath (mutated in Renamed, read everywhere else), and (3) f.root.file teardown in Close() against concurrent checkPath walks. Note the real downsides: it is a coarse attacher-wide RWMutex (widening stalls on blocking opens) and still cannot close TOCTOU against unrelated local host processes. Moving confinement into localfs itself (opened as hugelgupf/p9#138, plus server locking fixes in hugelgupf/p9#137) is the clean root fix.

Comment thread client/filter9p.go Outdated
case pathExported:
// Reject symlinks and special files (FIFOs, sockets, devices)
// before opening so a blocking open(2) cannot hold attacher.mu
// and deadlock the 9P server.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

blocking opens causing a deadlock is mildly worrisome. why are we holding attacher.mu, and what is the scenario where this deadlocks?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(from gemini) This is the worst trade-off in filter9p.go. attacher.mu.RLock() is held across f.File.Open to stop a concurrent 9P UnlinkAt+Symlink/RenameAt between checkPath and localfs's os.OpenFile. Without checkRegularOrDir, if goroutine A blocks in Open(O_RDONLY) on a FIFO under RLock(), any mutating op B blocks on Lock(), which causes Go's sync.RWMutex to block all new RLocks — including goroutine C trying to Open(O_WRONLY) the other end of the FIFO to unblock A (and server disconnect hangs in cs.stop()). Upstream p9.Server's tlopen.handle already has a narrower version of this deadlock because it holds server.renameMu.RLock() across ref.file.Open (triggered if any Trename/Trenameat/Tremove/Tlink arrives); filter9p widens it to any mutation or final Close. Even with checkRegularOrDir (which bans FIFOs/devices), a hung NFS/FUSE mount can still stall RLock(). Pushing confinement into localfs (hugelgupf/p9#138) eliminates the need for attacher.mu/checkPath/checkRegularOrDir in any wrapper.

Comment thread client/filter9p.go Outdated
return f.File.Readlink()
}

// Walk implements p9.File.Walk.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what's the strategy of Walk with respect to Open? Open has checks based on relPath. what are the goals of Walk? don't let clients walk to non-ancestor/non-allowed paths? or to make sure relPath is accurate? something else?

is there even a use case for letting someone walk to a non-exported/non-ancestor path?

we do want to be resilient to someone poking around for names, so i get that we want some checks in walk. (the ability to walk, even if you can't open, is still an info leak, and we might want to block other ops that don't require Open).

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(from gemini) Right — there is no use case for walking to a disallowed path, and Walk blocks it up front with os.ErrNotExist before touching the backing FS (preventing existence/QID/xattr probing and ensuring no disallowed fid ever exists). Walk also keeps relPath canonical (clamping ".." at "/") and steps one component at a time checking TypeDir so intermediate symlinks are never traversed. Open still needs classify(relPath) + checkPath because Walk legitimately hands out fids that must be restricted at Open time: (1) ancestor dirs (e.g. "/" and "/usr" for -namespace=/usr/bin) must be walkable/stat-able/filtered-Readdir-able, so Open restricts them to read-only and verifies checkDir (also preventing opening /etc/shadow if -namespace=/etc/shadow/sub); (2) symlinks inside exported dirs must be walkable for Lstat/Readlink/UnlinkAt, so Open rejects them because localfs.Local.Open calls os.OpenFile without O_NOFOLLOW; and (3) an ancestor could have been swapped for a symlink between Walk and Open.

Comment thread client/filter9p.go Outdated
curPath = next
}

// Never traverse out of a non-directory or stale fid behind a symlink.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can you explain more about the symlink business?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(from gemini) Three symlink escapes in upstream hugelgupf/p9 + localfs: (1) Stale-fid intermediate-symlink escape (zero race needed): walk /export/d/shadow -> fidS, unlink shadow and d, symlink d -> /etc, then call Tlink(exportDir, fidS, "stolen") — upstream p9.Server's tlink never checks refTarget.isDeleted() (fixed in hugelgupf/p9#137) and localfs calls os.Link on the stale path string (fixed in hugelgupf/p9#138), hard-linking host /etc/shadow into /export/stolen (Tgetattr also allows deleted fids). (2) Leaf symlinks: symlinks inside exported dirs are allowed for Readlink, but upstream localfs Open/SetAttr/*Xattr and macOS Link follow leaf symlinks on the host (fixed in hugelgupf/p9#138). (3) Multi-component localfs.Local.Walk(["sym_etc", "shadow"]) joins paths and Lstats without rejecting intermediate symlinks (fixed in hugelgupf/p9#138).

@brho
brho force-pushed the namespace-filter-localfs branch from 64ac4aa to 2836090 Compare November 24, 2026 22:21
@brho brho changed the title client, cmds/cpu, cmds/decpu: use localfs and restrict export to -namespace client: replace custom CPU9P with hugelgupf/p9/fsimpl/localfs Nov 24, 2026
@brho

brho commented Nov 24, 2026

Copy link
Copy Markdown
Collaborator Author

(from gemini)

Split this PR down to the first 3 commits (25e47fef..28360906: switching CPU9P to hugelgupf/p9/fsimpl/localfs, Cmd.Start/Close I/O race fixes, and ephemeral SSH keys / daemon test race fixes).

The -namespace export filtering (filter9p, NewFilterFS, -unsafe-export, and the export-isolation tests) has been split out to brho/cpu:namespace-filter while the generic server locking and localfs root-confinement/no-symlink fixes proceed upstream in hugelgupf/p9#137 and hugelgupf/p9#138.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants