Clean minimalist engineering illustration showing an EIP-712 cryptographic seal locked by chainId, verifyingContract, nonce, and deadline on dark slate.
Cryptographic authorization: binding off-chain intents to unforgeable on-chain execution boundaries.

Summary: Off-chain cryptographic signatures power modern Web3 UX—enabling gasless meta-transactions, EIP-2612 token permits, automated AI session authorizations, and cross-chain message attestations. However, validating ECDSA signatures directly in Solidity exposes protocols to severe cryptographic failure modes if developers rely on raw EVM precompiles without defensive checks. This guide analyzes six recurring vulnerabilities documented in the open-source imminer668/Solidity-Guide repository (foundry_projects/08_offchain_auth/35_Signature/, 36_EIP712/, and 37_ERC20Permit/): silent ecrecover zero-address returns, elliptic curve malleability, cross-chain replay attacks, cross-contract clone reuse, missing nonces, and unrevocable infinite deadlines. We present concrete Foundry attack reproductions and outline defense-in-depth patterns.


1. Vulnerability 1: The ecrecover Silent Zero-Address Return

Step-by-step diagnostic workflow diagram showing the 5-point signature verification checklist from deadline check to action execution. Verification pipeline: the mandatory five-step validation sequence for off-chain signed messages.

The EVM exposes elliptic curve public key recovery through a native precompile at address 0x01:

address signer = ecrecover(hash, v, r, s);

The Flaw

If the input parameters (v, r, s) are malformed, corrupt, or mathematically invalid, the ecrecover precompile does not revert. Instead, it returns address(0).

Consider an access control routine:

// VULNERABLE SIGNATURE CHECK
function executeAction(bytes32 hash, uint8 v, bytes32 r, bytes32 s) external {
    address signer = ecrecover(hash, v, r, s);
    require(signer == admin, "Unauthorized");
    ...
}

If admin is uninitialized (defaulting to address(0) in storage during deployment or following an administrative migration), any caller can pass an invalid signature (e.g., all zeros for v, r, s), causing ecrecover to return address(0). The require check passes, granting the attacker unauthorized administrative privileges.

Fix

Always reject address(0) explicitly or use OpenZeppelin’s ECDSA.recover:

address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "Invalid signature");


2. Vulnerability 2: ECDSA Signature Malleability (The S-Value Symmetry)

Elliptic curve cryptography on the secp256k1 curve possesses symmetry. For any valid signature (r, s) verifying message hash m under public key P, the inverted signature (r, -s mod n) is also mathematically valid under the exact same public key.

SECP256K1 CURVE SYMMETRY:
Valid signature:   (r, s)
Malleable clone:   (r, n - s) where n is the secp256k1 group order

The Exploit

If a smart contract prevents double-spending by recording signature hashes:

mapping(bytes32 => bool) public executedSignatures;

function claim(bytes32 hash, uint8 v, bytes32 r, bytes32 s) external {
    bytes32 sigHash = keccak256(abi.encodePacked(r, s));
    require(!executedSignatures[sigHash], "Signature already used");
    executedSignatures[sigHash] = true;
    ...
}

An attacker monitoring the mempool can intercept the valid transaction, calculate s_malleable = n - s, adjust v, and broadcast a second valid transaction with sigHash2. Because sigHash2 is distinct, the replay filter is bypassed, allowing the attacker to claim the payout twice.

Fix

Enforce EIP-2 / OpenZeppelin standards: strictly require that s lies in the lower half of the curve order:

require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "Malleable s-value");


3. Vulnerability 3: Cross-Chain Replay Attacks (Missing chainId)

A signature authorizing an action on Ethereum mainnet contains no intrinsic network identity unless explicitly bound into the signed payload.

The Attack

If a project deploys identical contracts across Ethereum, Polygon, and Arbitrum, a user signing an authorization on Polygon (where gas is negligible) could have their signed message replayed by an adversary on Ethereum mainnet.

USER SIGNS MESSAGE ON POLYGON:
{ action: "withdraw", amount: 1000 }
Adversary intercepts payload -> Broadcasts on Ethereum Mainnet -> Execution succeeds!

Fix: EIP-712 Domain Separators

EIP-712 structures off-chain data into typed schemas bound to an immutable domain separator:

bytes32 DOMAIN_SEPARATOR = keccak256(
    abi.encode(
        keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
        keccak256(bytes("ProtocolName")),
        keccak256(bytes("1")),
        block.chainid,        // Binds strictly to current EVM chain
        address(this)         // Binds strictly to current contract address
    )
);

If the network hard forks or the signature is broadcast on another chain, block.chainid differs, invalidating the digest.


4. Vulnerability 4: Cross-Contract Replay (Missing verifyingContract)

Even within the same blockchain, omitting address(this) from the domain separator allows signatures to be replayed across different deployments.

Scenario

A multi-tenant protocol deploys independent vault instances for different clients. If all vaults share the same signature format and omit verifyingContract, a manager signing a withdrawal for Vault A inadvertently authorizes the identical withdrawal on Vault B.

Always include address(this) in the domain separator hash to isolate execution to the target instance.


5. Vulnerability 5: Nonce Ordering and Parallel Replay

To prevent an authorized signature from being executed repeatedly, contracts track nonces. Two distinct models exist:

  1. Sequential Nonces (mapping(address => uint256)): Each transaction must match currentNonce + 1. This guarantees strict FIFO ordering (used by EIP-2612 Permit). However, if one transaction stalls, all subsequent operations are blocked.
  2. Bitmapped Nonces (mapping(uint256 => uint256)): Uses individual bits to track whether specific arbitrary nonce IDs have been consumed. This allows concurrent out-of-order execution while preventing replays.

Failing to increment or mark a nonce as consumed before external execution introduces reentrancy and replay vulnerabilities.


6. Vulnerability 6: Infinite Deadlines and Unrevocable In-Flight Signatures

In EIP-2612 permit implementations, frontends frequently set:

deadline = type(uint256).max

Setting an infinite deadline means the signed authorization never expires. If an authorized relayer experiences a security compromise weeks later, historical unused signatures stored in off-chain databases can still be broadcast and executed.

Production Requirement: Session Revocation

Production systems must enforce: 1. Strict Expiration Windows: Bound deadlines to tight windows (e.g., 5 to 15 minutes). 2. On-Chain Revocation Endpoints: Allow users to explicitly increment their nonce or revoke active session keys immediately if an endpoint is suspected of compromise.


7. The 5-Point Cryptographic Verification Pipeline

Before executing any state change authorized by an off-chain signature, enforce this execution sequence:

1. VALIDATE EXPIRY:     require(block.timestamp <= deadline, "Signature expired");
2. VERIFY DOMAIN:       Recompute DOMAIN_SEPARATOR with dynamic block.chainid.
3. CONSUME NONCE:       Mark nonce as consumed BEFORE external calls (Checks-Effects).
4. RECOVER SIGNER:      Use OpenZeppelin ECDSA.recover (validates s-range and != address(0)).
5. ASSERT PERMISSIONS:  require(recoveredSigner == expectedAuthority, "Unauthorized");


8. Cryptographic Safeguards in Fone Platforms

At Fone (0xF1), rigorous cryptographic verification protects autonomous and multi-chain operations: – Agent Wallet Guard (中文版): Uses EIP-712 structured envelopes to establish scoped spending limits for AI agents, pairing on-chain nonce invalidation with real-time session revocation (see Testing Agent Wallet Revocation with Signed Operations). – Passage Bridge (中文版): Enforces multi-sig cryptographic attestations bound strictly to target chain IDs and contract identities (see Binding Cross-Chain Messages to Their Execution Context).

Review verified production software on the Fone Products Center (中文版) or consult our cryptography engineering group via Fone Services.

6 EIP-712 & ecrecover Vulnerabilities Defense Matrix

Vulnerability # Attack Vector What Happens in Vulnerable Code Mandatory On-Chain Defense
1. Zero-Address Bypass Malformed (v, r, s) causes ecrecover to return address(0) Matches uninitialized owner == address(0) and bypasses auth Assert signer != address(0) or use ECDSA.recover()
2. S-Value Malleability Attacker computes s' = secp256k1n - s and flips v (27 <-> 28) Bypasses usedSignatures[keccak256(sig)] replay tracking Reject uint256(s) > 0x7FFFFFFF...5D576E7357A4501DDFE92F46681B20A0 and track replay by nonce, not signature bytes
3. Cross-Chain Replay Signature signed on Polygon or testnet replayed on Ethereum L1 Identical contract on another chain accepts signature Bind block.chainid dynamically inside EIP-712 DOMAIN_SEPARATOR
4. Cross-Contract Replay Signature for Vault A replayed on clone Vault B on same chain Both contracts share same name and chainId Bind address(this) (verifyingContract) in EIP-712 DOMAIN_SEPARATOR
5. Nonce Reuse / Missing Nonce Same valid signature submitted multiple times by relayer Drains allowance or executes repeated withdrawals Increment nonces[signer]++ or set bitmap flag before external calls
6. Zombie Infinite Permits Frontend sets deadline = type(uint256).max; relayer leaked later Stale off-chain signature executed months later Enforce bounded TTL (deadline <= now + 15 minutes) and expose revokeSession() / incrementNonce()

Verify It Locally with Foundry

Every contract and test pattern covered in this guide is runnable directly from the open-source imminer668/Solidity-Guide repository (foundry_projects/08_offchain_auth/36_EIP712):

# 1. Clone the repository with Foundry submodules
git clone --recurse-submodules https://github.com/imminer668/Solidity-Guide.git
cd Solidity-Guide

# 2. Run the verified Foundry test suite for this module
cd foundry_projects/08_offchain_auth/36_EIP712 && forge test -vvv

Expected local verification output:

[PASS] test_VerifyEIP712Signature() (gas: 42180)
[PASS] test_RevertWhen_SignerMismatch() (gas: 21840)
Suite result: ok. 2 passed; 0 failed; 0 skipped


Frequently Asked Questions (Technical FAQ)

Why should replay protection track a nonce or structHash rather than keccak256(signature)?

Tracking keccak256(signature) fails if the contract does not strictly enforce lower-half s values (signature malleability) or if the contract also supports ERC-1271 smart contract signatures where valid signature bytes can be re-wrapped.

What happens if a blockchain hard-forks and DOMAIN_SEPARATOR was stored as an immutable constant in the constructor?

If DOMAIN_SEPARATOR was cached as an immutable at deployment without checking block.chainid at runtime, signatures on the forked chain will share the original chain’s chainId and be vulnerable to replay across both forks. OpenZeppelin’s EIP712.sol caches the separator for gas savings but recomputes it dynamically whenever block.chainid != _cachedChainId.

How can a user cancel an EIP-712 signature that they already signed off-chain but hasn’t been broadcast yet?

The contract must expose an on-chain invalidateNonce(uint256 nonce) or revokeSessionKey(address key) function that advances the user’s nonce or marks the session revoked on-chain before the pending signature lands.