Artifact 2aa0be0b97962a6a88cfa669669f5521ded7c3963b7f93d6acf39013a7027e28:
- File
internal/xfer/decode_size_test.go
— part of check-in
[3a6126c3e9]
at
2026-10-11 01:34:31
on branch trunk
— fix: harden sync and repository defaults (security) (#282)
* fix(xfer): reject non-decimal card sizes and bound payload memory
A payload card's size was parsed with strconv.Atoi, so a peer sending `file HASH -1` reached readPayload's negative-size assertion and panicked the client or server decoding the message, and a signed size such as `+5` was accepted. Sizes now go through parseSize, which follows the sync draft's `decimal = 1*DIGIT` grammar and fossil's 32-bit limit and returns a decoding error for anything else. uvfile FLAGS use the same parser, so negative FLAGS are rejected as the draft requires. The assertion stays, now unreachable from peer input.
readPayload no longer allocates the declared size up front: its buffer grows with the bytes read, so a large size over a short message fails after allocating about what was sent.
A cfile payload may inflate only to its USIZE (a margin above it for a delta) and not past its 4-byte size prefix, and all cfile payloads in one message share a MaxCFileInflateBytes (1 GiB) budget, so a few megabytes of zlib cannot inflate to tens of gigabytes.
FuzzDecode exercises the decoder over both framings.
* fix(sync): refuse malformed xrow payloads and cap HTTP reply bodies
An xrow payload or xdelete PKData from a peer was decoded into a map and used as is. JSON null gave a nil map that reached coerceJSONNumbers' assertion, and a primary-key value of the wrong type or a nested value reached normalizeValue's, panicking the client or server. Both directions now decode through decodeRowJSON: one JSON object, nothing after it, and repo.ValidateRow's rules, which require scalar values and primary-key values that PKHash can normalize. A client refuses an xrow for a table it has not registered. Column types match case-insensitively, as table creation accepts them.
Both HTTP transports read replies through xfer.ReadBody, which stops at MaxBodyBytes (MaxDecompressedBytes plus framing headroom) and returns ErrBodyTooLarge, untagged for retry, instead of reading an endless body into memory.
FuzzTableSyncPayload drives the server handler and client over arbitrary payloads.
* fix(sync): check synced-table rows and identifiers before building SQL
repo.UpsertXRow wrote a row's map keys into its INSERT as column names, and the rows of an xrow payload or xdelete PKData come from the peer, so a key such as "val, mtime) VALUES(...) --" chose the statement's columns and values, and a key could select from other tables into a synced one. This held on the server for pushed rows and tombstones, and on the client for a server's rows.
A peer's row must now use exactly the table's declared columns: repo.ValidateRow refuses any other key, which also keeps a peer from setting _owner. UpsertXRow no longer trusts its caller: it reads the table's registered schema and refuses any key it does not declare, apart from _owner on an ownership-mode table. ListXRows, LookupXRowOwner and DeleteXRowByPKHash validate the table name and the column names they interpolate, so no synced-table identifier reaches SQL text unchecked.
* fix(sync): answer reqconfig only with fossil's transferable config
The sync server answered reqconfig NAME with any row of the config table, for any requester, including one with no capabilities, so project-code, server-code and every local setting could be read by anyone who could reach the sync endpoint.
handleReqConfig now follows fossil's page_xfer and configure.c. It answers only a /GROUP name, only for a requester with Read, matches the group by prefix in fossil's table order, and sends only the names fossil transfers in that group, in fossil's encoding. The user and subscriber tables also need Admin, which counts only for a verified login, and the concealed table needs RdAddr. A refused request gets no cards and no error.
The groups, their names and their capability rules live in one place, config_groups.go. A differential test answers the same requests with fossil's own server and with HandleSync on the same repository and requires identical config cards.
* test(sync): keep fossil http from leaving a backoffice process
* fix(sync): check the login nonce against the request body
The server verified a login card's signature over its nonce but never checked that the nonce was the SHA-1 of the request body after the login line, as fossil's check_tail_hash does (draft-fossil-sync-protocol-00 §6.2). A login card captured from one request therefore authenticated any other request body.
The decoder now records, for each login card, the SHA-1 of the decompressed bytes after the card's line, and VerifyLogin refuses a card whose nonce does not match it. A login card that was never decoded has no tail and is refused.
Login handling otherwise follows fossil's page_xfer and check_login: - a refused login ends the exchange with "error login failed" instead of continuing as nobody; - a second login card is refused with "multiple login cards"; - a successful login adds the user's capabilities to nobody's instead of replacing them; - nobody and anonymous log in without a password, and the reserved developer and reader logins and accounts with an empty password cannot be logged into.
Fixes GHSA-2g5p-q5f3-477p.
* fix(repo): seed nobody with fossil's default capabilities
A new repository seeded the nobody user with "cghijknorswy", so every request without a login card could push check-ins and unversioned files, write wiki pages and tickets, and held Setup. Seed the four built-in users `fossil new` creates, with fossil's capabilities: nobody "gjorz", anonymous "hz", developer "ei" and reader "kptw".
Setup and Admin now include check-in, read and clone, as they do in fossil, so the creating user can sync once given a password. A login to an account with no stored password is refused, as fossil's check_login refuses it; the creator starts with none, and the signature would otherwise be the SHA-1 of the nonce alone.
Tests that push without credentials grant nobody push explicitly. Existing repositories keep their stored capabilities.
* test(auth): reserved-login test updates the seeded developer and reader rows
New repositories now seed developer and reader as fossil does, so the test gives the existing rows a password instead of inserting them.
* docs(changelog): group the sync hardening fixes under Security
* test(sync): reqconfig tests sign their logins over the request body
The login nonce now has to cover the request body, so the reqconfig tests build their admin requests with signedRequest instead of a bare login card. (user: [email protected], size: 8040) [annotate] [blame] [check-ins using]
package xfer import ( "bytes" "compress/zlib" "encoding/binary" "runtime" "strconv" "strings" "testing" ) const sizeTestHash = "0123456789abcdef0123456789abcdef01234567" // badSizeTokens are tokens that strconv.Atoi accepts or that overflow, none // of which is the draft's `decimal = 1*DIGIT` within fossil's 32-bit int. var badSizeTokens = []string{ "-1", "-0", "+5", "-2147483648", "0x10", "1e3", "5x", "5", "2147483648", "99999999999999999999", } // sizeCardTemplates holds one card line per size-bearing token; %s marks the // token under test. Each is followed by enough payload bytes that a decoder // accepting the token would have something to read. var sizeCardTemplates = []string{ "file " + sizeTestHash + " %s\n", "file " + sizeTestHash + " " + sizeTestHash + " %s\n", "cfile " + sizeTestHash + " %s 4\n", "cfile " + sizeTestHash + " 4 %s\n", "cfile " + sizeTestHash + " " + sizeTestHash + " %s 4\n", "config /project %s\n", "uvfile name.txt 0 " + sizeTestHash + " %s 0\n", "uvfile name.txt 0 " + sizeTestHash + " 4 %s\n", "schema t 1 " + sizeTestHash + " 0 %s\n", "xrow t " + sizeTestHash + " 0 %s\n", "xdelete t " + sizeTestHash + " 0 %s\n", } // TestDecodeRejectsNonDecimalSizes checks that every size token on a // payload-bearing card is held to the draft's decimal grammar. Method: put // each bad token into each size position and decode. A negative size used to // reach readPayload's assertion and panic the process reading a peer's // message; a signed or hex size was read as a size. All must be a decode error. func TestDecodeRejectsNonDecimalSizes(t *testing.T) { for _, tmpl := range sizeCardTemplates { for _, tok := range badSizeTokens { line := strings.Replace(tmpl, "%s", tok, 1) data := []byte(line + "abcdefgh\n") t.Run(strings.TrimSpace(line), func(t *testing.T) { defer func() { if p := recover(); p != nil { t.Fatalf("Decode panicked: %v", p) } }() if _, err := Decode(data, ContentTypeUncompressed); err == nil { t.Fatalf("Decode accepted size token %q", tok) } }) } } } // allocatedBy reports the bytes f allocates on the heap. func allocatedBy(f func()) uint64 { var before, after runtime.MemStats runtime.GC() runtime.ReadMemStats(&before) f() runtime.ReadMemStats(&after) return after.TotalAlloc - before.TotalAlloc } // allocBudget is far above what decoding a few-kilobyte message costs and // far below the sizes these tests declare. const allocBudget = 16 << 20 // TestDecodeHugeDeclaredSizeIsNotAllocated checks that a declared size is // not trusted for allocation. Method: declare ~2 GiB on each payload card but // send a few bytes, and measure what decoding allocates. Allocating the // declared size up front lets a few bytes from a peer cost gigabytes. func TestDecodeHugeDeclaredSizeIsNotAllocated(t *testing.T) { const huge = "2147483647" lines := []string{ "file " + sizeTestHash + " " + huge + "\n", "cfile " + sizeTestHash + " 4 " + huge + "\n", "config /project " + huge + "\n", "uvfile name.txt 0 " + sizeTestHash + " " + huge + " 0\n", } for _, line := range lines { t.Run(strings.TrimSpace(line), func(t *testing.T) { data := []byte(line + "short payload") var err error n := allocatedBy(func() { _, err = Decode(data, ContentTypeUncompressed) }) if err == nil { t.Fatal("Decode accepted a truncated payload") } if n > allocBudget { t.Fatalf("decoding %d bytes allocated %d bytes", len(data), n) } }) } } // zlibZeros compresses n zero bytes without holding them in memory. func zlibZeros(t *testing.T, n int) []byte { t.Helper() var buf bytes.Buffer zw := zlib.NewWriter(&buf) chunk := make([]byte, 64<<10) for written := 0; written < n; written += len(chunk) { if _, err := zw.Write(chunk[:min(len(chunk), n-written)]); err != nil { t.Fatalf("zlib write: %v", err) } } if err := zw.Close(); err != nil { t.Fatalf("zlib close: %v", err) } return buf.Bytes() } // TestDecodeCFileInflationIsBounded checks that a cfile cannot inflate past // the size its card and prefix declare. Method: send a small zlib stream of // 256 MiB of zeros under cards declaring a few bytes, in the plain and the // prefixed form and as a delta, and measure what decoding allocates. Without // a bound, ~256 KiB on the wire costs 256 MiB, and a message of such cards // costs a multiple of that. func TestDecodeCFileInflationIsBounded(t *testing.T) { if testing.Short() { t.Skip("compresses 256 MiB") } bomb := zlibZeros(t, 256<<20) prefixed := binary.BigEndian.AppendUint32(nil, 16) prefixed = append(prefixed, bomb...) cases := []struct { name string header string payload []byte }{ {"plain", "cfile " + sizeTestHash + " 16", bomb}, {"prefixed", "cfile " + sizeTestHash + " 16", prefixed}, {"delta", "cfile " + sizeTestHash + " " + sizeTestHash + " 16", bomb}, {"delta prefixed", "cfile " + sizeTestHash + " " + sizeTestHash + " 16", prefixed}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { var data bytes.Buffer data.WriteString(tc.header) data.WriteString(" ") data.WriteString(strconv.Itoa(len(tc.payload))) data.WriteString("\n") data.Write(tc.payload) var err error n := allocatedBy(func() { _, err = Decode(data.Bytes(), ContentTypeUncompressed) }) if err == nil { t.Fatal("Decode accepted a cfile inflating past its declared size") } if n > allocBudget+uint64(data.Len())*2 { t.Fatalf("decoding %d bytes allocated %d bytes", data.Len(), n) } }) } } // TestDecodeCFileBudgetSpansMessage checks that cfile inflation is budgeted // across a whole message, not per card. Method: decode two full cfiles, each // inflating to exactly its own USIZE, under a budget that covers one of them. // Each card alone is consistent with its declaration, so only a message-wide // budget stops a message of many such cards from costing a multiple of it. func TestDecodeCFileBudgetSpansMessage(t *testing.T) { const usize = 48 << 10 payload := zlibZeros(t, usize) card := "cfile " + sizeTestHash + " " + strconv.Itoa(usize) + " " + strconv.Itoa(len(payload)) + "\n" + string(payload) if _, err := decodeMessage([]byte(card), usize); err != nil { t.Fatalf("one card within the budget: %v", err) } _, err := decodeMessage([]byte(card+card), usize+usize/2) if err == nil { t.Fatal("two cards over the message budget were accepted") } if !strings.Contains(err.Error(), "decode card 1") { t.Fatalf("budget did not stop the second card: %v", err) } } // FuzzDecode checks that no message a peer can send makes the decoder panic. // A malformed message must come back as an error; the decoder runs on both // sides of a sync, so a panic here stops a client or a server's handler. func FuzzDecode(f *testing.F) { seeds := []string{ "igot " + sizeTestHash + "\ngimme " + sizeTestHash + "\n", "file " + sizeTestHash + " 3\nabc", "file " + sizeTestHash + " " + sizeTestHash + " 3\nabc", "file " + sizeTestHash + " -1\nabc", "config /project 3\nabc\n", "uvfile a.txt 0 " + sizeTestHash + " 3 0\nabc", "uvfile a.txt 0 - 0 1\n", "xrow t " + sizeTestHash + " 0 2\n{}\n", "clone 3 1\nclone_seqno 5\npragma client-version 22800\n", } for _, s := range seeds { f.Add([]byte(s), false) } msg := &Message{Cards: []Card{ &CFileCard{UUID: sizeTestHash, Content: []byte("hello")}, &CFileCard{UUID: sizeTestHash, DeltaSrc: sizeTestHash, USize: 9, Content: []byte("5\n0:;")}, &FileCard{UUID: sizeTestHash, Content: []byte("x")}, }} raw, err := msg.EncodeUncompressed() if err != nil { f.Fatalf("encode seed: %v", err) } f.Add(raw, false) compressed, err := msg.Encode() if err != nil { f.Fatalf("encode seed: %v", err) } f.Add(compressed, true) f.Fuzz(func(t *testing.T, data []byte, isCompressed bool) { contentType := ContentTypeUncompressed if isCompressed { contentType = ContentTypeCompressed } // Only a panic fails; any error is the decoder doing its job. _, _ = Decode(data, contentType) }) }