Badger-Vested-Aura contest - defsec's results

Bringing BTC to DeFi

General Information

Platform: Code4rena

Start Date: 15/06/2022

Pot Size: $30,000 USDC

Total HM: 5

Participants: 55

Period: 3 days

Judge: Jack the Pug

Id: 138

League: ETH

BadgerDAO

Findings Distribution

Researcher Performance

Rank: 17/55

Findings: 3

Award: $203.40

🌟 Selected for report: 0

🚀 Solo Findings: 0

Findings Information

Awards

50.7077 USDC - $50.71

Labels

bug
duplicate
2 (Med Risk)
valid

External Links

Lines of code

https://github.com/Badger-Finance/vested-aura/blob/v0.0.2/contracts/MyStrategy.sol#L259

Vulnerability details

Impact

Trades can happen at a bad price and lead to receiving fewer tokens than at a fair market price. The attacker's profit is the protocol's loss.

Proof of Concept

MyStrategy contract has low slippage checks which can lead to being vulnerable to sandwich attacks.

A common attack in DeFi is the sandwich attack. Upon observing a trade of asset X for asset Y, an attacker frontruns the victim trade by also buying asset Y, lets the victim execute the trade, and then backruns (executes after) the victim by trading back the amount gained in the first trade. Intuitively, one uses the knowledge that someone’s going to buy an asset, and that this trade will increase its price, to make a profit. The attacker’s plan is to buy this asset cheap, let the victim buy at an increased price, and then sell the received amount again at a higher price afterwards.

In the exitPool call, you have to provide minAmountsOut, the lower limits for the tokens to receive. In short, what are the minimum amounts you would find acceptable, given the amount of BPT you are providing? A good practice would be to user queryExit in BalancerHelpers to find the current amounts of tokens you would get for your BPT, and then account for some possible slippage. Let's say that you want to allow a 1% slippage. After computing how many tokens you expect for a given amount of BPT, you'd apply a factor of 0.99 to all the amounts. These thresholds are important because it's possible for token amounts to change in the pool between the time you send your transaction and the when your transaction executes.

In the strategy contract, Its hardcoded as 2.

Tools Used

Code Review

IBalancerVault.ExitPoolRequest memory exitPoolRequest = IBalancerVault.ExitPoolRequest({ assets: assets, minAmountsOut: new uint256[](2), userData: abi.encode(ExitKind.EXACT_BPT_IN_FOR_ONE_TOKEN_OUT, balEthBptEarned, BPT_WETH_INDEX), toInternalBalance: false });

Add minimum return amount checks based on the queryExit in BalancerHelpers.

Accept a function parameter that can be chosen by the transaction sender, then check that the actually received amount is above this parameter.

Alternatively, check if it's feasible to send these transactions directly to a miner such that they are not visible in the public mempool.

#0 - GalloDaSballo

2022-06-19T00:37:53Z

We use private tx

#1 - GalloDaSballo

2022-06-22T00:40:51Z

dup of #155

Awards

102.4813 USDC - $102.48

Labels

bug
QA (Quality Assurance)
sponsor disputed
valid

External Links

ISSUE LIST

C4-001 : Missing events for only functions that change critical parameters - Non Critical
C4-002 : Critical changes should use two-step procedure - Non Critical
C4-003 : Missing zero-address/values check in the constructor - Low
C4-004 : The Contract Should approve(0) first - Low
C4-005 : Incompatibility With Rebasing/Deflationary/Inflationary tokens - Non Critical
C4-006 : Front-runnable Initializers - LOW
C4-007 : Bump OZ packages to ^4.5.0. - Non critical
C4-008 : Natspec documentation is missing in the contract - LOW
C4-009 : Open TODOs - LOW
C4-010 : Unbounded loops with external calls - Non critical

ISSUES

C4-001 : Missing events for only functions that change critical parameters

Impact - Non critical

The afunctions that change critical parameters should emit events. Events allow capturing the changed parameters so that off-chain tools/interfaces can register such changes with timelocks that allow users to evaluate them and consider if they would like to engage/exit based on how they perceive the changes as affecting the trustworthiness of the protocol or profitability of the implemented financial services. The alternative of directly querying on-chain contract state for such changes is not considered practical for most users/usages.

Missing events and timelocks do not promote transparency and if such changes immediately affect users’ perception of fairness or trustworthiness, they could exit the protocol causing a reduction in liquidity which could negatively impact protocol TVL and reputation.

Proof of Concept

  1. Navigate to the following contract.
https://github.com/Badger-Finance/vested-aura/blob/v0.0.2/contracts/MyStrategy.sol#L86 https://github.com/Badger-Finance/vested-aura/blob/v0.0.2/contracts/MyStrategy.sol#L92 https://github.com/Badger-Finance/vested-aura/blob/v0.0.2/contracts/MyStrategy.sol#L98

See similar High-severity H03 finding OpenZeppelin’s Audit of Audius (https://blog.openzeppelin.com/audius-contracts-audit/#high) and Medium-severity M01 finding OpenZeppelin’s Audit of UMA Phase 4 (https://blog.openzeppelin.com/uma-audit-phase-4/)

Tools Used

None

Add events to all functions that change critical parameters.

C4-002 : Critical changes should use two-step procedure

Impact - NON CRITICAL

The critical procedures should be two step process.

Proof of Concept

  1. Navigate to the following contract.
https://github.com/Badger-Finance/vested-aura/blob/v0.0.2/contracts/MyStrategy.sol#L98

Tools Used

Code Review

Lack of two-step procedure for critical operations leaves them error-prone. Consider adding two step procedure on the critical functions.

C4-003 : # Missing zero-address&values check

Impact

Missing checks for zero-addresses&values may lead to infunctional protocol, if the variable addresses are updated incorrectly.

Proof of Concept

There are a few validations that could be added to the system:

https://github.com/Badger-Finance/vested-aura/blob/v0.0.2/contracts/MyStrategy.sol#L98

Tools Used

Code Review

Consider adding zero-address and zero value checks.

C4-004 : The Contract Should approve(0) first

Impact - LOW

Some tokens (like USDT L199) do not work when changing the allowance from an existing non-zero allowance value. They must first be approved by zero and then the actual allowance must be approved.

IERC20(token).safeApprove(address(operator), 0); IERC20(token).safeApprove(address(operator), amount);

Proof of Concept

  1. Navigate to the following contract.
https://github.com/Badger-Finance/vested-aura/blob/v0.0.2/contracts/MyStrategy.sol#L67 https://github.com/Badger-Finance/vested-aura/blob/v0.0.2/contracts/MyStrategy.sol#L68
  1. When trying to re-approve an already approved token, all transactions revert and the protocol cannot be used.

Tools Used

None

Approve with a zero amount first before setting the actual amount. Consider use safeIncreaseAllowance and safeDecreaseAllowance.

C4-005 : Incompatibility With Rebasing/Deflationary/Inflationary tokens

Impact - LOW

PrePo protocol do not appear to support rebasing/deflationary/inflationary tokens whose balance changes during transfers or over time. The necessary checks include at least verifying the amount of tokens transferred to contracts before and after the actual transfer to infer any fees/interest.

Proof of Concept

  1. Navigate to the following contract.
https://github.com/Badger-Finance/vested-aura/blob/v0.0.2/contracts/MyStrategy.sol#L107

Tools Used

Manual Code Review

  • Ensure that to check previous balance/after balance equals to amount for any rebasing/inflation/deflation
  • Add support in contracts for such tokens before accepting user-supplied tokens
  • Consider supporting deflationary / rebasing / etc tokens by extra checking the balances before/after or strictly inform your users not to use such tokens if they don't want to lose them.

C4-006 : Front-runnable Initializers

Impact - LOW

All contract initializers were missing access controls, allowing any user to initialize the contract. By front-running the contract deployers to initialize the contract, the incorrect parameters may be supplied, leaving the contract needing to be redeployed.

Proof of Concept

  1. Navigate to the following contract.
https://github.com/Badger-Finance/vested-aura/blob/v0.0.2/contracts/MyStrategy.sol#L56
  1. initialize functions does not have access control. They are vulnerable to front-running.

Tools Used

Manual Code Review

While the code that can be run in contract constructors is limited, setting the owner in the contract's constructor to the msg.sender and adding the onlyOwner modifier to all initializers would be a sufficient level of access control.

C4-007: Bump OZ packages to ^4.5.0.

Impact - NON CRITICAL

Line Reference

https://github.com/Badger-Finance/vested-aura/blob/v0.0.2/brownie-config.yaml#L11

Description

I can verify that the installed version is 3.4.0 by executing the following commands:

https://github.com/Badger-Finance/vested-aura/blob/v0.0.2/brownie-config.yaml#L11

Update the versions of @openzeppelin/contracts and @openzeppelin/contracts-upgradeable to be the latest in package.json. I also recommend double checking the versions of other dependencies as a precaution, as they may include important bug fixes.

C4-008: Natspec Documentation Is Missing

Impact - NON CRITICAL

Line Reference

https://github.com/Badger-Finance/vested-aura/blob/v0.0.2/contracts/MyStrategy.sol#L78

Ensure that the code is well commented on both with NatSpec and inline comments for better readability and maintainability. The comments should accurately reflect what the corresponding code does.

Follow the official NatSpec comment guidelines to make the contract more readable. https://docs.soliditylang.org/en/develop/natspec-format.html

C4-009 : Open TODOs

Impact

Open TODOs can point to architecture or programming issues that still need to be resolved.

Proof of Concept

  1. Navigate to the following contract.
https://github.com/Badger-Finance/vested-aura/blob/v0.0.2/contracts/MyStrategy.sol#L284

Tools Used

None

Consider resolving the TODOs before deploying.

C4-010 : Unbounded loops with external calls

Impact

The interface and the function should require a start index and a lenght, so that the index composition can be fetched in batches without running out of gas. If there are thousands of index components (e.g. like the Wilshire 5000 index), the function may revert.

Proof of Concept

  1. Navigate to the following contract.
https://github.com/Badger-Finance/vested-aura/blob/v0.0.2/contracts/MyStrategy.sol#L288

Tools Used

None

Define proper bounds on the for loops.

#0 - GalloDaSballo

2022-06-19T02:06:46Z

<img width="359" alt="Screenshot 2022-06-19 at 04 06 27" src="https://user-images.githubusercontent.com/13383782/174462915-174a2d56-3202-4245-ba8b-8c83c954a6ce.png">

Let's just penalize this submission

Awards

50.2119 USDC - $50.21

Labels

bug
G (Gas Optimization)
valid

External Links

[S]: Suggested optimation, save a decent amount of gas without compromising readability;

[M]: Minor optimation, the amount of gas saved is minor, change when you see fit;

[N]: Non-preferred, the amount of gas saved is at cost of readability, only apply when gas saving is a top priority.

ISSUE LIST
C4-001 : Free gas savings for using solidity 0.8.10+ - [S]
C4-002: Revert String Size Optimization - [S]
C4-003 : Adding unchecked directive can save gas - [S]
C4-004 : Check if amount > 0 before token transfer can save gas - [S]
C4-005 : There is no need to assign default values to variables - [N]
C4-006 : Free gas savings for using solidity 0.8.10+ - [S]
C4-007 : Using operator && used more gas - [M]
C4-008 : Non-strict inequalities are cheaper than strict ones - [N]
C4-009 : Use Custom Errors instead of Revert Strings to save Gas - [S]
C4-010 : Use Shift Right/Left instead of Division/Multiplication if possible [N]
C4-011 : Cache array length in for loops can save gas - [S]
C4-012 : State Variables that can be changed to immutable - [N]
C4-013 : Use calldata instead of memory for function parameters - [M]
C4-014 : ABIEncoderV2 is activated by default from version 0.8.0 - [M]

C4-001 : Free gas savings for using solidity 0.8.10+

Impact

Using newer compiler versions and the optimizer gives gas optimizations and additional safety checks are available for free.

Proof of Concept

All Contracts

Solidity 0.8.10 has a useful change which reduced gas costs of external calls which expect a return value: https://blog.soliditylang.org/2021/11/09/solidity-0.8.10-release-announcement/

Solidity 0.8.13 has some improvements too but not well tested.

Code Generator: Skip existence check for external contract if return data is expected. In this case, the ABI decoder will revert if the contract does not exist

All Contracts

Tools Used

None

Consider to upgrade pragma to at least 0.8.10.

C4-002: Revert String Size Optimization

Impact

Shortening revert strings to fit in 32 bytes will decrease deploy time gas and will decrease runtime gas when the revert condition has been met.

Revert strings that are longer than 32 bytes require at least one additional mstore, along with additional overhead for computing memory offset, etc.

Proof of Concept

Revert strings > 32 bytes are here:

https://github.com/Badger-Finance/vested-aura/blob/v0.0.2/contracts/MyStrategy.sol#L184 https://github.com/Badger-Finance/vested-aura/blob/v0.0.2/contracts/MyStrategy.sol#L205 https://github.com/Badger-Finance/vested-aura/blob/v0.0.2/contracts/MyStrategy.sol#L290

Tools Used

Manual Review

Shorten the revert strings to fit in 32 bytes. That will affect gas optimization.

C4-003 : Adding unchecked directive can save gas

Impact

For the arithmetic operations that will never over/underflow, using the unchecked directive (Solidity v0.8 has default overflow/underflow checks) can save some gas from the unnecessary internal over/underflow checks.

Proof of Concept

https://github.com/Badger-Finance/vested-aura/blob/v0.0.2/contracts/MyStrategy.sol#L300 https://github.com/Badger-Finance/vested-aura/blob/v0.0.2/contracts/MyStrategy.sol#L153 https://github.com/Badger-Finance/vested-aura/blob/v0.0.2/contracts/MyStrategy.sol#L317

Tools Used

None

Consider applying unchecked arithmetic where overflow/underflow is not possible. Example can be seen from below.

Unchecked{i++};

C4-004 : Check if amount > 0 before token transfer can save gas

Impact

Since _amount can be 0. Checking if (_amount != 0) before the transfer can potentially save an external call and the unnecessary gas cost of a 0 token transfer.

Proof of Concept

https://github.com/Badger-Finance/vested-aura/blob/v0.0.2/contracts/MyStrategy.sol#L421 https://github.com/Badger-Finance/vested-aura/blob/v0.0.2/contracts/MyStrategy.sol#L429

All Contracts

Tools Used

None

Consider checking amount != 0.

C4-005 : There is no need to assign default values to variables

Impact - Gas Optimization

Boolean is default initialized to false. There is no need assign false to variable.

Proof of Concept

https://github.com/Badger-Finance/vested-aura/blob/v0.0.2/contracts/MyStrategy.sol#L300 https://github.com/Badger-Finance/vested-aura/blob/v0.0.2/contracts/MyStrategy.sol#L153 https://github.com/Badger-Finance/vested-aura/blob/v0.0.2/contracts/MyStrategy.sol#L317

Tools Used

Code Review

bool x = false costs more gas than bool x without having any different functionality.

C4-006 : Free gas savings for using solidity 0.8.13+

Impact

Using newer compiler versions and the optimizer gives gas optimizations and additional safety checks are available for free.

Proof of Concept

All Contracts

Solidity 0.8.14 has a useful change which reduced gas costs of external calls which expect a return value: https://blog.soliditylang.org/2021/11/09/solidity-0.8.10-release-announcement/

Solidity 0.8.13 has some improvements too but not well tested.

Code Generator: Skip existence check for external contract if return data is expected. In this case, the ABI decoder will revert if the contract does not exist

All Contracts

Tools Used

None

Consider to upgrade pragma to at least 0.8.13.

C4-007 : Using operator && used more gas

Impact

Using double require instead of operator && can save more gas.

Proof of Concept

  1. Navigate to the following contracts.
https://github.com/Badger-Finance/vested-aura/blob/v0.0.2/contracts/MyStrategy.sol#L185

Tools Used

Code Review

Example

using &&: function check(uint x)public view{ require(x == 0 && x < 1 ); } // gas cost 21630 using double require: require(x == 0 ); require( x < 1); } } // gas cost 21622

C4-008 : Non-strict inequalities are cheaper than strict ones

Impact

Strict inequalities add a check of non equality which costs around 3 gas.

Proof of Concept

https://github.com/Badger-Finance/vested-aura/blob/v0.0.2/contracts/MyStrategy.sol#L230 https://github.com/Badger-Finance/vested-aura/blob/v0.0.2/contracts/MyStrategy.sol#L279 https://github.com/Badger-Finance/vested-aura/blob/v0.0.2/contracts/MyStrategy.sol#L323 https://github.com/Badger-Finance/vested-aura/blob/v0.0.2/contracts/MyStrategy.sol#L387

Tools Used

Code Review

Use >= or <= instead of > and < when possible.

C4-009 : Use Custom Errors instead of Revert Strings to save Gas

Custom errors from Solidity 0.8.4 are cheaper than revert strings (cheaper deployment cost and runtime cost when the revert condition is met)

Source Custom Errors in Solidity:

Starting from Solidity v0.8.4, there is a convenient and gas-efficient way to explain to users why an operation failed through the use of custom errors. Until now, you could already use strings to give more information about failures (e.g., revert("Insufficient funds.");), but they are rather expensive, especially when it comes to deploy cost, and it is difficult to use dynamic information in them.

Custom errors are defined using the error statement, which can be used inside and outside of contracts (including interfaces and libraries).

Instances include:

All require Statements

Tools Used

Code Review

Recommended to replace revert strings with custom errors.

C4-010 : Use Shift Right/Left instead of Division/Multiplication if possible

Impact

A division/multiplication by any number x being a power of 2 can be calculated by shifting log2(x) to the right/left.

While the DIV opcode uses 5 gas, the SHR opcode only uses 3 gas. Furthermore, Solidity's division operation also includes a division-by-0 prevention which is bypassed using shifting.

Proof of Concept

Contracts

Tools Used

None

A division/multiplication by any number x being a power of 2 can be calculated by shifting log2(x) to the right/left.

C4-011 : Cache array length in for loops can save gas

Impact

Reading array length at each iteration of the loop takes 6 gas (3 for mload and 3 to place memory_offset) in the stack.

Caching the array length in the stack saves around 3 gas per iteration.

Proof of Concept

  1. Navigate to the following smart contract line.
https://github.com/Badger-Finance/vested-aura/blob/v0.0.2/contracts/MyStrategy.sol#L300 https://github.com/Badger-Finance/vested-aura/blob/v0.0.2/contracts/MyStrategy.sol#L317

Tools Used

None

Consider to cache array length.

C4-012 : State Variables that can be changed to immutable

Impact

Solidity 0.6.5 introduced immutable as a major feature. It allows setting contract-level variables at construction time which gets stored in code rather than storage.

Consider the following generic example:

contract C { /// The owner is set during contruction time, and never changed afterwards. address public owner = msg.sender; }

In the above example, each call to the function owner() reads from storage, using a sload. After EIP-2929, this costs 2100 gas cold or 100 gas warm. However, the following snippet is more gas efficient:

contract C { /// The owner is set during contruction time, and never changed afterwards. address public immutable owner = msg.sender; }

In the above example, each storage read of the owner state variable is replaced by the instruction push32 value, where value is set during contract construction time. Unlike the last example, this costs only 3 gas.

Tools Used

None

Consider using immutable variable.

C4-013 : Use calldata instead of memory for function parameters

Impact

In some cases, having function arguments in calldata instead of memory is more optimal.

Consider the following generic example:

contract C { function add(uint[] memory arr) external returns (uint sum) { uint length = arr.length; for (uint i = 0; i < arr.length; i++) { sum += arr[i]; } } }

In the above example, the dynamic array arr has the storage location memory. When the function gets called externally, the array values are kept in calldata and copied to memory during ABI decoding (using the opcode calldataload and mstore). And during the for loop, arr[i] accesses the value in memory using a mload. However, for the above example this is inefficient. Consider the following snippet instead:

contract C { function add(uint[] calldata arr) external returns (uint sum) { uint length = arr.length; for (uint i = 0; i < arr.length; i++) { sum += arr[i]; } } }

In the above snippet, instead of going via memory, the value is directly read from calldata using calldataload. That is, there are no intermediate memory operations that carries this value.

Gas savings: In the former example, the ABI decoding begins with copying value from calldata to memory in a for loop. Each iteration would cost at least 60 gas. In the latter example, this can be completely avoided. This will also reduce the number of instructions and therefore reduces the deploy time cost of the contract.

In short, use calldata instead of memory if the function argument is only read.

Note that in older Solidity versions, changing some function arguments from memory to calldata may cause "unimplemented feature error". This can be avoided by using a newer (0.8.*) Solidity compiler.

Proof of Concept

  1. Navigate to the following smart contract line.
https://github.com/Badger-Finance/vested-aura/blob/v0.0.2/contracts/MyStrategy.sol#L149

Tools Used

None

Some parameters in examples given above are later hashed. It may be beneficial for those parameters to be in memory rather than calldata.

C4-014 : ABIEncoderV2 is activated by default from version 0.8.0

Impact

From Pragma 0.8.0, ABI coder v2 is activated by default. The pragma abicoder v2 can be deleted from the repository. That will provide gas optimization.

Proof of Concept

1. All contracts are using abicoder v2.

Tools Used

None

After the 0.8.0, ABI coder v2 is activated by default. Upgrade pragma to 0.8.0 version. It is recommended to delete redundant codes.

From Solidity v0.8.0 Breaking Changes https://docs.soliditylang.org/en/v0.8.0/080-breaking-changes.html

AuditHub

A portfolio for auditors, a security profile for protocols, a hub for web3 security.

Built bymalatrax © 2024

Auditors

Browse

Contests

Browse

Get in touch

ContactTwitter