Repository navigation
fix: remediate internal security audit findings across the node stack - #2183
Open
nullPointerEnjoyer wants to merge 180 commits into
Open
nullPointerEnjoyer wants to merge 180 commits into
nullPointerEnjoyer wants to merge 180 commits into
Conversation
block_height_to_postgres_friendly panicked on heights above i64::MAX and the workspace builds with panic=abort, so a single unauthenticated /api/v2/chain/<height> request could abort the whole web-server on postgres deployments. The conversion now returns a typed ApiServerStorageError::BlockHeightTooHigh, propagated from every caller, and chain_at_height rejects out-of-range heights up front with the existing InvalidBlockHeight client error. A CatchPanicLayer is added to the router as defense-in-depth for unwinding builds. Found by internal security audit: WEBSERVER-8-1, WEBSERVER-7-2
check_proof_of_stake only looked at PoSData kernel inputs and never validated the kernel witness vector, which is decoded from the attacker-controlled block header. A block with a valid kernel input and an empty kernel witness vector passed all consensus checks and then hit assert_eq!(inputs.len(), sigs.len()) in the input verifier's CoreContext::new on the block connect path; the workspace builds with panic=abort, so such a block crashed the node. Reject blocks whose kernel witnesses don't match their kernel inputs with a typed consensus error before any state is connected, and replace the assertion with a typed InputCheckError so a future regression in the verifier returns an error instead of panicking. Per-witness authorization of each kernel input remains enforced by the existing full input verification on the connect path. Found by internal security audit: CHAINSTATE-1-1 (H1)
The pending (mempool) transaction rendering built the token decimals
map from the token ids of the outputs alone, while tx_to_json renders
the inputs with the same map and the MintTokens input carries an
amount rendered through it. A consensus-valid relayable transaction
that mints a token it does not also transfer (and whose issuance is
not indexed) left the id missing, so TokenDecimals::get panicked on
expect("must exist") every time the transaction was served from
/api/v2/mempool/transactions or /api/v2/transaction/{id}.
The pending collection now also includes the token ids referenced by
the account command inputs, mirroring the confirmed-path collection
of the scanner; the order-referencing commands are skipped, since
their rendered responses carry no decimal amounts and the referenced
order may itself be pending (unlike the confirmed path, where it is
looked up). The decimals lookup falls back to zero decimals: the
decimals are presentational, the atoms amounts of the responses are
authoritative regardless of them.
Found by internal security audit: WEBSERVER-10-1
Serve header/block requests through a per-peer token bucket; make the whole egress channel chain (frontend commands, per-peer backend events, socket writer queue) bounded; penalize and disconnect peers whose egress queue fills up or whose socket writes time out; remember recent offenses across reconnects so rapid reconnects can't reset ban scores; reject foreign-network peers at the handshake with a small ban score instead of answering with a full HelloAck. Found by internal security audit: H5 (P2P-2-1), L24 (P2P-2-2), L25 (P2P-2-3)
TimestampSearchData::obtain assumed the pool balances map returned by get_stake_pool_balances_at_heights to be contiguous over the requested range and panicked on the first height without an entry; the map is sparse by construction, and a pool decommissioned within the range made the whole node abort (panic=abort). Iterate the map's actual keys and skip the heights where the pool has no (non-zero) balance, carry the height in every search data entry and propagate invariant violations as typed errors instead of expects. Also bound the request: reject a height range longer than MAX_TIMESTAMP_SEARCH_HEIGHT_RANGE heights and a seconds_to_check_for_height above MAX_SECONDS_TO_CHECK_FOR_HEIGHT; both limits surface to RPC callers as errors. Found by internal security audit: BLOCKPROD-10-1, BLOCKPROD-10-2
The reorg rollback deleted the balance, utxo, delegation and similar history of the disconnected blocks, but left their ml.transactions and ml.block_aux_data rows in place, so a transaction of a reorged-out block kept being served as a confirmed one forever, with its confirmations count growing on every new block; the postgres block_aux_data rows were never deleted either, and the in-memory transaction listing could panic on the leftover rows whose aux data was already gone. Add del_transactions_above_height and del_block_aux_data_above_height to the storage trait and both backends, and run them from the reorg disconnect before the main-chain heights are cleared; guard the transaction reads and listings to serve only the transactions whose owning block is on the main chain; bump the storage version so the existing version-mismatch path wipes and rescans the databases that hold the leftover rows. Found by internal security audit: APISTORAGE-6-1, SCANNER-1-1, WEBSERVER-6-1
Round-1 review follow-up of the internal audit fix for the timestamp search (findings H4/M5): - bound the chainstate rewind depth of timestamp search data collection: previously only the requested range length was capped, so a small range far below the chain tip still rewound an unbounded number of blocks under the chainstate lock; the distance from the tip to the range start is now capped as well, and the range validation is consolidated into validate_and_clamp_search_height_range with unit tests - report the caller-supplied max_height in WrongHeightRange instead of the clamped one, so the error reflects what was actually sent - assert in test_decommissioned_pool that find_timestamps_for_staking keys its results by the heights carried by the sparse search data - document the request caps in the wallet controller, wallet RPC interface and CLI command docs - add a changelog entry for the panic fix, the new caps and the TimestampSearchData encoding incompatibility across versions
The pool/delegation reads were made point-in-time for block connect, but order and fungible token issuance reads still served the latest history row: the fill/conclude/freeze order commands read the order and every token account command read the issuance before mutating state, so a row written by a block above the connected height would silently drift the indexed token supply and order balances during replay. Add get_order_at_or_below_height and get_fungible_token_issuance_at_or_below_height to the storage trait with postgres and in-memory implementations mirroring the pool variant, cover both with a shared-suite test alongside the existing pool/delegation point-in-time test, and switch the connect-path reads (transaction state updates, order prefetch for fee checks, order token id collection and the secondary history re-derivation) to the bounded reads. Order::freeze returns a typed error instead of asserting on an already frozen order. Found by internal security audit: APISTORAGE-10-2, SCANNER-10-3, SCANNER-6-6
The node-supplied common ancestor and the scan inputs are now validated with typed errors returned to the caller instead of assertion failures, so a misbehaving remote node (WalletType::Remote) cannot panic the wallet worker. An account already at the node tip is handled as the common block itself. Height arithmetic on the sync and scan paths uses checked conversions with typed errors. Found by internal security audit: WALLET-10-1, WALLET-10-2
The decoded Argon2id memory size, iteration count, parallelism and hash length now have generous upper bounds enforced before they drive allocations or computation, so a crafted wallet file cannot trigger a multi-GiB allocation. Legitimately-created files are still accepted. Found by internal security audit: CRYPTO-10-1
Trezor-produced single-sig witnesses are now verified with the same local check the Ledger and software paths use before the input is marked fully signed. Found by internal security audit: WALLET-3-2
The --history-file command history, which can contain the seed phrase, is now restricted to 0600 on creation and on every start. The insecure warning stays in place. Found by internal security audit: WALLET-5-1
Newly created wallets now use 64 MiB of Argon2id memory instead of 16 MiB. The KDF parameters are stored per wallet file, so existing files keep opening with their stored values. Found by internal security audit: WALLET-5-2
The cookie file is now written to a randomly named temporary file that is created exclusively with owner-only permissions and atomically renamed, instead of a predictable .tmp name opened without truncate. Found by internal security audit: WALLET-5-3
Apply backpressure instead of punish-on-full on the egress path: the peer task now awaits the capacity of the socket writer queue, throttling the message producers to the rate at which the peer reads, so honest peers on slow links are no longer penalized; the backend disconnects a peer whose event queue overflows without a ban score, and the socket write timeout remains the sole slow-reader punishment. The unused EgressQueueFull protocol error is removed. Serve header and block requests by pacing them to the serving refill rate instead of refusing over-budget requests with a ban score, which punished honest fast syncers; only a request whose serving weight exceeds the whole serving budget bucket (a test-only misconfiguration, now clamped) is refused with a ban score. The writer close handling is factored out so a write timeout that closes a full writer queue is still reported. Found by internal security audit: review round 1 findings on B1-p2p-resource-quality (H5, L24, L25 follow-ups)
ml.nft_issuance.owner was derived as a side effect of the address balance and locked-balance writes, which the scan flushes aggregated in BTreeMap (address-string) key order at the same block_height: a same-block NFT transfer persisted the owner of whichever address happened to be flushed last, i.e. NULL about half the time, and a timelock expiry always ended owner NULL because the locked-balance write (amount zero, owner NULL) ran after the available-balance write (owner Some). The web server serves the owner straight from that row. Stop deriving the owner from the flush: drop the update_nft_owner side effect from set_address_balance_at_height and set_address_locked_balance_at_height in both backends, and add an explicit set_nft_token_owner storage write (versioned like the issuance rows) that the scan calls at the output-processing sites in transaction/output order: the recipient on a Transfer or LockThenTransfer output that pays the NFT (and the IssueNft issuance row as before), None when a matching input is consumed, so a burned NFT has no owner while a same-transaction pay-forward restores it. Add end-to-end scan tests: an NFT transferred issuer -> A -> B inside one block must serve B (both transfer addresses sort before the issuer's, the configuration that previously persisted NULL), and an NFT received under a block-count lock must keep its owner through the unlock. Rework the storage suite's set_get NFT section to the new contract: balance writes leave the owner untouched and only set_nft_token_owner moves it, including same-height overwrites and the versioned rollback via del_nft_issuance_above_height. Found by internal security audit: SCANNER-7-1
The experimental trusted-fee path takes per-transaction fees verbatim from the node's block_tx_fees RPC into AccumulatedFee::from_coin_fee and sums them into the total that is credited to the Staked statistic and the pool/delegation reward accounting, with no validation: fees are unsigned amounts (a negative entry cannot deserialize), but an absurdly large entry overflows the reward arithmetic, whose (block_subsidy + total_tx_fees).expect and the combine/map_into_block expects panic mid-batch, rolling the batch back on every retry and wedging the sync loop forever. Bound the values before use: per-transaction and per-block fee caps (just above the whole possible coin supply, which no legitimate fee payable from existing coins can reach, and far below the u128 accumulation range) reject a bad batch with typed TrustedFeeOutOfRange/TrustedBlockFeeOutOfRange errors, loudly logged; the reward-path expects (subsidy plus fees, fee combination and projection, reward distribution, delegation and pool balance updates) return typed FeeArithmeticOverflow/RewardDistributionError errors instead of panicking, so supervise_sync drops the batch and re-fetches it with escalating backoff. The pool-missing lookups keep the LowLevelStorageError convention used by the rest of the connect path. Cover with fee tests: a per-transaction fee above the cap is rejected with the scan staying at the common ancestor and a plain re-fetch succeeding, per-transaction fees below the cap that sum above the per-block cap are rejected before the reward distribution, and a sane trusted fee is indexed exactly as supplied. Found by internal security audit: SCANNER-6-2
Expired ml.locked_utxo rows are never removed, so their retention has to be a deliberate, test-enforced decision rather than an accident: the row is the replay source for the unlock transition. A reorg that disconnects blocks above the expiry height rolls the balance moves and the unlocked UTXO rows back, and reconnecting the expiry block re-drives them from get_locked_utxos_until_now; purging the row when it expires (as the retention cleanup would naturally do) would permanently lose the unlock on such a reorg - the balance would stay locked and the UTXO unservable. Rows are only ever removed by the reorg cleanup above the lock's creation height, which also covers the expired ones once the lock's creation itself is disconnected. Document the semantics on the storage trait reads/writes and at the expiry-processing site, and add a scan test that reorgs across the expiry height and proves the retained row re-drives the unlock: the balance and the spendable UTXO are restored on reconnect, and the expired row is still served by get_locked_utxos_until_now. Found by internal security audit: SCANNER-6-4
Inbound connections get a fresh peer ID each, so the per-peer orphan pool quota (10 entries) could be multiplied by opening more connections from one IP: ten connections times ten junk orphans saturated the aggregate pool cap and locked honest peers out until expiry, while eviction never touched the attacker's protected entries. The per-peer reservation is now keyed by the remote IP address for inbound connections (all of one address's connections share one reservation), while outbound peers keep their per-peer quota; this is the smaller change next to stacking a second per-IP cap, because the orphan pool already keys its accounting by transaction origin: making inbound origins compare by their canonical address (the same key bans use) gives shared counting, reservation and eviction for free. The peer ID is still carried for punishment, event reporting and disconnect cleanup, so peer teardown now removes a connection's orphans by peer ID instead of by origin key. The fail-closed policy is unchanged: a full pool still rejects a newcomer instead of displacing protected entries. Found by internal security audit: M6 (TXLAYER-4-1)
Derive the trusted-fee sanity caps from the chain config instead of the hardcoded 1e20-atom bound: the caps are twice the total supply (the coin amounts minted by the genesis outputs plus the emission schedule's final issuance), so every consensus-valid fee stays inside the cap on each built-in chain. The old hardcoded cap sat far below the Babbage testnet genesis mint (1e20 vs 4e24 atoms), so a consensus-valid testnet fee above 1e9 TML made every batch re-fetch fail TrustedFeeOutOfRange or TrustedBlockFeeOutOfRange and the scanner stalled permanently on a valid block. Chains with a nonzero tail subsidy have no finite total supply; their caps fall back to Amount::MAX, where the typed accumulation-overflow errors remain as the backstop. The caps rationale comment is corrected accordingly: mainnet total supply is ~6.0e19 atoms, not the previously claimed 4.1e17 atoms, and the supply bound is now stated per chain config instead of a single figure.
The address history (transaction_history of /api/v2/address/{address}),
the spendable and all UTXO listings and the delegations listings of an
address and a pool materialized the complete history of the queried
entity on every request, so any unauthenticated client could turn one
request into an arbitrarily large response (all the other listings are
already capped at 100 rows per page by the shared page parser).
The rows of these endpoints are now capped at 1000 per response; when
the cap truncates the result, the response carries a `truncated` flag,
so a partial listing is never silently presented as complete: an
additive field for the object-shaped address response (the same pattern
as the order book listing) and an object wrapping the rows for the
array-shaped ones, which keep their plain array form in the common
non-truncated case.
Found by internal security audit: APISTORAGE-7-2
POST /api/v2/transaction passed the error text of the connected node verbatim to unauthenticated clients, disclosing internal details (the node's state and configuration, the exact mempool rejection reasons). The detail is now kept in the server log and the client receives the generic "Transaction submission failed" client error. Found by internal security audit: WEBSERVER-8-4
The API served CORS responses with allow-origin: * and validated neither the Origin nor the Host header, so any web page the operator visits could read the responses of (and fire requests into) the default localhost-bound API from the operator's browser, and a DNS rebinding attack could reach it under an attacker-chosen host name. Requests carrying an Origin header are now rejected with 403 unless they come from the origin of the server itself or from another loopback address (local tools on the same machine); on loopback-bound deployments the Host header must additionally name a loopback host on the listening port, which defeats rebinding. Non-browser traffic (no Origin header) is unaffected; operators intentionally exposing the API to browser clients from other origins are expected to strip or rewrite the Origin header at their reverse proxy, as documented in the README (new "Browser access and cross-origin requests" section). The subscriber cap of the SSE event stream was also global-only (128 slots): a single client could hold every slot with idle connections and lock all other clients out of the stream. A per-client-IP cap of 16 subscriptions now applies alongside the global one, and the slots are released when the client disconnects. Found by internal security audit: WEBSERVER-8-3, WEBSERVER-8-5
The crawler logged one info line per unsolicited AddrListResponse with no rate limit, so a hostile peer could flood the crawler log with one line per message by sending unsolicited responses in a tight loop. The log line is now rate limited per peer (a small burst, then at most one line per minute); the suppressed lines are demoted to the debug level. Found by internal security audit: WEBSERVER-10-2, INFRA-10-1
The RPC auth layer logged one error line per unauthenticated or malformed request, so a hostile client could flood the log with one line per request while changing no state; the lines are now logged at the debug level. Found by internal security audit: WEBSERVER-10-3
Demote per-message log lines that a peer could trigger at socket rate (unsolicited/duplicate/over-limit transaction announcements and responses, repeated address list requests, block requests during the initial block download) to the debug level. Bound the volume of messages that are only ignored by token buckets that mirror the address announcement rate limiter: unsolicited transaction responses and repeated address list requests that exceed the tolerated rate accrue ban score, so a sustained flood gets the peer discouraged and disconnected. Block requests that arrive while the node is in the initial block download now return an error with a non-zero ban score instead of being ignored. Skip score adjustments for peers that are already being disconnected and log score adjustments at the debug level, so the punishment path itself can't be turned into a per-message log source. Found by internal security audit: M7 (P2P-10-1), M7 (P2P-10-2), M7 (P2P-10-3)
The 1000-row cap of the unpaginated listings was response-only: the backing storage queries still materialized and transferred the complete history of the queried entity before the web layer truncated the result. The five capped listing reads (address transactions, spendable/all UTXOs, delegations from an address, pool delegation shares) now take a max_rows parameter that both backends enforce in the read itself: LIMIT in the Postgres queries, take() in the in-memory backend. The web layer reads cap+1 rows and keeps the existing truncated-flag contract and response shapes. The capped reads pick a deterministic subset (delegation-id order for the delegation listings, outpoint order for the UTXO listings, block-height with transaction-id tiebreak for the history) so repeated truncated responses are stable. Found by internal security audit: APISTORAGE-7-2 (C6 review round 1)
ChainstateConfigFile now derives serde(deny_unknown_fields), and ChainstateLauncherConfigFile deserializes through an unflattened shadow struct, because serde silently drops deny_unknown_fields for a struct read through serde(flatten). A typo'd key in the [chainstate] config section is now a parse error instead of a silently ignored default; parsing tests cover the direct and section paths. Found by internal security audit: INFRA-9-1
The release and static-checks workflows pinned actions by mutable tags or branch refs; every actions/*, docker/*, dtolnay/rust-toolchain and ncipollo/release-action reference is now pinned to the full commit SHA, taken from the action repositories' refs. The release and static-checks workflows that lacked an explicit permissions block are bound to contents: read (release.yml keeps contents: write for creating the release). Found by internal security audit: INFRA-9-2, INFRA-10-5, INFRA-9-5
The GitLab gate installed whatever cargo-deny release was current at install time, so the GitLab and GitHub checks could run different tool versions against different advisory data; it now uses the same pinned cargo-deny 0.21.0 as the GitHub static-checks workflow. Found by internal security audit: INFRA-10-2
The CacheInvariantViolation error of the undo caches is a bug in the node's own cache, so it must not discourage the counterparty: descend into the wrapped undo error in the ban score arms and give the invariant violation a ban score of 0, consistent with its General classification. The detail of the inner cache operation error is embedded in the violation message to keep it available for diagnostics.
A failed peer task used to just end, leaving the connection to linger until the peer sent its next inbound message, with the stalling detection for that peer inactive in the meantime. Instead, ask the peer manager to disconnect the peer with the peer DB record kept, so no ban score is applied.
Phase A of the bounded subscription test never asserted the number of received events and could pass trivially if the stream ended early. Assert the received count matches the expected number of events and drop the leftover debug prints.
Convert the leftover storage-read expects in the in-memory disconnect loop to propagated InMemoryReorgError values, consistent with the surrounding error propagation, and update the empty-chainstate test that still expected the removed best-block-id panic.
The catch-all arm of the encryption state probe swallowed all remove_private_key_encryption failures and misreported the wallet as unencrypted. Log the swallowed error and surface it instead, so e.g. a WalletCorruptedData failure during re-encryption is reported to the user.
Store a root key and a seed phrase blob encrypted with a key unknown to the store and assert that get_root_key/get_seed_phrase fail with WalletCorruptedData instead of panicking.
The method list and the subsystem RPC interface description tests were not updated when the bounded subscription methods were introduced.
- move trezor check_session device I/O into the timed blocking region so a wedged device cannot freeze the wallet task before the operation timeout - raise the shutdown drain window above the worst-case in-flight unit and wait for the worker to join instead of a fixed sleep - surface a terminal event when a background sync iteration panics instead of silently answering no-wallet-opened - mempool.transactions: replace the silent empty-page-on-evicted-cursor contract with a typed cursor-expired error, restart-once pagination in the node client, and a bounded page-iteration budget
- run the trezor provider construction on wallet open, recover and create inside the timed blocking region: device search, session setup and the expected public key fetch now report a typed DeviceOperationTimeout on a wedged device instead of blocking the wallet task forever - acquire the device client mutex only inside the bounded region (the blocking std lock previously ran on the wallet task on the open path) - bound the account public key fetch in make_new_account the same way, so wallet create/recover cannot hang past the device operation timeout at account creation either - scope the SHUTDOWN_TIMEOUT comment to the termination guarantee it provides
…supported variants cleanly
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Remediates the findings of an internal end-to-end security audit of the node stack (consensus and chainstate, p2p networking, transaction handling, wallet, indexer, storage, web server/RPC, deployment), plus the residual items surfaced by two hint-free re-audits of the remediated tree.
High-severity fixes
assert_eq!on the connect path (workspace builds withpanic = "abort", so the old behavior was a network-wide node kill from a single produced block). Rejection happens incheck_proof_of_stakebefore any storage access; the connect-path assert becomes a typed error as defense in depth.GET /api/v2/chain/:heightfor heights above the postgresi64range: heights are bounded at the handler, the storage conversion returns a typed error instead of panicking, and aCatchPanicLayeris installed as defense in depth.0.ml.transactionsandml.block_aux_dataare deleted on disconnect (both storage backends, in one transaction), every transaction read verifies main-chain membership, and the storage version bump forces a rescan so stale rows cannot survive.Other fixes (selection)
NULLowner), trusted fees are bounded and no longer wedge the scanner, genesis Burn is counted, exotic genesis spends produce typed batch errors instead of crashes, the daemon takes a single-writer advisory lock, andml.locked_utxoexpiry lookup is indexed.circulating_supplyreconciles with the sum of served balances; a spent data-deposit counter correction and afungible_token.authoritysame-height rewrite fix close the remaining drift paths.Hostvalidation (DNS rebinding), node error text no longer echoed to clients, capped unpaginated listings with atruncatedflag, and exact pagination-cursor key-count enforcement.SharedSecret/SymmetricKeydebug output redacted, KDF parameters bounded at decode, derivation-path and KDF-length truncations made self-defending, hardware-wallet signatures verified locally, seed-phrase purgeVACUUMs the database, CLI history files get0600, node-supplied sync data is validated instead of asserted.--lockedand default to a versioned tag, unknown[chainstate]config keys are rejected, packaged env files installed0600, andsnowupdated to 0.9.7 (RUSTSEC-2026-0626).Storage version
Bumped
CURRENT_STORAGE_VERSIONto 31 (this branch supersedes the version 29 bump from #2181, which is included here): scanners reinitialize and rescan on the next start, rebuilding address balances, holders, statistics (including the new open-HTLC and open-order buckets) and the token authority column.Tests
Based on #2181 (included via master); the block-reward debit and the new statistics buckets are verified together by the reconciliation tests.