Code size check vulnerability
Last updated
Last updated
You can determine if an address is a Solidity smart contract by checking the size of the code stored at the address. Assembly extcodesize is used in Solidity functions to determine the size of the code at a particular address. If the code size at the address is greater than 0 then the address is a smart contract.
This opcode returns the size of the code on an address. If the size is larger than zero, the address is a contract.
But if EXTCODESIZE is called from the constructor it returns 0.
And that's where a problem occurs.
To pwn a contract that contains Assembly extcodesize simple put a function in the attacking contract’s constructor. During contract creation when the constructor is executed there is no code yet so the code size will be 0. The constructor will run the function and bypass the target contract’s extcodesize check.
Let's look at the following image:
So after we now know how the attacker is creating a contract with code size returned by extcodesize equal to 0, let's look at the code of the attacker:
The Attack contract will call the target contract in the constructor. When the contract is created the target address will detect 0 code and the transaction will be successful. It puts the results in the bool isContract in the attack contract.