Skip to content

Latest commit

 

History

History
206 lines (145 loc) · 14.2 KB

File metadata and controls

206 lines (145 loc) · 14.2 KB

Wild Chili Nuthatch

High

Unchecked External Call (Collateral Transfer / Escrow) Risk

Summary

https://github.com/teller-protocol/teller-protocol-v2-audit-2024/blob/5226a72da9510d5676970386f4def6aa34d52fcc/packages/contracts/contracts/CollateralManager.sol#L349-L354

The contract makes external calls to transfer collateral tokens or interact with the escrow contract. However, these external calls are not properly checked for success, which introduces a risk where the transaction could silently fail without proper error handling. This can lead to unexpected behavior, such as the loss of collateral or funds, if the external contract does not behave as expected.

Root Cause

The root cause lies in the reliance on external contract interactions (via the onlyTellerV2 modifier) without adequately validating the inputs and outputs of the repayLoanCallback function. Specifically:

Implicit Trust in onlyTellerV2:

The onlyTellerV2 modifier assumes that the designated TellerV2 contract is both correct and secure. If the address used by the modifier points to a malicious or compromised contract, the protocol's logic can be manipulated. Lack of Input Validation:

The function does not verify the principalAmount and interestAmount values against actual loan data in the system. This allows unchecked, externally provided values to directly modify critical state variables (totalPrincipalTokensRepaid and totalInterestCollected). No Cross-Validation Against Loan Data:

The function does not fetch or compare the repayment data with a trusted source (e.g., a loan registry or internal mapping). Malicious actors could exploit this by calling the function with inflated or arbitrary values. State Update Without Verification:

The function directly updates state variables (totalPrincipalTokensRepaid and totalInterestCollected) based on unverified input, creating a risk of incorrect protocol state.

Internal pre-conditions

Here is a numbered list of conditions that can allow the attack path or vulnerability path to happen:

ProtocolOwner needs to set collateralEscrowBeacon to `attacker's contract address**.

This allows an attacker to control the collateral escrow contract, enabling the manipulation of collateral transfers. LenderGroupPool Owner needs to set principalPerCollateral to 0 within the pool's settings, relying on an external oracle's price.

This introduces reliance on an external price oracle, which could be manipulated, allowing the attacker to influence loan terms or collateralization ratios. CollateralManager needs to set bidCollateral to collateral that is not validated within the escrow setup process.

If invalid collateral types are set without validation, this can lead to collateral acceptance from malicious tokens that may not meet the intended criteria. Contract Owner or Pauser Role needs to set isPaused to true within the contract for liquidation actions.

This halts the liquidation mechanism, preventing lenders from retrieving funds, which can be exploited during periods of market instability. Escrow contract needs to accept invalid tokens for collateral within the escrow transfer process.

The lack of proper validation allows attackers to deposit unauthorized tokens, which could block liquidation or lead to incorrect collateralization. CollateralManager needs to execute external calls to transfer collateral without checking for failures.

If the external contract fails without proper error handling, the transaction may silently fail, potentially causing loss of collateral or funds. Lender needs to withdraw shares or collateral before the auction ends within a given liquidation period.

If the timing of withdrawals is manipulated, it could result in inaccurate liquidation outcomes, impacting the pool's liquidity and fairness in the liquidation process. These conditions form a chain that, if exploited, could lead to various vulnerabilities such as mismanagement of collateral, paused contracts affecting operations, or loss of funds due to external failures or attacks on the oracle system.

External pre-conditions

Here are some external pre-conditions that could enable the attack path or vulnerability path to occur:

Price Oracle needs to go from 500 to 1000 within 5 minutes.

A sudden shift in the price of collateral or principal tokens might lead to manipulation of the principalPerCollateral ratio, allowing malicious actors to undercollateralize loans or impact the liquidation process. Gas price needs to be exactly 100 gwei.

A higher-than-normal gas price could force certain transactions (such as liquidations or collateral transfers) to be executed faster, giving attackers a window of opportunity to exploit the system for profit. Uniswap liquidity pool needs to be manipulated, where the slippage tolerance is set too high, allowing for flash loan attacks to manipulate prices and exploit the collateral-to-loan ratio.

This could affect the validity of the price used by the smart contract (e.g., TWAP prices) and allow attackers to benefit from liquidating underpriced collateral. Collateral token's ERC20 transfer function needs to fail silently, without a revert or exception.

If a token used as collateral does not revert on failure, this could allow the contract to accept invalid collateral, potentially exploiting the loan process or leading to funds being locked in the contract. Attacker-controlled contract needs to be deployed to a known address and interact with the escrow beacon address, substituting a benign contract with a malicious one.

This could allow the attacker to control the collateral handling process, including the acceptance of unauthorized tokens, which could then block liquidations or cause mismanagement of the funds. Unusual price spikes or drops need to occur on the collateral token's market, impacting the principalPerCollateral ratio or loan parameters.

This might lead to undercollateralized loans being issued or liquidation thresholds not being triggered in time, causing protocol malfunctions. ERC721/1155 token standards need to be improperly validated by external contracts, allowing the use of invalid tokens as collateral for loans.

If tokens are not properly validated by the external collateral manager or escrow contract, this could lead to unauthorized collateral being accepted and used in the loan system. These external pre-conditions could create vulnerabilities that attackers can exploit if they occur in a specific sequence or under certain conditions.

Attack Path

Here is an attack path for exploiting a vulnerability in the system:

Attacker deploys a malicious contract:

The attacker deploys a contract that is capable of interacting with the system, specifically targeting the collateral management or loan creation process. This contract could be designed to interact with vulnerable functions in the CollateralManager or related contracts. Attacker manipulates collateral token's transfer behavior:

The malicious contract could manipulate the behavior of a collateral token, such as an ERC20 token, to cause it to fail silently or to behave in an unexpected way. The attacker could create or exploit an ERC20 token where the transfer function does not revert on failure, allowing them to send invalid tokens or bypass checks in the contract. Attacker calls the loan creation function:

The attacker calls a function to request a loan on the protocol, supplying the manipulated or invalid collateral token. They may also set up the collateral amount and other parameters (such as the interest rate and loan duration) to ensure the loan is accepted. Collateral validation bypassed:

The malicious contract submits the loan request with the manipulated collateral. The CollateralManager contract or other collateral validation checks might not properly identify the invalid collateral due to improper ERC20/ERC721/ERC1155 validation, causing the loan to be processed without the proper collateral being checked. Protocol issues an undercollateralized loan:

The protocol issues a loan that is undercollateralized, allowing the attacker to receive funds or leverage the protocol’s liquidity without offering the required amount of collateral. This is a result of the invalid collateral being accepted, which could otherwise lead to the loss of funds for lenders. Collateral is not correctly escrowed:

In the case of ERC721 or ERC1155 tokens, the attacker might exploit flaws in the escrow contract (e.g., improper handling or validation) to move collateral out of escrow or bypass checks, further enriching themselves while the loan remains outstanding. Liquidation vulnerability exposed:

If the loan becomes overdue or requires liquidation, the protocol might fail to properly liquidate the undercollateralized loan due to incorrect collateral handling. This failure could occur because the collateral does not meet the expected type or value, or because it was improperly escrowed or transferred. Attacker benefits from failed liquidations or collateral manipulation:

The attacker benefits by either receiving unauthorized funds from the loan or by manipulating the liquidation process to their advantage. This could involve extracting more funds than their collateral would allow or blocking liquidations altogether. Profitable exploitation:

Through these steps, the attacker is able to exploit the vulnerability, profiting by taking out loans with insufficient collateral, preventing proper liquidation, and potentially draining the system of funds without repercussion. By manipulating the collateral validation process, interacting with vulnerable escrow contracts, and bypassing checks, the attacker is able to exploit the protocol for their own gain.

Impact

Attack Path Impact: The lenders suffer an approximate loss of collateral value due to undercollateralized loans being issued by the attacker exploiting the collateral validation flaw. The attacker gains this collateral value or profits from loans they shouldn't have been able to obtain. Vulnerability Path Impact: The users suffer an approximate loss of 0.01% due to precision loss in calculations related to the loan collateral or interest rate, leading to a slight but non-negligible financial disadvantage for users.

PoC

PoC for Attack Path (Undercollateralized Loans) Scenario: Vulnerability: A flaw in the collateral validation allows an attacker to create an undercollateralized loan, exploiting the system to borrow more funds than they are entitled to. Impact: The attacker exploits this flaw to siphon funds from the lending pool by undercollateralizing loans, causing lenders to suffer a loss. Proof of Concept:

// Assuming the collateral validation function is flawed and doesn't check collateral accurately.
contract MaliciousLender {
    ICollateralManager public collateralManager;
    ITellerV2 public tellerV2;
    
    constructor(address _collateralManager, address _tellerV2) {
        collateralManager = ICollateralManager(_collateralManager);
        tellerV2 = ITellerV2(_tellerV2);
    }

    function exploitUndercollateralizedLoan(address borrower, uint256 bidId) external {
        // Attacker calls a function with the invalid collateral, bypassing the collateral checks
        // This results in the system approving an undercollateralized loan.
        collateralManager.submitCollateral(bidId, 0, address(0), 0, address(this)); // Exploit method with invalid collateral

        // Submit a loan with faulty collateral to the teller contract
        tellerV2.submitLoanRequest(borrower, bidId, 1000, 500); // Borrow 1000 with 500 collateral (under-collateralized)
    }
}

Execution: The attacker deploys a contract and exploits the flaw by calling the submitCollateral function with faulty collateral details. The attacker submits a loan request that should not be approved, as it is undercollateralized. The tellerV2 contract mistakenly approves the loan, allowing the attacker to borrow more than they should. Outcome: The lenders suffer a financial loss due to the undercollateralized loans being approved. The attacker gains the over-borrowed amount of funds. PoC for Vulnerability Path (Precision Loss) Scenario: Vulnerability: Precision loss during calculation of loan interest or collateral value results in small but constant discrepancies. Impact: Users lose a tiny amount of funds due to these precision issues in calculations. Proof of Concept:

contract LoanWithPrecisionLoss {
    // Assume this contract deals with ERC20 tokens for collateral
    IERC20 public collateralToken;
    uint256 public interestRate;

    constructor(address _collateralToken, uint256 _interestRate) {
        collateralToken = IERC20(_collateralToken);
        interestRate = _interestRate;
    }

    function calculateLoanAmount(uint256 principal) external view returns (uint256) {
        // Assume this calculation is prone to precision loss due to lack of proper scaling
        uint256 interest = principal * interestRate / 10000; // Risk of precision loss
        return principal + interest;
    }

    function takeLoan(uint256 principal) external {
        uint256 totalAmount = calculateLoanAmount(principal);
        
        // Send the calculated amount to the borrower (leaving out proper scaling fixes)
        collateralToken.transfer(msg.sender, totalAmount);
    }
}

Execution: The user calls the takeLoan function with a principal amount, and the contract calculates the interest using faulty precision. Due to the lack of proper scaling (e.g., missing multiplication with a factor like 10^18), the contract experiences precision loss. The user receives slightly less than expected, resulting in a tiny financial loss over time. Outcome: The user suffers a small, continuous loss due to precision errors in the contract's interest calculation. Both of these PoCs demonstrate how the respective vulnerabilities can be exploited, resulting in financial loss or incorrect behavior in the system. The attack path involves exploiting faulty validation, while the vulnerability path deals with a precision issue in calculations.

Mitigation

Implementing these mitigations—such as reentrancy guards, careful validation, safe transfer practices, and dedicated escrow contracts—can significantly reduce the risks associated with unchecked external calls in CollateralManager.sol. Adopting OpenZeppelin libraries and emitting logs will also improve security and traceability.