fix(crypto): address audit findings in crypto module

FE
7d ago
+1622-210

What does this PR do?

Harden crypto helpers and keystore handling, and make BN128 coordinate and scalar-input assumptions explicit.

Keccak / digest engine

  • Copy the complete Keccak state through the DigestEngine override. Reject null or incompatible destinations before modifying them, checking the Keccak type, algorithm, digest length, and internal block length.
  • Cache the digest length in a final field, clear the input buffer and temporary Keccak output on reset, and document constructor initialization and padding requirements.

Keystore / wallet

  • Decode password files and piped stdin as strict UTF-8. Reject replacement characters and non-ASCII console passwords when the detected console encoding is not UTF-8 or is unknown; clear console password arrays after use.
  • Validate wallet-creation inputs before scrypt, including the password, signing key, private-key encoding/value, and supported KDF parameters. Wrap derivation failures in CipherException; address/private-key consistency remains the caller's responsibility during creation.
  • Validate required wallet fields, address/hex encodings, IV/MAC/ciphertext lengths, KDF parameter types, salt size, and supported derivation bounds before decryption or discovery. PBKDF2 uses its validated declared dklen.
  • Atomically create temporary wallet files with CREATE_NEW and 0600 permissions. Serialize through the creating channel, force the temporary file contents, close the channel, and replace the destination using the existing atomic-move/fallback behavior. Do not reopen the temporary path for writing.
  • Use the base branch's directory-creation flow. Directories are not opened as channels for syncing.
  • Share password-input checks across the CLI flows. Accept an optional lowercase 0x prefix in StringUtil.isHexadecimal, while rejecting non-ASCII hex.

Blake2bf / ECKey / JCE

  • Validate the Blake2bf output buffer before compression, honor the requested output offset, and disable the inherited shallow clone that shared mutable digest state.
  • While signing, skip recovery candidates that are not curve points instead of aborting the recovery-id search. Document transaction recovery ids 2 and 3 (v = 29/30) separately from the precompile's component restrictions.
  • Include v in ECDSASignature.equals and hashCode; make MissingPrivateKeyException an IllegalStateException and clarify recovery exceptions.
  • Require a 65-byte uncompressed public-key encoding for normal address derivation. Preserve the historical address for legacy signature recovery's single-zero-byte infinity encoding.
  • Use TronCastleProvider explicitly in provider-less key-generation and raw-signature helpers, avoiding the JDK default provider's secp256k1 limitations.

BN128 safety contracts

  • Use a dedicated G2Homogeneous running-point type in the flipped Miller loop, initialized from an affine point, to keep homogeneous coordinates separate from Jacobian group operations.
  • Reject negative Java scalar arguments to BN128.mul.
  • Keep Fp2/Fp6/Fp12 arithmetic and the G2 subgroup check identical to the base branch.

Why are these changes required?

These changes address crypto audit findings: incomplete digest-state copies, retained buffers, lossy credential decoding, unsafe temporary-path reopening, and malformed inputs reaching cryptographic routines. They also make coordinate and validation contracts explicit.

Directory crash durability is outside this PR's scope. The wallet-write changes protect temporary-file creation and writing while preserving the base branch's directory handling.

This PR has been tested by:

Local validation used macOS with an x86_64/JDK 8 runtime:

  • 108 focused Gradle tests passed across WalletUtilsWriteTest, KeystoreCliUtilsTest, KeystoreNewTest, KeystoreImportTest, and KeystoreUpdateTest.
  • Focused Gradle regression tests passed for FpTest, Fp12Test, PairingCheckTest, and IstanbulTest.altBn128PairingEnergyChangeTest. 17 tests passed.
  • Outputs from this revision and the base branch matched for 128 Fp2 arithmetic cases, 32 arbitrary twist points with full-order subgroup/cofactor checks, 18 pairing cases, and 38 Keccak cases including copy/reset/output-offset checks.
  • Regression coverage includes malformed password bytes and wallet schemas, incompatible digest copies, reset clearing, temporary-file sync failure before replacement, successful writes without directory reads, temporary-path replacement by files/symlinks, filename collisions, and unsupported atomic permissions.
  • ./gradlew clean build -x test, the CI Checkstyle tasks (:framework:checkstyleMain :framework:checkstyleTest :plugins:checkstyleMain), the Math usage check, and git diff --check passed.

These focused runs overlap and do not represent a full-suite or multi-platform result.

Follow up

  • Complete multi-platform CI and review. The full test suite and Linux/ARM64-JDK 17 validation were not run locally.
  • Complete historical replay validation.

Extra details

Consensus impact

Review of 66540cd113 against release_v4.8.3 at 8d18edc4a6 found no reachable change to block or transaction acceptance, TVM outputs, or Energy pricing. On this evidence, the change does not require a protocol activation height.

  • The BN128 multiplication precompile decodes its scalar as unsigned. The pairing path handles points at infinity before the Miller loop and converts finite points to affine coordinates before the new z = 1 check.
  • The recovery-ID change affects local signing. Transaction and block verification already accept the recovery IDs it can produce. Address derivation accepts the uncompressed public keys returned by recovery and preserves the historical address for the single-zero-byte infinity encoding in legacy mode.
  • Consensus callers compute Keccak digests directly. The Blake2bf precompile uses a fresh digest with output offset zero. Neither path relies on the copy or nonzero-offset behavior changed here.

The focused tests and differential comparisons above support this assessment. Historical block replay and mixed-version node validation have not been performed for this revision.

Compatibility and upgrade impact

  • Nodes and clients. The diff introduces no P2P or protobuf encoding, RPC schema, database format, or configuration-key change. No chain database migration is required.
  • SR keystores. V3 files generated with the base version’s default parameters remain readable. Some imported files that previously unlocked can now fail validation. For example, the base decoder padded odd-length hex fields, and the PBKDF2 path always derived 32 bytes even if the file declared dklen = 16. The new reader rejects both forms. If an SR uses such a file, startup fails with WITNESS_KEYSTORE_LOAD. Before upgrading an SR, unlock a copy of its configured keystore offline with the new version and verify the derived witness key address.
  • Passwords and discovery. New wallets require at least six characters. An existing wallet with a shorter password can still be decrypted through Wallet.decrypt. CLI password files and piped input require valid UTF-8. Imported files with an absent or empty address can still be decrypted by path when their other fields are valid, but keystore discovery skips them.
  • Wallet writes. Creating or replacing a keystore requires a filesystem that can set mode 0600 atomically at file creation. A temporary-file sync failure preserves the existing wallet. As on the base branch, directory entries can be lost after sudden power loss, and the wallet directory must be trusted.
  • Java callers. WalletUtils.getWalletFileName is now private. Blake2bf cloning is unsupported. ECDSASignature.equals and hashCode include the recovery byte v, which can change deduplication results. The protected Keccak copyState parameter changes to DigestEngine. Downstream callers or subclasses using these APIs may need source changes or recompilation.