Skip to content
Smart contracts Audit finding Intermediate

Unsafe downcasting operation truncate user’s input

The smart contract code unsafely downcasts user-supplied amounts and prices from larger integer types to smaller ones, which truncates the values. An attacker could pay a large amount but have their balance recorded as a much smaller truncated value, leading to loss of funds when they cannot get a refund for the full amount.

ladboy233 Follow with seyni, slvDev and 9 others

Originally disclosed on Code4rena

Submitted by ladboy233, also found by seyni, slvDev, minhquanym, gzeon, karanctf, Matin, 0x1f8b, yixxas, UniversalCrypto, obront, and rvierdiiev

https://github.com/code-423n4/2022-12-escher/blob/5d8be6aa0e8634fdb2f328b99076b0d05fefab73/src/minters/LPDA.sol#L71

https://github.com/code-423n4/2022-12-escher/blob/5d8be6aa0e8634fdb2f328b99076b0d05fefab73/src/minters/LPDA.sol#L82

https://github.com/code-423n4/2022-12-escher/blob/5d8be6aa0e8634fdb2f328b99076b0d05fefab73/src/minters/LPDA.sol#L101

https://github.com/code-423n4/2022-12-escher/blob/5d8be6aa0e8634fdb2f328b99076b0d05fefab73/src/minters/FixedPrice.sol#L62

Impact

Unsafe downcasting operation truncates user’s input.

Proof of Concept

There are a few unsafe downcasting operation that truncates user’s input. The impact can be severe or minimal.

In FixedPrice.sol,

/// @notice buy from a fixed price sale after the sale starts
/// @param _amount the amount of editions to buy
function buy(uint256 _amount) external payable {
	Sale memory sale_ = sale;
	IEscher721 nft = IEscher721(sale_.edition);
	require(block.timestamp >= sale_.startTime, "TOO SOON");
	require(_amount * sale_.price == msg.value, "WRONG PRICE");
	uint48 newId = uint48(_amount) + sale_.currentId;
	require(newId <= sale_.finalId, "TOO MANY");

	for (uint48 x = sale_.currentId + 1; x <= newId; x++) {
		nft.mint(msg.sender, x);
	}

	sale.currentId = newId;

	emit Buy(msg.sender, _amount, msg.value, sale);

	if (newId == sale_.finalId) _end(sale);
}

The amount is unsafely downcasted from uint256 to uint48, note the code:

require(_amount * sale_.price == msg.value, "WRONG PRICE");
uint48 newId = uint48(_amount) + sale_.currentId;

The upper limit for uint48 is 281474976710655,

If user wants to buy more than 281474976710655 amount of NFT and pay the 281474976710655 * sale price amount, the user can only receive 281474976710655 amount of NFT because of the downcasting.

In LPDA.sol, we are unsafely downcasting the price in the buy function:

receipts[msg.sender].amount += amount;
receipts[msg.sender].balance += uint80(msg.value);

for (uint256 x = temp.currentId + 1; x <= newId; x++) {
	nft.mint(msg.sender, x);
}

sale.currentId = newId;

emit Buy(msg.sender, amount, msg.value, temp);

if (newId == temp.finalId) {
	sale.finalPrice = uint80(price);
	uint256 totalSale = price * amountSold;
	uint256 fee = totalSale / 20;
	ISaleFactory(factory).feeReceiver().transfer(fee);
	temp.saleReceiver.transfer(totalSale - fee);
	_end();
}

Note the line:

uint80(msg.value) and uint80(price)

In LPDA.sol, same issue exists in the refund function:

/// @notice allow a buyer to get a refund on the current price difference
function refund() public {
	Receipt memory r = receipts[msg.sender];
	uint80 price = uint80(getPrice()) * r.amount;
	uint80 owed = r.balance - price;
	require(owed > 0, "NOTHING TO REFUND");
	receipts[msg.sender].balance = price;
	payable(msg.sender).transfer(owed);
}

Note the downcasting: uint80(getPrice())

This means if the price goes above uint80, it will be wrongly truncated to uint80 for price.

The Downcasting in LPDA.sol is damaging because it truncated user’s fund.

Below is the POC:

Add test in LPDA.t.sol

https://github.com/code-423n4/2022-12-escher/blob/5d8be6aa0e8634fdb2f328b99076b0d05fefab73/test/LPDA.t.sol#L167

    function test_LPDA_downcasting_POC() public {

        // make the lpda sales contract
        sale = LPDA(lpdaSales.createLPDASale(lpdaSale));
        // authorize the lpda sale to mint tokens
        edition.grantRole(edition.MINTER_ROLE(), address(sale));
        //lets buy an NFT

        uint256 val = uint256(type(uint80).max) + 10 ether;
        console.log('msg.value');
        console.log(val);
        sale.buy{value: val}(1);

    }

And import “forge-std/console.sol” in LPDA.sol:

https://github.com/code-423n4/2022-12-escher/blob/5d8be6aa0e8634fdb2f328b99076b0d05fefab73/src/minters/LPDA.sol#L3

import "forge-std/console.sol";

And add console.log in LPDA.sol buy function.

https://github.com/code-423n4/2022-12-escher/blob/5d8be6aa0e8634fdb2f328b99076b0d05fefab73/src/minters/LPDA.sol#L69

receipts[msg.sender].amount += amount;
receipts[msg.sender].balance += uint80(msg.value);

console.log("truncated value");
console.log(receipts[msg.sender].balance);

We run our test:

forge test -vv --match test_LPDA_downcasting_POC

The output is:

Running 1 test for test/LPDA.t.sol:LPDATest
[PASS] test_LPDA_downcasting_POC() (gas: 385619)
Logs:
  msg.value
  1208935819614629174706175
  truncated value
  9999999999999999999

Test result: ok. 1 passed; 0 failed; finished in 3.61ms

As we can see, user uses 1208935819614629174706175 to buy in LPDA.sol but the balance is truncated to 9999999999999999999, later user is not able to get the refund they are entitled to because the msg.value is unsafely downcasted.

Also note the downcasting for getPrice in LPDA.sol is also a issue:

The getPrice in LPDA.sol returns a uint256

/// @notice the price of the sale
function getPrice() public view returns (uint256) {
	Sale memory temp = sale;
	(uint256 start, uint256 end) = (temp.startTime, temp.endTime);
	if (block.timestamp < start) return type(uint256).max;
	if (temp.currentId == temp.finalId) return temp.finalPrice;

	uint256 timeElapsed = end > block.timestamp ? block.timestamp - start : end - start;
	return temp.startPrice - (temp.dropPerSecond * timeElapsed);
}

But this is downcasted into uint80 in function buy and refund.

uint80 price = uint80(getPrice()) * r.amount;

Recommended Mitigation Steps

We recommend the project handle downcasting and use safe casting library to make sure the downcast does not provide an unexpected truncate value.

https://docs.openzeppelin.com/contracts/3.x/api/utils#SafeCast

stevennevins (Escher) confirmed, but disagreed with severity and commented:

Scenarios seem pretty unlikely but we should just handle these truncations better.

berndartmueller (judge) commented:

While very unlikely, it could result in a loss of funds for the user. Therefore, I consider Medium severity to be appropriate.


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.

How it worked

Root cause

Likely the contract uses unsafe downcasting from uint256 to uint48 or uint80 without checking that the value fits, causing truncation of user input.

Impact

A user could lose funds because their payment is truncated and they cannot get a full refund; the judge rated it Medium severity as it is very unlikely but could result in loss of funds.

What the attacker needed

A sale contract deployed; user has enough funds to exceed uint80 max

The fix

The project should handle downcasting and use a safe casting library to ensure the downcast does not produce an unexpected truncated value.

How it was found

  1. Create an LPDA sale and grant the sale contract the minter role.
  2. Call the buy function with a value that exceeds the maximum uint80 plus some ether.
  3. Observe that the recorded balance is truncated to a much smaller number.

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.

In smart contracts, numbers have fixed sizes. If you try to store a very large number in a smaller slot, the extra digits are cut off, like pouring a gallon of water into a pint glass. This report shows that the contract does this with user payments, so a user might pay a huge amount but the contract only records a tiny fraction of it, meaning they lose money.

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 ladboy233

View all

47 more disclosed reports, best first.

More from Escher contest

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.