Artifact 2da2cb43e67b336cb2a1527e1095add84bc65cd681fde6b8827f9a47eee9f650:
- File
internal/xfer/card.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: 8362) [annotate] [blame] [check-ins using]
// Package xfer implements Fossil's sync protocol card codec. // It encodes and decodes the line-oriented "xfer card" format used by // Fossil's /xfer HTTP endpoint, with NO database dependency. package xfer // CardType enumerates the 24 card types in Fossil's sync protocol. type CardType int const ( CardFile CardType = iota // 0 — file CardCFile // 1 — cfile (compressed file) CardIGot // 2 — igot CardGimme // 3 — gimme CardLogin // 4 — login CardPush // 5 — push CardPull // 6 — pull CardCookie // 7 — cookie CardClone // 8 — clone CardCloneSeqNo // 9 — clone_seqno (undocumented) CardConfig // 10 — config CardReqConfig // 11 — reqconfig CardPrivate // 12 — private CardUVFile // 13 — uvfile CardUVGimme // 14 — uvgimme CardUVIGot // 15 — uvigot CardPragma // 16 — pragma CardError // 17 — error CardMessage // 18 — message CardUnknown // 19 — unrecognized card CardSchema // 20 — schema (table sync) CardXIGot // 21 — xigot (table sync row announcement) CardXGimme // 22 — xgimme (table sync row request) CardXRow // 23 — xrow (table sync row payload) CardXDelete // 24 — xdelete (table sync row deletion) CardComment // 25 — "# ..." comment line ) // Card is the interface implemented by every xfer card type. type Card interface { Type() CardType } // FileCard represents a "file" card carrying an artifact payload. type FileCard struct { UUID string DeltaSrc string // empty when not a delta Content []byte } func (c *FileCard) Type() CardType { return CardFile } // CFileCard represents a "cfile" card (compressed file with uncompressed size). type CFileCard struct { UUID string DeltaSrc string USize int Content []byte // StoredBlob is the received card's payload re-expressed in Fossil's // on-disk blob format ([4-byte big-endian uncompressed size][zlib // data]), suitable for writing to the blob table's content column // verbatim. It is derived by decode-time bookkeeping only -- never by // recompressing Content -- so a receiver that persists StoredBlob // reproduces the sender's stored bytes exactly, rather than the bytes // of a fresh, independently-parameterized zlib pass. Always non-nil // after a successful decode. StoredBlob []byte } func (c *CFileCard) Type() CardType { return CardCFile } // IGotCard represents an "igot" card — the sender has this artifact. type IGotCard struct { UUID string IsPrivate bool // true when second arg is "1" } func (c *IGotCard) Type() CardType { return CardIGot } // GimmeCard represents a "gimme" card — the sender wants this artifact. type GimmeCard struct { UUID string } func (c *GimmeCard) Type() CardType { return CardGimme } // LoginCard represents a "login" card for authentication. // User is stored as plain text (Fossil-decoded). type LoginCard struct { User string // plain text (defossilized) Nonce string Signature string // tailSHA1 is the SHA-1 of the message bytes that followed this card's // line, recorded by DecodeUncompressed. Empty for a card built in memory. tailSHA1 string } func (c *LoginCard) Type() CardType { return CardLogin } // NonceCoversTail reports whether Nonce is the SHA-1 of the decompressed bytes // that followed this card's line in the message it was decoded from: "every // decompressed body byte after the body login line's LF through body end" // (draft §6.2, src/xfer.c check_tail_hash). The signature covers only the // nonce, so this check is what binds a login to its body; without it a // captured card authenticates any body. A card that was not decoded has no // tail and covers nothing. func (c *LoginCard) NonceCoversTail() bool { return c.tailSHA1 != "" && c.Nonce == c.tailSHA1 } // CommentCard represents a "# ..." line. A receiver ignores it — canonical's // card loop skips any line starting with '#', as does this package's decoder, // so a comment never survives a round trip. // // It carries no protocol meaning but it is not inert: a login card's nonce // hashes every byte that follows it, and the server re-hashes those bytes to // validate it (src/xfer.c check_tail_hash). The comment is where a client puts // the randomness that makes each nonce, and so each signature, unique — which // only works if the comment is actually transmitted, not merely hashed. type CommentCard struct { Text string } func (c *CommentCard) Type() CardType { return CardComment } // PushCard represents a "push" card sent by the client to begin a push. type PushCard struct { ServerCode string ProjectCode string } func (c *PushCard) Type() CardType { return CardPush } // PullCard represents a "pull" card sent by the client to begin a pull. type PullCard struct { ServerCode string ProjectCode string } func (c *PullCard) Type() CardType { return CardPull } // CookieCard carries a session cookie value. type CookieCard struct { Value string } func (c *CookieCard) Type() CardType { return CardCookie } // CloneCard represents a "clone" card. Version and SeqNo are zero for a // bare "clone" request. // // SeqNoIsDecimal records the SHAPE of the SEQNO token, not its presence: // §8.1 keys its fatal on a digit-only SEQNO (`decimal = 1*DIGIT`) and a // parsed int cannot carry that. "clone 3 -1" therefore has a SEQNO token // but is not decimal, and "clone" and "clone 3 0" both parse to SeqNo 0 // while only the latter is fatal. type CloneCard struct { Version int SeqNo int SeqNoIsDecimal bool } func (c *CloneCard) Type() CardType { return CardClone } // CloneSeqNoCard represents a "clone_seqno" card. type CloneSeqNoCard struct { SeqNo int } func (c *CloneSeqNoCard) Type() CardType { return CardCloneSeqNo } // ConfigCard represents a "config" card carrying configuration data. type ConfigCard struct { Name string Content []byte } func (c *ConfigCard) Type() CardType { return CardConfig } // ReqConfigCard requests a named configuration section. type ReqConfigCard struct { Name string } func (c *ReqConfigCard) Type() CardType { return CardReqConfig } // PrivateCard signals that subsequent igot cards are private. type PrivateCard struct{} func (c *PrivateCard) Type() CardType { return CardPrivate } // UV file flag constants. const ( UVFlagDeletion = 0x0001 // File is a deletion tombstone. UVFlagContentOmitted = 0x0004 // Content not included in this card. UVFlagNoPayload = UVFlagDeletion | UVFlagContentOmitted // Mask: no payload expected. ) // UVFileCard represents an "uvfile" card for unversioned file content. type UVFileCard struct { Name string MTime int64 Hash string Size int Flags int Content []byte } func (c *UVFileCard) Type() CardType { return CardUVFile } // UVGimmeCard requests an unversioned file by name. type UVGimmeCard struct { Name string } func (c *UVGimmeCard) Type() CardType { return CardUVGimme } // UVIGotCard announces possession of an unversioned file. type UVIGotCard struct { Name string MTime int64 Hash string Size int } func (c *UVIGotCard) Type() CardType { return CardUVIGot } // PragmaCard represents a "pragma" card for protocol negotiation. type PragmaCard struct { Name string Values []string } func (c *PragmaCard) Type() CardType { return CardPragma } // ErrorCard carries an error message from the server. type ErrorCard struct { Message string // plain text (defossilized) } func (c *ErrorCard) Type() CardType { return CardError } // MessageCard carries an informational message. type MessageCard struct { Message string // plain text (defossilized) } func (c *MessageCard) Type() CardType { return CardMessage } // UnknownCard captures any unrecognized card command. type UnknownCard struct { Command string Args []string } func (c *UnknownCard) Type() CardType { return CardUnknown }