Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/workflows/v2-security-regression.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion internal/api/certified_block_delivery.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")

Expand Down
19 changes: 19 additions & 0 deletions internal/consensus/messages.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,19 @@ 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.
// Together with tx.MaxEnvelopeJSONBytes this bounds the transaction portion
// 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"`
Expand Down Expand Up @@ -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 == "" {
Expand Down
20 changes: 20 additions & 0 deletions internal/consensus/vote_wire_size_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
})
}
}
59 changes: 59 additions & 0 deletions internal/ledger/certified_delivery_budget.go
Original file line number Diff line number Diff line change
@@ -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
}
55 changes: 55 additions & 0 deletions internal/ledger/certified_delivery_budget_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
3 changes: 3 additions & 0 deletions internal/ledger/certified_import.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
3 changes: 3 additions & 0 deletions internal/ledger/consensus_state.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
3 changes: 3 additions & 0 deletions internal/ledger/store.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
Loading