Skip to content
Smart contracts Audit finding Beginner

_onTransferReceived() does not work as intended

The contract's transfer callback check uses an inverted comparison, so it reverts when a compliant receiver returns the expected selector and accepts when the selector is wrong. This prevents safe transfers to contracts that correctly implement the ERC-721 receiver interface.

adeolu Follow with Tigerfrake, 0xAleko and 21 others

Originally disclosed on Code4rena

Submitted by adeolu, also found by debo (1, 2), Tigerfrake, 0xAleko, 0xastronatey, zhaojohnson, nslavchev, ZanyBonzy, Rhaydden, Nikki, ABAIKUNANBAEV, Agontuk, OMEN, Testerbot, mashbust, swapnaliss, Sparrow, NexusAudits, SBSecurity, Bauchibred, Decap, wasm_it, oakcobalt, SpicyMeatball, and dreamcoder

_onTransferReceived does not work as intended or described in the function natspec.

  • It will not revert when the recipient does not implement onERC721Received() function correctly (does not return onERC721Received().selector).
  • It will revert when the recipient implements onERC721Received() function correctly and as described/specified by the EIP 712 (returns onERC721Received().selector).
  • This will prevent transfers to contracts that have correctly implemented the ERC721TokenReceiver interface to accept safe token transfers via safeTransferFrom().

Proof of Concept

_onTransferReceived() has a require statement that will pass when the recipient does not return the IERC721TokenReceiver.onERC721Received() selector. EIP 721 defines that if a recipient is a contract, it should implement the IERC721TokenReceiver.onERC721Received() function and that function must return the IERC721TokenReceiver.onERC721Received() selector for it to be recognized as a valid erc721 token receiver.

Snippet of the faulty require statement below:

https://github.com/code-423n4/2024-08-superposition/blob/4528c9d2dbe1550d2660dac903a8246076044905/pkg/sol/OwnershipNFTs.sol#L82-L95

        bytes4 data = IERC721TokenReceiver(_to).onERC721Received(
            _sender,
            _from,
            _tokenId,

            // this is empty byte data that can be optionally passed to
            // the contract we're confirming is able to receive NFTs
            ""
        );

        require(
            data != IERC721TokenReceiver.onERC721Received.selector,
            "bad nft transfer received data"
        );

We can see that the require statement expects the data returned from the erc721 token receiver to not be equal to IERC721TokenReceiver.onERC721Received.selector. This means that if the recipient implements the onERC721Received function correctly and returns IERC721TokenReceiver.onERC721Received.selector, the require statement in function _onTransferReceived() will revert the whole transfer.

Coded POC

Create foundry test repo and run the file below in test folder:

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

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

/// @dev Note: the ERC-165 identifier for this interface is 0x150b7a02.
interface IERC721TokenReceiver {
    /// @notice Handle the receipt of an NFT
    /// @dev The ERC721 smart contract calls this function on the recipient
    ///  after a `transfer`. This function MAY throw to revert and reject the
    ///  transfer. Return of other than the magic value MUST result in the
    ///  transaction being reverted.
    ///  Note: the contract address is always the message sender.
    /// @param _operator The address which called `safeTransferFrom` function
    /// @param _from The address which previously owned the token
    /// @param _tokenId The NFT identifier which is being transferred
    /// @param _data Additional data with no specified format
    /// @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
    ///  unless throwing
    function onERC721Received(
        address _operator,
        address _from,
        uint256 _tokenId,
        bytes memory _data
    ) external returns (bytes4);
}

/*
 * OwnershipNFTs is a simple interface for tracking ownership of
 * positions in the Seawater Stylus contract.
 */
contract OwnershipNFTs {
    /**
     * @notice _onTransferReceived by calling the callback `onERC721Received`
     *         in the recipient if they have codesize > 0. if the callback
     *         doesn't return the selector, revert!
     * @param _sender that did the transfer
     * @param _from owner of the NFT that the sender is transferring
     * @param _to recipient of the NFT that we're calling the function on
     * @param _tokenId that we're transferring from our internal storage
     */
    //  _onTransferReceived() is exact same function that is in the codebase, with no changes to logic whatsoever
    function _onTransferReceived(
        address _sender,
        address _from,
        address _to,
        uint256 _tokenId
    ) internal {
        // only call the callback if the receiver is a contract
        if (_to.code.length == 0) return;

        bytes4 data = IERC721TokenReceiver(_to).onERC721Received(
            _sender,
            _from,
            _tokenId,
            // this is empty byte data that can be optionally passed to
            // the contract we're confirming is able to receive NFTs
            ""
        );

        require(
            data != IERC721TokenReceiver.onERC721Received.selector,
            "bad nft transfer received data"
        );
    }

    // mock wrapper function that calls the internal _onTransferReceived()
    function safeTransferFrom(
        address _from,
        address _to,
        uint256 _tokenId
    ) external {
        _onTransferReceived(msg.sender, _from, _to, _tokenId);
    }
}

contract MockCompliantReceiver is IERC721TokenReceiver {
    function onERC721Received(
        address _operator,
        address _from,
        uint256 _tokenId,
        bytes memory _data
    ) external returns (bytes4) {
        return IERC721TokenReceiver.onERC721Received.selector;
    }
}

contract receiverTest is Test {
    MockCompliantReceiver compliant_receiver;
    OwnershipNFTs ownershipNft;

    function setUp() public {
        //deploy MockCompliantReceiver
        compliant_receiver = new MockCompliantReceiver();

        //deploy ownershipNft contract
        ownershipNft = new OwnershipNFTs();
    }

    function test_revertForCompliantReceiver() public {
        /* we expect the call to revert because of the faulty require statement */
        /** this shows that the _onTransferReceived will always reject transfers to a contract that is
         IERC721TokenReceiver compliant.  */

        vm.expectRevert(bytes("bad nft transfer received data"));
        ownershipNft.safeTransferFrom(
            msg.sender,
            payable(address(compliant_receiver)), //param `to` is set to be the compliant receiver here
            1
        );
    }
}

Recommended Mitigation Steps

Change the != in the require statement to ==:

        require(
            data == IERC721TokenReceiver.onERC721Received.selector,
            "bad nft transfer received data"
        );

Assessed type

Context

af-afk (Superposition) confirmed and commented via duplicate issue #55:

We don’t believe this is a high risk submission since assets cannot be stolen. Maybe transfers to up to spec contracts could not be used, but that’s just frustrating for users.

0xsomeone (judge) decreased severity to Medium and commented:

The submission details how the EIP-721 safe transfers will fail to validate the return data properly, causing EIP-721 callback integrations to fail for the token.

I believe a medium-risk severity rating is better suited for this submission given that assets are not at risk and functionality becomes inaccessible that should normally be circumventable.


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

Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.

How it worked

Root cause

The require statement uses '!=' instead of '==' when comparing the returned selector to the expected ERC-721 receiver selector.

Impact

Safe transfers to contracts that correctly implement the ERC-721 receiver interface will fail, making the token incompatible with such integrations; assets are not at risk.

What the attacker needed

Recipient is a contract implementing onERC721Received; recipient returns the correct selector

The fix

The comparison should be changed from '!=' to '==' so that the transfer only proceeds when the receiver returns the expected selector.

How it was found

  1. Deploy a receiver contract that correctly implements onERC721Received and returns the expected selector.
  2. Call safeTransferFrom to send an NFT to that compliant receiver.
  3. Observe that the transaction reverts with the 'bad nft transfer received data' error.

Explained by bugbounty.wiki with AI from the original and checked against quotes from it; it can still be wrong. Read the original before relying on a detail.

Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.

When an NFT is sent to a contract, the sending contract asks the receiving contract to confirm it can handle NFTs by calling a special function. The receiving contract is supposed to reply with a specific code word. This code checks for the wrong answer: it rejects the correct code word and accepts anything else, so well-behaved receiving contracts cannot accept the NFT.

What is Smart contracts?

Flaws in on-chain code that let an attacker drain funds, freeze them or break the protocol's accounting.

More by adeolu

View all

16 more disclosed reports, best first.

More from Superposition

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Smart contract vulnerabilities

The lesson behind this report.

Flaws in on-chain code that let an attacker drain funds, freeze them or break the protocol's accounting.