From 96fd6018a9161fa907c5b46552bccda861f6912b Mon Sep 17 00:00:00 2001 From: shoemoney Date: Tue, 23 Jun 2026 02:21:03 -0500 Subject: [PATCH] =?UTF-8?q?fix(sec):=20block=20blob-hash=20path=20traversa?= =?UTF-8?q?l=20(arbitrary=20file=20read)=20=F0=9F=94=93=F0=9F=9B=A1?= =?UTF-8?q?=EF=B8=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit GET /v1/blob/{hash} and /v1/have passed the URL hash straight into filepath.Join in the blob store. Go's ServeMux URL-decodes %2f/%2e in the wildcard, so '..%2f..%2f..%2fetc%2fpasswd' (or a hash starting with '..') escaped the blob root — any enrolled device could read arbitrary files incl. the hub token DB. Defense in depth: - hub: validHash() rejects non-(64 hex) keys at the HTTP boundary (404 on GET, 400 on /have) before any store call. - blobstore: safeKey() rejects keys that aren't a bare, separator-free filename in Has/Get/Put/Delete — the sink can't be escaped even if a caller forgets. e2e + unit regression tests for both layers. --- internal/hub/blob_traversal_test.go | 62 ++++++++++++++++++++++++ internal/hub/blobstore/blobstore.go | 26 +++++++++- internal/hub/blobstore/traversal_test.go | 54 +++++++++++++++++++++ internal/hub/server.go | 31 +++++++++++- 4 files changed, 170 insertions(+), 3 deletions(-) create mode 100644 internal/hub/blob_traversal_test.go create mode 100644 internal/hub/blobstore/traversal_test.go diff --git a/internal/hub/blob_traversal_test.go b/internal/hub/blob_traversal_test.go new file mode 100644 index 0000000..96dcd15 --- /dev/null +++ b/internal/hub/blob_traversal_test.go @@ -0,0 +1,62 @@ +package hub + +import ( + "crypto/ed25519" + "crypto/rand" + "encoding/json" + "net/http" + "testing" + "time" + + "git.shoemoney.ai/shoemoney/devbox/internal/hub/meta" + "git.shoemoney.ai/shoemoney/devbox/pkg/proto" +) + +// enroll joins a device and returns its bearer token. +func enroll(t *testing.T, base string, db *meta.DB) string { + t.Helper() + if err := db.CreateToken(HashToken("tok"), time.Now().Unix()+3600); err != nil { + t.Fatal(err) + } + pub, _, err := ed25519.GenerateKey(rand.Reader) + if err != nil { + t.Fatal(err) + } + status, body := do(t, "POST", base+proto.PathJoin, "", mustJSON(t, proto.JoinRequest{ + Token: "tok", Name: "dev", Pubkey: pub, + })) + if status != http.StatusOK { + t.Fatalf("join status %d: %s", status, body) + } + var jr proto.JoinResponse + if err := json.Unmarshal(body, &jr); err != nil { + t.Fatal(err) + } + return jr.Bearer +} + +// An authenticated device must NOT be able to read files outside the blob root +// via a path-traversal blob hash (ServeMux URL-decodes %2f in the {hash} wildcard). +func TestBlobGetRejectsTraversal(t *testing.T) { + base, db := testHub(t) + bearer := enroll(t, base, db) + + for _, key := range []string{ + "..%2f..%2f..%2f..%2fetc%2fpasswd", + "..%2f..%2fdevbox-hub.db", + "not-a-hash", + "deadbeef", // valid hex but wrong length + } { + status, body := do(t, "GET", base+proto.PathBlob+key, bearer, nil) + if status == http.StatusOK { + t.Errorf("GET blob %q returned 200 (leak): %s", key, body) + } + } + + // /v1/have must reject a traversal hash rather than stat an arbitrary path. + status, _ := do(t, "POST", base+proto.PathHave, bearer, + mustJSON(t, proto.HaveRequest{Hashes: []string{"../../../../etc/hosts"}})) + if status != http.StatusBadRequest { + t.Errorf("have with traversal hash = %d, want 400", status) + } +} diff --git a/internal/hub/blobstore/blobstore.go b/internal/hub/blobstore/blobstore.go index aee7093..a136ee5 100644 --- a/internal/hub/blobstore/blobstore.go +++ b/internal/hub/blobstore/blobstore.go @@ -13,11 +13,24 @@ import ( "io/fs" "os" "path/filepath" + "strings" ) // ErrNotFound is returned by Get/Delete for a missing blob. var ErrNotFound = errors.New("blobstore: blob not found") +// safeKey rejects keys that aren't a single, separator-free filename. The hub +// validates hash *shape* at its HTTP boundary; this is defense in depth so a key +// like "../../etc/passwd" (or one whose first two chars are "..", which would +// escape via shardDir) can never leave the blob root, even if a future caller +// forgets to validate. Stays algorithm-agnostic (no fixed length/charset). +func safeKey(hash string) error { + if hash == "" || hash == "." || strings.Contains(hash, "..") || strings.ContainsAny(hash, `/\`) { + return fmt.Errorf("blobstore: unsafe blob key %q", hash) + } + return nil +} + // Store is a content-addressed blob store. type Store interface { Has(hash string) (bool, error) // does a blob with this hash exist? @@ -53,6 +66,9 @@ func (d *Disk) path(hash string) string { // Has reports whether a blob with the given hash exists. func (d *Disk) Has(hash string) (bool, error) { + if err := safeKey(hash); err != nil { + return false, err + } _, err := os.Stat(d.path(hash)) if err == nil { return true, nil @@ -67,8 +83,8 @@ func (d *Disk) Has(hash string) (bool, error) { // writes atomically via a temp file + rename, so a partial write never appears // as a complete blob. func (d *Disk) Put(hash string, data []byte) error { - if hash == "" { - return fmt.Errorf("blobstore: empty hash") + if err := safeKey(hash); err != nil { + return err } if ok, err := d.Has(hash); err != nil || ok { return err @@ -97,6 +113,9 @@ func (d *Disk) Put(hash string, data []byte) error { // Get returns the blob bytes for hash, or ErrNotFound. func (d *Disk) Get(hash string) ([]byte, error) { + if err := safeKey(hash); err != nil { + return nil, err + } b, err := os.ReadFile(d.path(hash)) if errors.Is(err, fs.ErrNotExist) { return nil, ErrNotFound @@ -106,6 +125,9 @@ func (d *Disk) Get(hash string) ([]byte, error) { // Delete removes a blob, returning ErrNotFound if it was absent. func (d *Disk) Delete(hash string) error { + if err := safeKey(hash); err != nil { + return err + } err := os.Remove(d.path(hash)) if errors.Is(err, fs.ErrNotExist) { return ErrNotFound diff --git a/internal/hub/blobstore/traversal_test.go b/internal/hub/blobstore/traversal_test.go new file mode 100644 index 0000000..7d6c7d5 --- /dev/null +++ b/internal/hub/blobstore/traversal_test.go @@ -0,0 +1,54 @@ +package blobstore + +import ( + "os" + "path/filepath" + "testing" +) + +// A blob key that tries to escape the root (path traversal) must be rejected, +// not resolved to a file outside the store. +func TestDiskRejectsPathTraversalKeys(t *testing.T) { + root := t.TempDir() + // A secret living OUTSIDE the blob root that an attacker would target. + secret := filepath.Join(filepath.Dir(root), "secret.txt") + if err := os.WriteFile(secret, []byte("top-secret"), 0o600); err != nil { + t.Fatal(err) + } + d, err := NewDisk(root) + if err != nil { + t.Fatal(err) + } + + for _, key := range []string{ + "../secret.txt", + "../../etc/passwd", + "..", "..a", // first two chars ".." would escape via shardDir + "a/b", `a\b`, + ".", + } { + if _, err := d.Get(key); err == nil { + t.Errorf("Get(%q) returned no error — traversal not blocked", key) + } + if has, err := d.Has(key); err == nil && has { + t.Errorf("Has(%q) = true — traversal not blocked", key) + } + if err := d.Delete(key); err == nil { + t.Errorf("Delete(%q) returned no error — traversal not blocked", key) + } + } + + // The targeted secret must still be intact (never read or removed). + if b, err := os.ReadFile(secret); err != nil || string(b) != "top-secret" { + t.Fatalf("secret outside root was touched: %q, %v", b, err) + } + + // A well-formed key still round-trips. + good := "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" + if err := d.Put(good, []byte("ok")); err != nil { + t.Fatalf("Put(valid) = %v", err) + } + if b, err := d.Get(good); err != nil || string(b) != "ok" { + t.Fatalf("Get(valid) = %q, %v", b, err) + } +} diff --git a/internal/hub/server.go b/internal/hub/server.go index 07a3fbc..280e688 100644 --- a/internal/hub/server.go +++ b/internal/hub/server.go @@ -149,6 +149,23 @@ func (s *Server) handlePublish(w http.ResponseWriter, r *http.Request, deviceID w.WriteHeader(http.StatusOK) } +// validHash reports whether h is a well-formed content hash (BLAKE3-256 hex). +// Blob keys flow into filesystem paths, so anything else (../, %2f-decoded +// slashes, absolute paths) is rejected at the trust boundary before it can +// escape the blob root. Legit keys are always 64 lowercase hex chars. +func validHash(h string) bool { + if len(h) != 64 { + return false + } + for i := 0; i < len(h); i++ { + c := h[i] + if !((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f')) { + return false + } + } + return true +} + func (s *Server) handleHave(w http.ResponseWriter, r *http.Request, _ string) { var req proto.HaveRequest if !decode(w, r, &req) { @@ -156,6 +173,10 @@ func (s *Server) handleHave(w http.ResponseWriter, r *http.Request, _ string) { } var missing []string for _, h := range req.Hashes { + if !validHash(h) { + writeErr(w, http.StatusBadRequest, "invalid hash") + return + } has, err := s.store.Has(h) if err != nil { writeErr(w, http.StatusInternalServerError, err.Error()) @@ -170,7 +191,15 @@ func (s *Server) handleHave(w http.ResponseWriter, r *http.Request, _ string) { // handleGetBlob serves a blob's bytes for download (pull fetches manifests + chunks). func (s *Server) handleGetBlob(w http.ResponseWriter, r *http.Request, _ string) { - b, err := s.store.Get(r.PathValue("hash")) + hash := r.PathValue("hash") + if !validHash(hash) { + // ServeMux URL-decodes %2f/%2e in the {hash} wildcard, so an unvalidated + // key like "..%2f..%2fetc%2fpasswd" would escape the blob root. Reject as + // "not found" — an invalid hash is, by definition, not a stored blob. + writeErr(w, http.StatusNotFound, "no such blob") + return + } + b, err := s.store.Get(hash) if errors.Is(err, blobstore.ErrNotFound) { writeErr(w, http.StatusNotFound, "no such blob") return