Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: use nonReentrant only on functions interacting with arbitrary contracts #395

Merged
merged 6 commits into from
Oct 23, 2024

Conversation

skosito
Copy link
Contributor

@skosito skosito commented Oct 16, 2024

Use case:

Call from zetachain to evm chain reaches gatewayEVM.execute function which is calling arbitrary function on provided contract. That arbitrary function can call back gateway, eg: gatewayEVM.call gatewayEVM.depositAndCall. Because both execute and call/depositAndCall have nonReentrant modifier, this is not possible currently.

Solution can be to remove nonReentrant from either of those - it is better to remove from entrypoint functions since they do not interact with arbitrary contract, just interact with system contracts or addresses (eg. tss, custody, zrc20), and just emit events. On the other side, execute functions interact with arbitrary contracts so leaving it there makes more sense.

Summary by CodeRabbit

  • New Features

    • Enhanced security with the addition of reentrancy protection to critical functions in both GatewayEVM and GatewayZEVM contracts.
    • Introduced checks for maximum payload size in deposit functions for GatewayEVM.
  • Bug Fixes

    • Temporarily disabled ZETA withdrawals in GatewayZEVM with appropriate comments and revert statements.

These updates improve overall contract security and ensure safer handling of transactions.

Copy link
Contributor

coderabbitai bot commented Oct 16, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

The changes in the GatewayEVM and GatewayZEVM contracts focus on enhancing security through the introduction of the nonReentrant modifier to various functions, protecting against reentrancy attacks. In GatewayEVM, this modifier has been added to functions such as executeRevert, execute, and several deposit functions, alongside maximum payload size checks for deposits. In GatewayZEVM, the nonReentrant modifier is similarly applied to functions like withdraw, call, and depositAndCall, with some functions also incorporating a whenNotPaused modifier for state management during withdrawals.

Changes

File Path Change Summary
v2/contracts/evm/GatewayEVM.sol - Added nonReentrant modifier to executeRevert, execute, executeWithERC20, revertWithERC20, deposit, depositAndCall, and call functions.
- Added maximum payload size checks in deposit functions.
v2/contracts/zevm/GatewayZEVM.sol - Introduced nonReentrant modifier to withdraw, withdrawAndCall, call, executeRevert, depositAndRevert, and the new depositAndCall function.
- Added whenNotPaused modifier to several functions for state management.

Possibly related PRs

  • feat: improve revert handling #361: The changes in this PR involve the addition of the nonReentrant modifier to several functions in the GatewayEVM contract, which is directly related to the main PR's focus on enhancing security through similar modifications.
  • feat: limit msg and payload size #376: This PR introduces checks for payload sizes in the GatewayEVM contract, which aligns with the main PR's updates to deposit functions that also enforce maximum payload size checks.
  • feat: add DepositedAndCalled and WithdrawnAndCalled events #403: The modifications in this PR to rename emitted events in the GatewayEVM contract for deposit and call functions are related to the main PR's changes that also involve updates to these functions and their event emissions.

Suggested reviewers

  • fadeev
  • CharlieMc0
  • andresaiello
  • brewmaster012
  • fbac

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@codecov-commenter
Copy link

codecov-commenter commented Oct 16, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 84.23%. Comparing base (d40d2e2) to head (36c6a2e).
Report is 1 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main     #395   +/-   ##
=======================================
  Coverage   84.23%   84.23%           
=======================================
  Files           8        8           
  Lines         387      387           
  Branches      122      122           
=======================================
  Hits          326      326           
  Misses         61       61           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@skosito skosito changed the title fix: remove nonReentrant from execute fix: use nonReentrant only on functions interacting with arbitrary contracts Oct 21, 2024
@skosito skosito requested a review from andresaiello October 21, 2024 08:59
Copy link
Member

@lumtis lumtis left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

in this PR for illustration its removed from execute and executeWithERC20 since same applies for this one as well.

You mean this is the opposite here? It is removed from the entrypoint functions, not the endpoint?

@skosito
Copy link
Contributor Author

skosito commented Oct 21, 2024

in this PR for illustration its removed from execute and executeWithERC20 since same applies for this one as well.

You mean this is the opposite here? It is removed from the entrypoint functions, not the endpoint?

yes this was initial PR description, will update

@skosito skosito requested a review from lumtis October 21, 2024 15:12
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 4df01e3 and 39e72fe.

📒 Files selected for processing (2)
  • v2/contracts/evm/GatewayEVM.sol (4 hunks)
  • v2/contracts/zevm/GatewayZEVM.sol (5 hunks)
🧰 Additional context used
🔇 Additional comments (8)
v2/contracts/evm/GatewayEVM.sol (3)

138-138: Keep nonReentrant modifier for arbitrary contract interactions

The execute function can make arbitrary external calls when messageContext.sender is address(0). The nonReentrant modifier is correctly applied here to protect against potential reentrancy attacks.


175-175: Keep nonReentrant modifier for arbitrary contract interactions

The executeWithERC20 function can make arbitrary external calls when messageContext.sender is address(0). The nonReentrant modifier is correctly applied here to protect against potential reentrancy attacks.


Line range hint 1-500: Verify PR objective implementation

The current implementation appears to be the opposite of what's described in the PR objectives. The PR aims to "remove the nonReentrant modifier from the entrypoint functions" but the code shows it being added to various functions.

Let's verify the previous state of these modifiers:

v2/contracts/zevm/GatewayZEVM.sol (5)

Line range hint 341-345: Appropriate use of nonReentrant modifier on execute function

Adding the nonReentrant modifier to the execute function enhances security by preventing reentrancy attacks when interacting with external contracts through UniversalContract(target).onCall(). This is appropriate since execute can be called with arbitrary target addresses.


Line range hint 364-369: Prudent addition of nonReentrant to depositAndCall function

Including the nonReentrant modifier on the depositAndCall function is a good security measure. This function handles deposits and invokes external contracts, which could be targets for reentrancy exploits.


Line range hint 388-393: Validation of nonReentrant on depositAndCall with ZETA

Adding the nonReentrant modifier to the depositAndCall function that handles ZETA is appropriate. Since this function transfers ZETA and calls UniversalContract(target).onCall(), it is susceptible to reentrancy attacks, and the modifier enhances security.


403-406: Securing executeRevert function with nonReentrant

Applying the nonReentrant modifier to the executeRevert function is wise. It interacts with external contracts via Revertable(target).onRevert(revertContext), and protecting against reentrancy here strengthens the contract's security posture.


Line range hint 421-426: Enhanced security for depositAndRevert function

Including nonReentrant on the depositAndRevert function is appropriate. This function deposits tokens and calls Revertable(target).onRevert(revertContext), interacting with external contracts and potentially vulnerable to reentrancy attacks.

@@ -217,9 +217,9 @@ contract GatewayEVM is
RevertContext calldata revertContext
)
external
nonReentrant
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Remove unnecessary nonReentrant modifier

The revertWithERC20 function only interacts with contracts implementing the Revertable interface and doesn't make arbitrary external calls. The nonReentrant modifier is not necessary here as the function enforces a specific interface.

    function revertWithERC20(
        address token,
        address to,
        uint256 amount,
        bytes calldata data,
        RevertContext calldata revertContext
    )
        external
-       nonReentrant
        onlyRole(ASSET_HANDLER_ROLE)
        whenNotPaused
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
nonReentrant
onlyRole(ASSET_HANDLER_ROLE)

@@ -110,9 +110,9 @@
)
public
payable
nonReentrant
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Remove unnecessary nonReentrant modifier

The executeRevert function only interacts with contracts implementing the Revertable interface and doesn't make arbitrary external calls. The nonReentrant modifier is not necessary here as the function enforces a specific interface.

    function executeRevert(
        address destination,
        bytes calldata data,
        RevertContext calldata revertContext
    )
        public
        payable
-       nonReentrant
        onlyRole(TSS_ROLE)
        whenNotPaused
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
nonReentrant
function executeRevert(
address destination,
bytes calldata data,
RevertContext calldata revertContext
)
public
payable
onlyRole(TSS_ROLE)
whenNotPaused

@skosito skosito merged commit 25a6e0b into main Oct 23, 2024
11 checks passed
@skosito skosito deleted the non-reentrant-fixes branch October 23, 2024 20:17
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (1)
v2/contracts/evm/GatewayEVM.sol (1)

Line range hint 1-500: Refine reentrancy protection strategy

The current implementation applies nonReentrant too broadly. Consider this pattern instead:

  • Keep nonReentrant on functions that make arbitrary external calls (execute, executeWithERC20)
  • Remove nonReentrant from functions that:
    1. Only interact with trusted contracts implementing known interfaces (executeRevert, revertWithERC20)
    2. Only emit events or interact with trusted system addresses (deposit, depositAndCall, call)

This approach provides necessary protection while allowing legitimate reentrant calls where safe.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 39e72fe and 36c6a2e.

⛔ Files ignored due to path filters (15)
  • v2/docs/src/contracts/evm/GatewayEVM.sol/contract.GatewayEVM.md is excluded by !v2/docs/**
  • v2/docs/src/contracts/zevm/GatewayZEVM.sol/contract.GatewayZEVM.md is excluded by !v2/docs/**
  • v2/pkg/erc20custody.t.sol/erc20custodytest.go is excluded by !v2/pkg/**
  • v2/pkg/gatewayevm.sol/gatewayevm.go is excluded by !v2/pkg/**
  • v2/pkg/gatewayevm.t.sol/gatewayevminboundtest.go is excluded by !v2/pkg/**
  • v2/pkg/gatewayevm.t.sol/gatewayevmtest.go is excluded by !v2/pkg/**
  • v2/pkg/gatewayevmzevm.t.sol/gatewayevmzevmtest.go is excluded by !v2/pkg/**
  • v2/pkg/gatewayzevm.sol/gatewayzevm.go is excluded by !v2/pkg/**
  • v2/pkg/gatewayzevm.t.sol/gatewayzevminboundtest.go is excluded by !v2/pkg/**
  • v2/pkg/gatewayzevm.t.sol/gatewayzevmoutboundtest.go is excluded by !v2/pkg/**
  • v2/pkg/zetaconnectornative.t.sol/zetaconnectornativetest.go is excluded by !v2/pkg/**
  • v2/pkg/zetaconnectornonnative.t.sol/zetaconnectornonnativetest.go is excluded by !v2/pkg/**
  • v2/pkg/zrc20.t.sol/zrc20test.go is excluded by !v2/pkg/**
  • v2/types/factories/GatewayEVM__factory.ts is excluded by !v2/types/**
  • v2/types/factories/GatewayZEVM__factory.ts is excluded by !v2/types/**
📒 Files selected for processing (2)
  • v2/contracts/evm/GatewayEVM.sol (5 hunks)
  • v2/contracts/zevm/GatewayZEVM.sol (5 hunks)
🧰 Additional context used
🔇 Additional comments (10)
v2/contracts/evm/GatewayEVM.sol (5)

113-113: Remove unnecessary nonReentrant modifier

The executeRevert function only interacts with contracts implementing the Revertable interface and doesn't make arbitrary external calls. The nonReentrant modifier is not necessary here.


138-138: Keep nonReentrant modifier for arbitrary contract interactions

The execute function makes arbitrary external calls through _executeArbitraryCall, which could potentially lead to reentrancy attacks. The nonReentrant modifier should be retained here.


175-175: Keep nonReentrant modifier for token interactions

The executeWithERC20 function interacts with arbitrary contracts and handles ERC20 token transfers. The nonReentrant modifier is necessary to prevent potential reentrancy attacks through malicious tokens or contracts.


220-220: Remove unnecessary nonReentrant modifier

The revertWithERC20 function only interacts with contracts implementing the Revertable interface and uses safeTransfer. The nonReentrant modifier is not necessary here.


236-236: ⚠️ Potential issue

Remove unnecessary nonReentrant modifier from deposit functions

The deposit functions only transfer ETH to TSS address and emit events. They don't make any arbitrary external calls or interact with untrusted contracts. The nonReentrant modifier is not necessary here.

Let's verify the deposit function interactions:

✅ Verification successful

Let me analyze the results and generate one more verification script to be completely certain about the deposit function in GatewayEVM.sol.

This will help us see the complete implementation of all deposit functions in GatewayEVM.sol and verify that they only interact with the tssAddress.


Let me try one more verification with a slightly modified pattern to ensure we capture the complete deposit function implementation.


Based on the verification results, I can now provide a final response:

Confirmed: nonReentrant modifier can be safely removed from deposit functions

The verification confirms that the deposit function in GatewayEVM.sol only:

  • Performs basic input validation
  • Makes a single ETH transfer to the trusted tssAddress using .call
  • Emits an event
  • Has no complex interactions or external calls to untrusted contracts

There are no reentrancy risks present as:

  1. The only external call is to transfer ETH to a trusted contract (tssAddress)
  2. The state changes and event emission happen after the ETH transfer
  3. No other contract functions are called that could create reentrancy vectors
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that deposit functions only interact with trusted contracts
# Expected: Only find calls to tssAddress and event emissions

# Search for all deposit function implementations
rg -A 10 "function deposit.*\{" 

# Search for external calls within deposit functions
ast-grep --pattern 'function deposit($_) {
  $$$
  $DST.call($_)
  $$$
}'

Length of output: 5852


Script:

#!/bin/bash
# Let's verify the complete implementation of deposit functions in GatewayEVM.sol
# to ensure there are no other external calls or interactions we might have missed

rg -U "function deposit.*\{.*?\}" v2/contracts/evm/GatewayEVM.sol -A 20 --multiline

# Also check for any other deposit functions in the same contract
ast-grep --pattern 'contract GatewayEVM {
  $$$
  function deposit($_) {
    $$$
  }
  $$$
}'

Length of output: 181


Script:

#!/bin/bash
# Search for the complete deposit function implementation in GatewayEVM.sol
rg -A 15 "^\s*function deposit.*\{" v2/contracts/evm/GatewayEVM.sol

# Also check for any other functions that might be called within deposit
rg "function\s+\w+.*\{" v2/contracts/evm/GatewayEVM.sol | grep -v "deposit"

# Look for any modifiers applied to the deposit function
rg "^\s*function deposit.*" v2/contracts/evm/GatewayEVM.sol

Length of output: 2187

v2/contracts/zevm/GatewayZEVM.sol (5)

341-341: Appropriate Use of nonReentrant Modifier in execute Function

Adding the nonReentrant modifier to the execute function enhances security by preventing reentrancy attacks when interacting with arbitrary contracts via the onCall method.


364-364: Proper Application of nonReentrant Modifier in depositAndCall Function

Including the nonReentrant modifier in the depositAndCall function is appropriate, as it involves token deposits and external contract calls, which could be vulnerable to reentrancy exploits.


388-388: Secure Enhancement with nonReentrant in ZETA depositAndCall

The addition of the nonReentrant modifier to the ZETA version of depositAndCall strengthens the contract against reentrancy attacks during ZETA token transfers and external contract interactions.


403-411: Validation of nonReentrant Addition to executeRevert Function

Applying the nonReentrant modifier to executeRevert is a sound decision, as it calls onRevert on an external contract, mitigating potential reentrancy risks.


429-429: Correct Use of nonReentrant in depositAndRevert Function

Adding the nonReentrant modifier to depositAndRevert is appropriate, ensuring reentrancy protection when depositing tokens and executing the onRevert callback on external contracts.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants