fix(sec): block blob-hash path traversal (arbitrary file read) 🔓🛡️

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.
This commit is contained in:
shoemoney 2026-06-23 02:21:03 -05:00
parent 7366ab757c
commit 96fd6018a9
4 changed files with 170 additions and 3 deletions

View file

@ -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)
}
}

View file

@ -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

View file

@ -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)
}
}

View file

@ -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