diff --git a/.github/workflows/v2-security-regression.yml b/.github/workflows/v2-security-regression.yml index a93d3473..12e63208 100644 --- a/.github/workflows/v2-security-regression.yml +++ b/.github/workflows/v2-security-regression.yml @@ -70,6 +70,8 @@ jobs: run: go test -race ./internal/api -run '^TestCertifiedCatchupRequiresTypedHTTPConflict$' -count=30 -timeout=4m - name: Protocol wire-size envelope and block transaction caps run: go test -race ./internal/tx ./internal/consensus ./internal/ledger ./internal/api -run '^(TestEnvelopeWireSizeIncludesActualJSONEscapingAndSignedPayload|TestConsensusProposalRejectsExcessiveTransactionCountBeforeSignatureWork|TestLedgerRejectsOversizedMempoolEnvelopeBeforePersistence|TestLedgerRejectsImportedBlockWithMoreThanConsensusTransactionCap|TestProtocolWireLimitViolationsReturnRequestTooLarge)$' -count=10 -timeout=4m + - name: Fail-closed pre-quorum certified delivery size budget and signed vote bounds + run: go test -race ./internal/consensus ./internal/ledger -run '^(TestCertifiedDeliveryBudget|TestSignedVoteWireSize)' -count=10 -timeout=4m - name: Outbound certified finality must honor exact JSON body cap run: go test -race ./internal/api -run '^TestSignedCertifiedOutboundRejectsOversizedJSONBeforeNetwork$' -count=1 -timeout=4m - name: Bound signed certified finality HTTP bodies before proof and JSON decoding diff --git a/internal/api/certified_block_delivery.go b/internal/api/certified_block_delivery.go index c0de4735..4076b126 100644 --- a/internal/api/certified_block_delivery.go +++ b/internal/api/certified_block_delivery.go @@ -20,7 +20,7 @@ type certifiedBlockDelivery struct { // each peer request. Even an admitted validator must not force unbounded // decoding, hashing or memory use in the finality import path. This limit // applies to both declared Content-Length and streaming/chunked bodies. -const maxCertifiedBlockDeliveryBytes int64 = 64 << 20 +const maxCertifiedBlockDeliveryBytes int64 = ledger.MaxCertifiedDeliveryJSONBytes var errCertifiedDeliveryTooLarge = errors.New("signed certified block payload exceeds transport byte limit") diff --git a/internal/consensus/messages.go b/internal/consensus/messages.go index 2c601d21..b39b6e4d 100644 --- a/internal/consensus/messages.go +++ b/internal/consensus/messages.go @@ -30,6 +30,7 @@ var ( ErrTransactionMismatch = errors.New("proposal transactions do not match transaction IDs") ErrHashMismatch = errors.New("block hash does not match proposal fields") ErrTooManyTransactions = errors.New("consensus block exceeds transaction count limit") + ErrSignedVoteTooLarge = errors.New("signed consensus vote exceeds wire byte limit") ) // MaxConsensusBlockTransactions caps both proposed and imported blocks. @@ -37,6 +38,11 @@ var ( // of signed certified delivery well below the endpoint's HTTP body limit. const MaxConsensusBlockTransactions = 512 +// MaxSignedVoteJSONBytes reserves a deterministic conservative per-validator +// allowance in prospective certified block delivery. Applies to encoded JSON, +// including escape expansion, before any peer signature verification. +const MaxSignedVoteJSONBytes int64 = 4 << 10 + type Proposal struct { ChainID string `json:"chainId"` Domain string `json:"domain"` @@ -228,6 +234,19 @@ func (v Vote) CanonicalPayload() string { } func (v Vote) ValidateStatic() error { + // Reject unexpectedly large signed vote payloads before cryptographic + // verification; the same cap is used by ledger pre-quorum budgeting. + var rawSize int64 + for _, part := range []string{v.ChainID, v.Domain, v.BlockHash, v.Voter, v.Payload, v.PublicKey, v.Signature} { + if int64(len(part)) > MaxSignedVoteJSONBytes-rawSize { + return ErrSignedVoteTooLarge + } + rawSize += int64(len(part)) + } + encoded, err := json.Marshal(v) + if err != nil || int64(len(encoded)) > MaxSignedVoteJSONBytes { + return ErrSignedVoteTooLarge + } chainID := strings.TrimSpace(v.ChainID) domain := strings.TrimSpace(v.Domain) if chainID == "" || domain == "" || v.BlockHash == "" || v.Voter == "" || v.Payload == "" || v.PublicKey == "" || v.Signature == "" { diff --git a/internal/consensus/vote_wire_size_test.go b/internal/consensus/vote_wire_size_test.go new file mode 100644 index 00000000..af3085f5 --- /dev/null +++ b/internal/consensus/vote_wire_size_test.go @@ -0,0 +1,20 @@ +package consensus + +import ( + "errors" + "strings" + "testing" +) + +func TestSignedVoteWireSizeRejectsJSONEscapingAndExcessivePayload(t *testing.T) { + for _, tt := range []struct{ name, payload string }{ + {"raw bytes above cap", strings.Repeat("a", int(MaxSignedVoteJSONBytes)+1)}, + {"JSON escaping above cap", strings.Repeat("\x00", int(MaxSignedVoteJSONBytes/2))}, + } { + t.Run(tt.name, func(t *testing.T) { + if err := (Vote{Payload: tt.payload}).ValidateStatic(); !errors.Is(err, ErrSignedVoteTooLarge) { + t.Fatalf("oversized vote should fail before crypto verification, got %v", err) + } + }) + } +} diff --git a/internal/ledger/certified_delivery_budget.go b/internal/ledger/certified_delivery_budget.go new file mode 100644 index 00000000..e0dd2231 --- /dev/null +++ b/internal/ledger/certified_delivery_budget.go @@ -0,0 +1,59 @@ +package ledger + +import ( + "encoding/json" + "errors" + + "github.com/zephyr-chain/zephyr-chain/internal/consensus" +) + +// MaxCertifiedDeliveryJSONBytes is a consensus admission invariant as well +// as the transport's byte limit. A node must not finalize a block whose +// transferable proof could be rejected by a correctly configured peer. +const MaxCertifiedDeliveryJSONBytes int64 = 64 << 20 + +// The wrapper {"block":...,"evidence":{"proposal":...,"votes":[...]}} +// has fewer than 128 bytes of fixed JSON punctuation/property names. Count +// one comma per vote; the estimate deliberately reserves a conservative +// maximum serialized size for EVERY authorized validator, not only quorum. +const certifiedDeliveryWrapperBudget int64 = 128 + +var ErrCertifiedDeliveryBudget = errors.New("certified block exceeds protocol delivery byte budget") + +// certifiedDeliveryBudgetFits uses subtraction to avoid integer overflow when +// computing the worst case for an attacker-controlled validator roster. +func certifiedDeliveryBudgetFits(blockBytes, proposalBytes, validators int64) bool { + if blockBytes < 0 || proposalBytes < 0 || validators < 0 || + blockBytes > MaxCertifiedDeliveryJSONBytes-certifiedDeliveryWrapperBudget { + return false + } + remaining := MaxCertifiedDeliveryJSONBytes - certifiedDeliveryWrapperBudget - blockBytes + if proposalBytes > remaining { + return false + } + remaining -= proposalBytes + return validators <= remaining/(consensus.MaxSignedVoteJSONBytes+1) +} + +// checkCertifiedDeliveryBudget is deliberately called before a proposal is +// recorded/voted, and again on certificate-backed block imports. Both the +// signed proposal and block encode the transactions; measuring only one would +// underestimate the actual authenticated delivery JSON. Every signed vote is +// independently bounded in consensus.Vote.ValidateStatic(). +func checkCertifiedDeliveryBudget(proposal consensus.Proposal, validatorCount int) error { + if validatorCount < 0 { + return ErrCertifiedDeliveryBudget + } + blockJSON, err := json.Marshal(blockFromProposal(proposal)) + if err != nil { + return ErrCertifiedDeliveryBudget + } + proposalJSON, err := json.Marshal(proposal) + if err != nil { + return ErrCertifiedDeliveryBudget + } + if !certifiedDeliveryBudgetFits(int64(len(blockJSON)), int64(len(proposalJSON)), int64(validatorCount)) { + return ErrCertifiedDeliveryBudget + } + return nil +} diff --git a/internal/ledger/certified_delivery_budget_test.go b/internal/ledger/certified_delivery_budget_test.go new file mode 100644 index 00000000..996b1d94 --- /dev/null +++ b/internal/ledger/certified_delivery_budget_test.go @@ -0,0 +1,55 @@ +package ledger + +import ( + "errors" + "strings" + "testing" + + "github.com/zephyr-chain/zephyr-chain/internal/consensus" + "github.com/zephyr-chain/zephyr-chain/internal/tx" +) + +func TestCertifiedDeliveryBudgetExactBoundaryAndOverflow(t *testing.T) { + const limit = MaxCertifiedDeliveryJSONBytes + const wrapper = certifiedDeliveryWrapperBudget + const vote = consensus.MaxSignedVoteJSONBytes + 1 + tests := []struct { + name string + block, proposal, validators int64 + want bool + }{ + {"exact total transport budget", limit - wrapper, 0, 0, true}, + {"one over total transport budget", limit - wrapper + 1, 0, 0, false}, + {"exact one validator allowance", limit - wrapper - vote, 0, 1, true}, + {"one byte short for vote", limit - wrapper - vote + 1, 0, 1, false}, + {"negative block rejected", -1, 0, 0, false}, + {"negative validator count rejected", 0, 0, -1, false}, + {"attacker-count overflow rejected", 0, 0, int64(^uint64(0) >> 1), false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := certifiedDeliveryBudgetFits(tt.block, tt.proposal, tt.validators); got != tt.want { + t.Fatalf("fits(%d,%d,%d)=%v, want %v", tt.block, tt.proposal, tt.validators, got, tt.want) + } + }) + } +} + +func TestCertifiedDeliveryBudgetCountsDuplicatedEscapedTransactionsAndWorstCaseVotes(t *testing.T) { + p := consensus.Proposal{ + Transactions: make([]tx.Envelope, consensus.MaxConsensusBlockTransactions), + TransactionIDs: make([]string, consensus.MaxConsensusBlockTransactions), + } + for i := range p.Transactions { + // Escapes expand on JSON serialization, and proposal and block each + // carry the same transaction vector. Do not budget only memo bytes. + p.Transactions[i].Memo = strings.Repeat("\\", 2048) + p.TransactionIDs[i] = strings.Repeat("a", 64) + } + if err := checkCertifiedDeliveryBudget(p, 20); err != nil { + t.Fatalf("bounded 512-transaction / 20-validator candidate rejected: %v", err) + } + if err := checkCertifiedDeliveryBudget(p, 20000); !errors.Is(err, ErrCertifiedDeliveryBudget) { + t.Fatalf("oversized validator roster must reject before voting, got %v", err) + } +} diff --git a/internal/ledger/certified_import.go b/internal/ledger/certified_import.go index 5c0c28f6..8ee70f14 100644 --- a/internal/ledger/certified_import.go +++ b/internal/ledger/certified_import.go @@ -184,6 +184,9 @@ func attachCertifiedBlockEvidence(state persistedState, block Block, evidence Ce if err := proposal.ValidateForChain(chainID); err != nil { return state, ErrCertifiedEvidenceInvalid } + if err := checkCertifiedDeliveryBudget(proposal, len(state.ValidatorSnapshot.Validators)); err != nil { + return state, err + } if proposal.Height != block.Height || proposal.BlockHash != block.Hash || proposal.StateRoot != block.StateRoot { return state, ErrCertifiedEvidenceInvalid } diff --git a/internal/ledger/consensus_state.go b/internal/ledger/consensus_state.go index a600c6bb..38626892 100644 --- a/internal/ledger/consensus_state.go +++ b/internal/ledger/consensus_state.go @@ -151,6 +151,9 @@ func recordProposalIntoState(state persistedState, proposal consensus.Proposal, if len(state.ValidatorSnapshot.Validators) == 0 { return state, ErrNoValidatorSet } + if err := checkCertifiedDeliveryBudget(proposal, len(state.ValidatorSnapshot.Validators)); err != nil { + return state, err + } if proposal.Height != uint64(len(state.Blocks))+1 { return state, ErrConsensusHeightMismatch } diff --git a/internal/ledger/store.go b/internal/ledger/store.go index 2c2a2266..4a15940a 100644 --- a/internal/ledger/store.go +++ b/internal/ledger/store.go @@ -846,6 +846,9 @@ func validateBlockConsensus(state persistedState, block Block, requireCertificat if proposal == nil { return ErrConsensusTemplateMismatch } + if err := checkCertifiedDeliveryBudget(*proposal, len(state.ValidatorSnapshot.Validators)); err != nil { + return err + } if proposal.PreviousHash != block.PreviousHash { return ErrConsensusPreviousHash }