NFTBridge
60,000 USDC
View results
Submission Details
Severity: medium
Invalid

Unsafe Downcasting in ASCII Conversion Leading to Data Truncation

Summary

The uint256AsciiNbcharsToString function in the Cairo compatibility library performs unsafe downcasting from uint256 to uint8 without proper validation. This can lead to data truncation and unintended behavior, potentially causing incorrect string conversions.

Vulnerability Details

  1. Location: uint256AsciiNbcharsToString function, line 452.

  2. Code Snippet:

    byteString[i] = bytes1(uint8(asciiValue));

  3. The function extracts ASCII values from a uint256 and downcasts them to uint8. If asciiValue exceeds the range of uint8 (0-255), it will be truncated, leading to data loss.

  4. Detail test:

    function testUnsafeDowncasting() public pure returns (string memory) {
    uint256 value = 0x1234567890ABCDEF1234567890ABCDEF1234567890ABCDEF1234567890ABCDEF;
    uint8 length = 31;
    return Cairo.uint256AsciiNbcharsToString(value, length);
    }
    // Expected: Truncated and incorrect string due to unsafe downcasting.

Impact

  • Characters in the resulting string may be incorrect if the asciiValue exceeds 255, leading to loss of significant bits.

  • The function may produce strings with unintended characters, potentially affecting the integrity of data and causing unexpected behavior in applications relying on this conversion.

Tools Used

Manual review

Recommendations

Implement OpenZeppelin's SafeCast library to ensure safe downcasting.

+ import "@openzeppelin/contracts/utils/math/SafeCast.sol";
function uint256AsciiNbcharsToString(
uint256 value,
uint8 length
)
internal
pure
returns (string memory)
{
string memory s = new string(length);
bytes memory byteString = bytes(s);
// cairo string is 31 bytes with first character as higher bit
for (uint256 i = 0; i < length; ++i) {
uint256 asciiValue = (value >> (8 * (length - 1 - i))) & 0xFF;
_ byteString[i] = bytes1(uint8(asciiValue));
+ byteString[i] = bytes1(SafeCast.toUint8(asciiValue));
}
return s;
}
Updates

Lead Judging Commences

n0kto Lead Judge 11 months ago
Submission Judgement Published
Invalidated
Reason: Incorrect statement

Support

FAQs

Can't find an answer? Chat with us on Discord, Twitter or Linkedin.