The call to MsgValueSimulator with non zero msg.value will call to sender itself which will bypass the onlySelf check
A call to the MsgValueSimulator system contract with a non-zero msg.value causes the simulator to re-enter itself with corrupted register values, making the original sender call itself with attacker-influenced calldata and value. This bypasses msg.sender-based checks such as onlySelf and can break accounting logic in contracts that assume they cannot call themselves.
First, I need to clarify, there may be more serious ways to exploit this issue. Due to the lack of time and documents, I cannot complete further exploit. The current exploit has only achieved the impact in the title. I will expand the possibility of further exploit in the poc chapter.
The call to MsgValueSimulator with non zero msg.value will call to sender itself with the msg.data. It means that if you can make a contract or a custom account call to specified address with non zero msg.value (that’s very common in withdrawal functions and smart contract wallets), you can make the contract/account call itself. And if you can also control the calldata, you can make the contract/account call its functions by itself.
It will bypass some security check with the msg.sender, or break the accounting logic of some contracts which use the msg.sender as account name.
For example the onlySelf modifier in the ContractDepolyer contract:
modifier onlySelf() {
require(msg.sender == address(this), "Callable only by self");
_;
}
Proof of Concept
The MsgValueSimulator use the mimicCall to forward the original call.
return EfficientCall.mimicCall(gasleft(), to, _data, msg.sender, false, isSystemCall);
And if the to address is the MsgValueSimulator address, it will go back to the MsgValueSimulator.fallback function again.
The fallback function will Extract the value to send, isSystemCall flag and the to address from the extraAbi params(r3,r4,r5) in the _getAbiParams function. But it’s different from the first call to the MsgValueSimulator. The account uses EfficientCall.rawCall function to call the MsgValueSimulator.fallback in the first call. For example, code in DefaultAccount._execute:
bool success = EfficientCall.rawCall(gas, to, value, data);
The rawCall will simulate system_call_byref opcode to call the MsgValueSimulator. And the system_call_byref will write the r3-r5 registers which are read as the above extraAbi params.
But the second call is sent by EfficientCall.mimicCall, as the return value explained in the document https://github.com/code-423n4/2023-03-zksync/blob/main/docs/VM-specific_v1.3.0_opcodes_simulation.pdf, mimicCall will mess up the registers and will use r1-r4 for standard ABI convention and r5 for the extra whotomimic arg. So extraAbi params(r3-r5) read by _getAbiParams will be messy data. It can lead to very serious consequences, because the r3 will be used as the msg.value, and the r4 will be used as the to address in the final mimicCall. It means that the contract will send a different(greater) value to a different address, which is unexpected in the original call.
I really don’t know how to write a complex test to verify register changes in the era-compiler-tester. So to find out how to control the registers, I use the repo https://github.com/matter-labs/zksync-era and replace the etc/system-contracts/ codes with the lastest version in the audit, and write an integration test.
import { TestMaster } from '../src/index';
import * as zksync from 'zksync-web3';
import { BigNumber } from 'ethers';
describe('ETH token checks', () => {
let testMaster: TestMaster;
let alice: zksync.Wallet;
let bob: zksync.Wallet;
beforeAll(() => {
testMaster = TestMaster.getInstance(__filename);
alice = testMaster.mainAccount();
bob = testMaster.newEmptyAccount();
});
test('Can perform a transfer (legacy)', async () => {
const LEGACY_TX_TYPE = 0;
const value = BigNumber.from(30000);
const MSG_VALUE_SYSTEM_CONTRACT = "0x0000000000000000000000000000000000008009";
console.log(await alice.getBalance());
console.log(await alice.provider.getBalance(MSG_VALUE_SYSTEM_CONTRACT));
let block = await alice.provider.getBlock("latest");
console.log("block gas limit", block.gasLimit);
let tx_gasLimit = block.gasLimit.div(8);
console.log("tx_gasLimit", tx_gasLimit);
console.log("gas price", await alice.getGasPrice());
try {
let tx = await alice.sendTransaction({ type: LEGACY_TX_TYPE, to: MSG_VALUE_SYSTEM_CONTRACT, value , gasLimit: tx_gasLimit, data: '0x'});
let txp = await tx.wait();
console.log("success");
console.log(txp["logs"]);
} catch (err ) {
console.log("fail");
console.log(err);
console.log('--------');
console.log(err["receipt"]["logs"]);
}
console.log(await alice.getBalance());
console.log(await alice.provider.getBalance(MSG_VALUE_SYSTEM_CONTRACT));
console.log(await alice.getNonce());
});
afterAll(async () => {
await testMaster.deinitialize();
});
});
There are two l2 eth token transaction in addition to gas processing. And the value sent to the MsgValueSimulator will stuck in the contract forever.
I found that the r4(to) is always msg.sender, the r5(mask) is always 0x1, and if the length of the calldata is 0, the r3(value) will be 0x2129c0000000a00000000, and if the length > 0, r3(value) will be 0x215800000000a00000000 + calldata.length << 96. So in this case, the balance of the sender should be at least 0x2129c0000000a00000000 wei to finish the whole transaction whitout reverting.
I did not find any document about the standard ABI convention mentioned in the VM-specificv1.3.0*opcodessimulation.pdf and the r5 is also not really the extra who*to_mimic arg. I didn’t make a more serious exploit due to lack of time. I’d like more documentation about register call conventions to verify the possibility of manipulating registers.
Recommended Mitigation Steps
Check the to address in the MsgValueSimulator contract. The to address must not be the MsgValueSimulator address.
Note: extensive discussion took place regarding this issue. Final comments are included below. For full details, please see the original submission.
Depending on the use case, a user could manipulate the msg.value of the reentrant call. However if length > 0, the rawFatPointer = msg.value >= 2^96. So if an attacker manipulates length, the result msg.value will be very large, so the attack is realistically impossible. Just as note, 2^96 wei == 79228162514 Ether == $100 trillion.
So the length of the data should be 0, but manipulating other data is still possible.
I see the impact of a non-unauthorized call to itself fallback function. It is indeed pretty bad, even though I don’t know any smart contract that would suffer from this in practice.
All in all, I confirm the issue and appreciate that deep research, thanks a lot @ronnyx2017!
For a note here is the test that we add to our compiler-tester to reproduce the issue.
pragma solidity ^0.8.0;
// The same copy of the system contracts that was on the scope.
import "./system-contracts/libraries/EfficientCall.sol";
contract Main {
/// @dev The address of msgValueSimulator system contract.
address constant MSG_VALUE_SIMULATOR_ADDRESS = address(0x8009);
/// @dev Number of times that fallback function was called.
uint256 fallbackEntrantCounter;
function test() external payable {
// Reset counter, after the call to msgValueSimulator it should be increased
fallbackEntrantCounter = 0;
require(msg.value >= 2, "msg.value should be at least 2 to ");
// The same pattern as on `DefaultAccount`
bool success = EfficientCall.rawCall(gasleft(), MSG_VALUE_SIMULATOR_ADDRESS, msg.value / 2, msg.data[0:0]);
if (!success) {
EfficientCall.propagateRevert();
}
require(fallbackEntrantCounter == 1, "Fallback function wasn't called");
}
fallback() external payable {
fallbackEntrantCounter++;
}
}
Last but not least, even though the impact of the issue wasn’t clear to us after triaging the report, the fix was done immediately after the end of the audit, before the launch. So this (and others) issues are not in production.
Thank you @vladbochok for the extra detail and am glad this was already addressed.
I do believe self-calling opens up to a category of exploits, especially for contracts that for example use try/catch or have “unusual” behaviour around transfers.
I believe we can agree that the finding is unique and at least of medium severity -> Incorrect behaviour, which can conditionally lose funds.
We must agree that the operation also can be viewed as account hijacking, in the sense that we can impersonate the receiving contract and then have it call itself.
These lead me to believe that a higher severity should be appropriate.
Have asked for advice to other judges with the goal of clarifying if there was sufficient information in the original submission, I believe the initial POC was valid but I want to get their perspective.
While plenty of discussion has happened, the original finding has shown a valid POC that shows the following impact:
By performing a call with value, we can forge a call that will cause the target contract to call itself
The discussion after that helped demonstrate the report’s validity and the Sponsor has already mitigated the potential risk.
The ability for a specific contract to call self can be met with some skepticism in terms of its impact, however, I believe that in different scenarios, the severity would easily be raised to High.
For example:
Bridge contracts that call to self
Contract that calls to self to use try/catch
Vault Contracts, can be tricked into minting empty shares (no-op transfers), if the caller and the payer are the same (quirkiness of DAI)
If those contracts were in-scope and the setup demonstrated in the finding was not patched, the finding would have easily been rated as High Severity.
In this case, those contracts are not in-scope, so I would maintain a Medium Severity, because that’s reliant on the specific integrators using that pattern.
In contrast to isSystem which breaks an invariant on fully in-scope contracts, without the ability of causing damage, I have reason to believe that this specific vulnerability could have caused higher degrees of damage, for example:
Contracts that allow to call or delegate call
Vault Contracts as shown above
Contracts where there is no expectation that the contract can call itself (as it may mess up the balance, accounting, etc..)
Given the following considerations, I have asked myself whether this is a type of risk that would in any way be imputable to the integrator as a quirk, and at this time I cannot justify that.
For the logic above, because the finding has shown a way to break a very strong expectation that a contract cannot call itself unless programmed for it, considering this as msg.sender spoofing, although limited to self calls, considering the potential risks for integrators, and the breaking of expectations for EVM systems, I am raising the finding to High Severity because I believe this would have not been a risk that the Sponsor would have wanted any user nor developer to take.
The Sponsor has already mitigated the finding at the time of writing
The original report as published on Code4rena, by ronnyx2017. 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 30 seconds. 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 MsgValueSimulator does not reject calls where the recipient is its own address, so it re-enters itself and reads corrupted register values as the value and recipient for a second call.
Impact
A contract can be made to call itself, bypassing msg.sender checks like onlySelf and potentially breaking accounting; however, if calldata length is greater than zero the required value becomes astronomically large, making the attack realistically impossible in that case.
What the attacker needed
Ability to send a transaction with value to the simulator; empty calldata for realistic value; sender balance at least the corrupted value
The fix
The MsgValueSimulator should reject any call where the recipient address is its own address; the text states the fix was done before launch.
How it was found
Send a transaction to the MsgValueSimulator address with a non-zero value and empty calldata.
The MsgValueSimulator forwards the call using mimicCall, which re-enters the simulator itself.
The simulator reads corrupted extraAbi parameters, using a large value and the original sender as the recipient.
The original sender is made to call itself with the same calldata and the corrupted value.
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 30 seconds. 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
In this blockchain system, a special helper contract is meant to forward calls that carry a payment (value). If you send a payment directly to that helper, it gets confused and ends up making the original sender call itself instead of the intended recipient. That means a contract can be tricked into running its own functions, which it normally would never do, potentially bypassing safety checks that rely on who is calling.
What is Business logic?
The application works as coded but not as intended: a negative price, a skipped payment step, a limit that can be crossed.