Skip to content
Business logic Write-up Advanced

[web3] Port Finance Logic Error Bugfix Review. This is a postmortem of a vulnerability… | by Immunefi | May, 2022 | Medium

A logic error in Port Finance's collateral withdrawal calculation allowed a user to withdraw all collateral without fully repaying their debt. An attacker could have stolen $20–25 million by exploiting the mismatch between liquidation bonus and loan-to-value ratios.

medium.com

Published on medium.com

Port Finance

Immunefi, on medium.com

The full write-up lives on its author's site

It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 8 min read.

Context

Port Finance is a non-custodial money market protocol on Solana. Its stated goal is to bring a suite of interest rate products to the Solana blockchain, including variable rate lending, fixed rate lending and interest rate swap. The vulnerability described here lives in the collateral withdrawal logic of the lending pools, so a short recap of how the protocol models lending is needed first.

Lending pools are called Reserves and are described by a set of parameters held in ReserveConfig:

Rust
/// Lending market reserve state
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Reserve {
    /// Version of the struct
    pub version: u8,
    /// Last slot when supply and rates updated
    pub last_update: LastUpdate,
    /// Lending market address
    pub lending_market: Pubkey,
    /// Reserve liquidity
    pub liquidity: ReserveLiquidity,
    /// Reserve collateral
    pub collateral: ReserveCollateral,
    /// Reserve configuration values
    pub config: ReserveConfig,
}
Rust
/// Reserve configuration values
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct ReserveConfig {
    /// Optimal utilization rate, as a percentage
    pub optimal_utilization_rate: u8,
    /// Target ratio of the value of borrows to deposits, as a percentage
    /// 0 if use as collateral is disabled
    pub loan_to_value_ratio: u8,
    /// Bonus a liquidator gets when repaying part of an unhealthy obligation, as a percentage
    pub liquidation_bonus: u8,
    /// Loan to value ratio at which an obligation can be liquidated, as a percentage
    pub liquidation_threshold: u8,
    /// Min borrow APY
    pub min_borrow_rate: u8,
    /// Optimal (utilization) borrow APY
    pub optimal_borrow_rate: u8,
    /// Max borrow APY
    pub max_borrow_rate: u8,
    /// Program owner fees assessed, separate from gains due to interest accrual
    pub fees: ReserveFees,
    /// corresponded staking pool pubkey of deposit
    pub deposit_staking_pool: COption<Pubkey>,
}

loan_to_value_ratio sets the target LTV for the pool, and liquidation_bonus sets the discount at which liquidators can buy liquidated collateral. The value of collateral a liquidator receives is collateral_to_be_liquidated * (1 + liquidation_bonus): they pay for collateral_to_be_liquidated but receive that larger amount.

User positions are stored in Obligation structs, which hold every borrow and collateral deposit for a user:

Rust
/// Lending market obligation state
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Obligation {
    /// Version of the struct
    pub version: u8,
    /// Last update to collateral, liquidity, or their market values
    pub last_update: LastUpdate,
    /// Lending market address
    pub lending_market: Pubkey,
    /// Owner authority which can borrow liquidity
    pub owner: Pubkey,
    /// Deposited collateral for the obligation, unique by deposit reserve address
    pub deposits: Vec<ObligationCollateral>,
    /// Borrowed liquidity for the obligation, unique by borrow reserve address
    pub borrows: Vec<ObligationLiquidity>,
    /// Market value of deposits
    pub deposited_value: Decimal,
    /// Market value of borrows
    pub borrowed_value: Decimal,
    /// The maximum borrow value at the weighted average loan to value ratio
    pub allowed_borrow_value: Decimal,
    /// The dangerous borrow value at the weighted average liquidation threshold
    pub unhealthy_borrow_value: Decimal,
}

Interacting with collateral updates the deposits array; interacting with borrows updates the borrows array. Two derived values matter throughout:

  • allowed_borrow_value is the maximum total market value the user may borrow. It is the sum of the value of all user collaterals multiplied by the relevant pools' LTVs.
  • unhealthy_borrow_value is the borrowed value at which the collateral is at risk of liquidation. It is the sum of user collaterals multiplied by the relevant pools' liquidation thresholds, and it should be greater than allowed_borrow_value.
From the original on medium.com

Withdrawing collateral decreases both values. The maximum market value that could be withdrawn from an Obligation was computed by Obligation::max_withdraw_value:

Rust
/// Calculate the maximum collateral value that can be withdrawn
pub fn max_withdraw_value(&self) -> Result<Decimal, ProgramError> {
    let required_deposit_value = self
        .borrowed_value
        .try_mul(self.deposited_value)?
        .try_div(self.allowed_borrow_value)?;
    if required_deposit_value >= self.deposited_value {
        return Ok(Decimal::zero());
    }
    self.deposited_value.try_sub(required_deposit_value)
}

In words: the maximum withdrawable value was the delta between the total user deposit value and the total user deposit value multiplied by the borrow to allowed borrow ratio.

From the original on medium.com

Liquidation works on the other side. If an obligation's borrow_value exceeds its unhealthy_borrow_value, the obligation is liquidatable. Liquidators buy the collateral at a discount defined by the collateral reserve's liquidation_bonus, and a maximum of 50% of the total borrowed_value can be withdrawn in one go. The result is scaled by the bonus_rate for the collateral's reserve and transferred to the liquidator's account.

From the original on medium.com

Setup

The report does not describe any tooling, local validator, account setup or specific program version. What it does establish is the precondition for the attack: the attacker needs two reserves, one with a high liquidation bonus_rate and one with a high LTV, such that the sum of the first reserve's bonus_rate and the second reserve's LTV is greater than 100%. The attacker also needs to be able to create an obligation, deposit into both reserves, borrow, withdraw and liquidate, all as the owner of the obligation.

Finding it

The flaw is in max_withdraw_value, which computes the withdrawable amount from the aggregate borrowed_value, deposited_value and allowed_borrow_value. That treats the obligation as if all collateral were interchangeable and as if the only thing that matters is the aggregate borrow-to-allowed ratio. It does not take into account the LTV of the reserve whose collateral is being withdrawn.

The second half of the problem is the interaction with liquidation. Liquidation repays borrow and seizes collateral at a bonus. If the bonus on the collateral being seized is large enough relative to the borrow being repaid, the collateral can be drained faster than the debt is cleared.

Exploitation

Before the patch, a malicious user could withdraw all of their obligation collateral without paying off their full debt, under the following assumptions:

  1. They find some reserve R1 with high liquidation bonus_rate and some reserve R2 with high LTV such that the sum of reserve R1 bonus_rate and reserve R2 LTV is greater than 100%.
  2. They create an obligation and deposit some token T1 as collateral to reserve R1.
  3. They deposit some token T2 as collateral to reserve R2. The value of the T2 deposit should be greater than the value of the T1 deposit by several orders of magnitude, e.g. 3.
  4. They borrow token T2 from the reserve with high LTV. The borrow value should be similar to the value of the T1 token deposit.
  5. They withdraw the entire T2 token deposit. This makes their obligation liquidatable because the T2 token borrow is heavily undercollateralized now.
  6. They liquidate their obligation. Because the T2 token borrow value is similar to the value of the T1 token deposit and the R1 reserve has high bonus_rate, the obligation collateral is liquidated at a quicker pace than the borrow is being repaid, and the malicious user drains their T1 token deposit before they pay off their borrow in full.

The report does not include the individual transactions, instructions or account addresses used for these steps.

Root cause

The mistake is in Obligation::max_withdraw_value. It computes the withdrawable amount from the aggregate borrowed_value, deposited_value and allowed_borrow_value only. It never takes into account the LTV of the reserve whose collateral is being withdrawn. The check therefore allows a position to be left in a state that the protocol's own liquidation parameters make profitable to unwind: with a high enough bonus_rate on the remaining collateral, liquidation seizes collateral faster than it repays debt.

The existing defence, the max_withdraw_value check itself, did not stop the attack because it was the component that was wrong. The problem was that becoming liquidatable was the attacker's goal, not a failure of the attack.

Impact

If exploited, the vulnerability would have allowed a malicious attacker to steal $20-25 million. No user funds were lost because the bug was responsibly disclosed. Port Finance patched the bug and paid the whitehat $180,000 USD and $450,000 in PORT tokens linearly vested over a year, the maximum payout for Port Finance's bounty program. The attack requires the two-reserve precondition above (a high bonus_rate reserve and a high LTV reserve whose parameters sum to more than 100%), and the report frames the outcome in terms of what could have happened rather than a realised loss.

Fix

The Obligation::max_withdraw_value function was fixed by introducing the withdraw_collateral_ltv parameter, denoting the LTV of the reserve corresponding to the withdrawn collateral, and calculating the maximum withdraw value as the ratio of the delta of the allowed borrow value and the borrowed value, and the reserve LTV.

From the original on medium.com

Variants to test

  • Aggregate-ratio withdrawal checks in other lending protocols. Look for any withdraw or redeem path that computes a limit from total deposited value, total borrowed value and total allowed borrow value without the LTV of the specific reserve. A positive result is a position where withdrawing one collateral asset leaves the remaining collateral liquidatable at a bonus that exceeds the outstanding debt.
  • Cross-collateral parameter combinations. Enumerate reserves and check whether any pair has a liquidation bonus plus an LTV greater than 100%. A positive result is a pair where self-liquidation of a small position repays less than the collateral seized.
  • Self-liquidation paths. Check whether an obligation owner can liquidate their own obligation. If so, test whether the bonus on the seized collateral can exceed the value of the debt being repaid, which is the condition the report describes.
  • Withdrawal of the largest collateral first. In protocols that allow multiple collateral types, try depositing a very large amount of a high-LTV asset and a small amount of a high-bonus asset, borrowing against the high-LTV asset, then withdrawing the large deposit in full. A positive result is the position becoming liquidatable while the small high-bonus collateral remains.
  • Liquidation close-factor limits. The report notes that a maximum of 50% of the total borrowed_value can be withdrawn in one go. Test whether repeated partial liquidations, or a single liquidation sized to the cap, can still drain collateral faster than debt when the bonus is high enough.
  • Parameter changes after position creation. Check whether a position created under one set of reserve parameters can be withdrawn after those parameters change, and whether the withdrawal check uses current or cached values.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 17 min read.

What happened, in plain words

Port Finance is a service on a blockchain called Solana where people lend and borrow digital tokens. You put tokens in as security (called collateral), and the service lets you borrow other tokens against them. A person who goes by the name nojob found a flaw in how the service decided how much collateral a user was allowed to take back out. If someone had abused the flaw, they could have walked away with other people's money, somewhere between $20 and $25 million. nojob told Port Finance instead of stealing, Port Finance fixed the code quickly, and nojob was paid $180,000 in US dollars plus $450,000 in PORT tokens that unlock gradually over a year. That was the largest reward the Port Finance programme offers. Nobody lost funds.

This explanation was written by Piotr of Halborn, a company that audits DeFi security, for Immunefi, the platform that runs the bug bounty. A bug bounty is a public offer: find a flaw in our software, tell us privately, and we pay you. It is cheaper and safer for everyone than waiting for a criminal to find the same flaw.

Below I walk through what lending is, how Port Finance models it, where the mistake was, how it could have been used, and how it was fixed. Everything is explained from scratch, so you do not need to know any programming.

From the original on medium.com

A short introduction to lending

In traditional finance, the big capital markets are hard for ordinary people to reach. Only large players get in. If you want to fund a business, one route is to take a loan and hand over assets as collateral. The collateral is effectively frozen while the loan is outstanding, and you get it back later. It is not risk free: if you mismanage the loan, you can default and lose the collateral.

DeFi lending protocols opened this up to anyone. You lock digital assets as collateral and borrow against them. Decentralised lending has grown very fast since late 2020 and is one of the biggest categories in DeFi.

Borrowing

How much you may borrow is set by a number called LTV, short for Loan To Value. Think of it as the ratio between what you owe and what you have put up as security. Most protocols only allow overcollateralized loans, meaning you must lock more value than you borrow. If you borrow $60 of a cryptocurrency and lock $100 as collateral, your LTV is $60 divided by $100, which is 0.6.

Why insist on overcollateralization? Because the price of a cryptocurrency can fall sharply. The extra cushion means the lender is still covered if the collateral loses value.

Liquidations

Liquidation is the safety net that protects lenders from price swings. In plain terms, if your collateral is no longer worth enough to cover your loan, other people (liquidators) are allowed to buy your collateral at a discount. They do this by repaying part of your debt for you.

Lending pools set target LTVs. As a borrower, your main risk is that your position's LTV drifts past the target because prices move. Crypto prices are extremely volatile, so if your loan goes past the target you risk having your collateral liquidated. That is a bad outcome: you usually take a sizeable loss and pay a liquidation fee on top. That is why borrowers watch their collateral ratio closely.

Keeping state in order

DeFi generally avoids having a central company run everything; the community does. Blockchain applications also prefer a "push over pull" style: instead of one heavy operation, the protocol's state is updated in several smaller steps that must happen in a particular order. This keeps the design simple and gives users reasons to take part, for example rewards in tokens.

Looking at the vulnerability

Port Finance is a non-custodial money market protocol on Solana. "Non-custodial" means the service never holds your coins itself; the code moves them according to rules. Its aim is to bring a full set of interest rate products to Solana: variable rate lending, fixed rate lending and interest rate swaps.

Lending pools

Port Finance's lending pools are called Reserves. Each one is described by a set of settings held in a structure called ReserveConfig. A structure (or struct) is just a labelled bundle of values, like a form with named fields. Here is the Reserve struct:

Rust
/// Lending market reserve state
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Reserve {
    /// Version of the struct
    pub version: u8,
    /// Last slot when supply and rates updated
    pub last_update: LastUpdate,
    /// Lending market address
    pub lending_market: Pubkey,
    /// Reserve liquidity
    pub liquidity: ReserveLiquidity,
    /// Reserve collateral
    pub collateral: ReserveCollateral,
    /// Reserve configuration values
    pub config: ReserveConfig,
}

Line by line:

  • /// Lending market reserve state is a comment for humans; the computer ignores it.
  • #[derive(Clone, Debug, Default, PartialEq)] tells the compiler to generate some standard helper behaviour for this type automatically (copying it, printing it for debugging, creating an empty default, and comparing two of them).
  • pub struct Reserve { starts the definition of a new type called Reserve. pub means other parts of the program may use it.
  • pub version: u8, is a field named version holding a small unsigned number (u8 means a whole number from 0 to 255). It records which version of the layout this is.
  • pub last_update: LastUpdate, records when supply and interest rates were last refreshed.
  • pub lending_market: Pubkey, holds the address of the lending market this reserve belongs to. A Pubkey is a public identifier, like an account number on the blockchain.
  • pub liquidity: ReserveLiquidity, holds the pool's actual tokens and related bookkeeping.
  • pub collateral: ReserveCollateral, holds the pool's collateral side.
  • pub config: ReserveConfig, holds the settings, defined next.
  • } closes the struct.

Now the settings themselves:

Rust
/// Reserve configuration values
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct ReserveConfig {
    /// Optimal utilization rate, as a percentage
    pub optimal_utilization_rate: u8,
    /// Target ratio of the value of borrows to deposits, as a percentage
    /// 0 if use as collateral is disabled
    pub loan_to_value_ratio: u8,
    /// Bonus a liquidator gets when repaying part of an unhealthy obligation, as a percentage
    pub liquidation_bonus: u8,
    /// Loan to value ratio at which an obligation can be liquidated, as a percentage
    pub liquidation_threshold: u8,
    /// Min borrow APY
    pub min_borrow_rate: u8,
    /// Optimal (utilization) borrow APY
    pub optimal_borrow_rate: u8,
    /// Max borrow APY
    pub max_borrow_rate: u8,
    /// Program owner fees assessed, separate from gains due to interest accrual
    pub fees: ReserveFees,
    /// corresponded staking pool pubkey of deposit
    pub deposit_staking_pool: COption<Pubkey>,
}

Line by line:

  • The comment and #[derive(...)] line do the same kind of housekeeping as before; Copy additionally lets the value be duplicated by simple assignment.
  • pub struct ReserveConfig { starts the settings bundle.
  • optimal_utilization_rate is the share of the pool that is ideally lent out, as a percentage.
  • loan_to_value_ratio is the target LTV for this pool, as a percentage. The comment notes that a value of 0 means the asset cannot be used as collateral at all.
  • liquidation_bonus is the discount a liquidator gets when they repay part of an unhealthy obligation, as a percentage.
  • liquidation_threshold is the LTV at which an obligation becomes liquidatable, as a percentage.
  • min_borrow_rate, optimal_borrow_rate and max_borrow_rate are the interest rates (APY means annual percentage yield) at different levels of pool usage.
  • fees holds the programme owner's fees, kept separate from interest earnings.
  • deposit_staking_pool optionally records a staking pool address linked to deposits. COption<Pubkey> means "either a public key or nothing".
  • } closes the struct.

Two of these fields drive the whole story. loan_to_value_ratio sets the target LTV for the pool. liquidation_bonus sets the discount at which liquidators can buy liquidated collateral. In plain terms, the value of collateral a liquidator receives is collateral_to_be_liquidated * (1 + liquidation_bonus): they pay for collateral_to_be_liquidated but receive that larger amount. A 10% bonus means they pay for 100 units and receive 110.

User positions

Each user's position is stored in an Obligation struct, which records every borrow and every collateral deposit that user has:

Rust
/// Lending market obligation state
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Obligation {
    /// Version of the struct
    pub version: u8,
    /// Last update to collateral, liquidity, or their market values
    pub last_update: LastUpdate,
    /// Lending market address
    pub lending_market: Pubkey,
    /// Owner authority which can borrow liquidity
    pub owner: Pubkey,
    /// Deposited collateral for the obligation, unique by deposit reserve address
    pub deposits: Vec<ObligationCollateral>,
    /// Borrowed liquidity for the obligation, unique by borrow reserve address
    pub borrows: Vec<ObligationLiquidity>,
    /// Market value of deposits
    pub deposited_value: Decimal,
    /// Market value of borrows
    pub borrowed_value: Decimal,
    /// The maximum borrow value at the weighted average loan to value ratio
    pub allowed_borrow_value: Decimal,
    /// The dangerous borrow value at the weighted average liquidation threshold
    pub unhealthy_borrow_value: Decimal,
}

Line by line:

  • version records the layout version.
  • last_update records when collateral, liquidity or their market values last changed.
  • lending_market is the market address.
  • owner is the address allowed to borrow against this position. Think of it as the account holder.
  • deposits: Vec<ObligationCollateral> is a list (a Vec is a growable list) of collateral deposits, one per reserve address.
  • borrows: Vec<ObligationLiquidity> is a list of borrows, one per borrow reserve address.
  • deposited_value: Decimal is the total market value of the deposits. Decimal is a number type that handles fractions precisely, which matters for money.
  • borrowed_value: Decimal is the total market value of the borrows.
  • allowed_borrow_value: Decimal is the maximum value the user may borrow, at the weighted average LTV.
  • unhealthy_borrow_value: Decimal is the borrowed value at which the position becomes dangerous, at the weighted average liquidation threshold.
  • } closes the struct.

When a user touches their collateral, the deposits list is updated. When they touch their borrows, the borrows list is updated. Two derived numbers matter throughout:

  • allowed_borrow_value is the maximum total market value the user may borrow. It is the sum of the value of all the user's collateral, each multiplied by the LTV of the pool it sits in.
  • unhealthy_borrow_value is the borrowed value at which the collateral is at risk of liquidation. It is the sum of the user's collateral, each multiplied by the liquidation threshold of its pool. It should always be greater than allowed_borrow_value.
From the original on medium.com

Withdrawing collateral

Each deposit is recorded in the user's Obligation, either updating or adding an ObligationCollateral entry. Users can take collateral back out, which lowers both allowed_borrow_value and unhealthy_borrow_value.

The maximum market value that could be withdrawn from an Obligation was computed by a function called Obligation::max_withdraw_value:

Rust
/// Calculate the maximum collateral value that can be withdrawn
pub fn max_withdraw_value(&self) -> Result<Decimal, ProgramError> {
    let required_deposit_value = self
        .borrowed_value
        .try_mul(self.deposited_value)?
        .try_div(self.allowed_borrow_value)?;
    if required_deposit_value >= self.deposited_value {
        return Ok(Decimal::zero());
    }
    self.deposited_value.try_sub(required_deposit_value)
}

Line by line:

  • The comment says what the function does: work out the largest collateral value that may be withdrawn.
  • pub fn max_withdraw_value(&self) declares a function that can be called from elsewhere. &self means it reads the obligation it belongs to.
  • -> Result<Decimal, ProgramError> says the function returns either a Decimal (the answer) or a ProgramError (something went wrong). This is Rust's way of forcing callers to handle failure.
  • let required_deposit_value = self starts a calculation and stores the result in a variable named required_deposit_value.
  • .borrowed_value takes the total borrowed value.
  • .try_mul(self.deposited_value)? multiplies it by the total deposited value. try_mul is a checked multiplication: if the numbers overflow, it returns an error instead of a wrong answer, and the ? passes that error up to the caller.
  • .try_div(self.allowed_borrow_value)? divides the result by the allowed borrow value, again with an error check.
  • if required_deposit_value >= self.deposited_value { checks whether the required deposit is at least as large as what the user actually deposited.
  • return Ok(Decimal::zero()); if so, the answer is zero: nothing may be withdrawn.
  • } closes the check.
  • self.deposited_value.try_sub(required_deposit_value) otherwise subtracts the required amount from the deposited value and returns the difference. That difference is the maximum withdrawable value.
  • } closes the function.

In words: the maximum withdrawable value was the difference between the total user deposit value and the total user deposit value multiplied by the ratio of borrow to allowed borrow.

From the original on medium.com

Liquidating collateral

Liquidation works from the other side. If an obligation's borrow_value is greater than its unhealthy_borrow_value, the obligation is liquidatable. Liquidators can then buy the collateral at a discount set by the collateral reserve's liquidation_bonus. A maximum of 50% of the total borrowed_value can be withdrawn in one go. The result is scaled by the bonus_rate for the collateral's reserve and sent to the liquidator's account.

From the original on medium.com

Setting up the attack

The report does not describe any tooling, local test network, account setup or specific program version. What it does establish is the precondition: the attacker needs two reserves, one with a high liquidation bonus_rate and one with a high LTV, such that the sum of the first reserve's bonus_rate and the second reserve's LTV is greater than 100%. The attacker also needs to be able to create an obligation, deposit into both reserves, borrow, withdraw and liquidate, all as the owner of the obligation.

Finding the flaw

The mistake is in how max_withdraw_value reasons about the position. It compares borrowed_value against allowed_borrow_value and scales the whole deposited_value by that single ratio. That treats the obligation as if all collateral were interchangeable, and as if the only thing that mattered was the overall borrow-to-allowed ratio. It ignores the fact that different collateral reserves have different LTVs and different liquidation bonuses, and that withdrawing from one reserve changes the position's risk in a way the overall ratio does not capture.

The second half of the problem is how this interacts with liquidation. Liquidation repays debt and seizes collateral at a bonus. If the bonus on the collateral being seized is large enough relative to the debt being repaid, the collateral can be drained faster than the debt is cleared. The withdrawal check should have stopped the position from ever reaching that state, but because it only looked at the overall ratio, it did not.

Carrying out the exploit

Before the patch, a malicious user could withdraw all of their obligation collateral without paying off their full debt, under these assumptions:

  1. They find some reserve R1 with a high liquidation bonus_rate and some reserve R2 with a high LTV, such that the sum of reserve R1's bonus_rate and reserve R2's LTV is greater than 100%.
  2. They create an obligation and deposit some token T1 as collateral into reserve R1.
  3. They deposit some token T2 as collateral into reserve R2. The value of the T2 deposit should be greater than the value of the T1 deposit by several orders of magnitude, for example 3.
  4. They borrow token T2 from the reserve with the high LTV. The borrow value should be similar to the value of the T1 token deposit.
  5. They withdraw the entire T2 token deposit. This makes their obligation liquidatable, because the T2 borrow is now heavily undercollateralized.
  6. They liquidate their own obligation. Because the T2 borrow value is similar to the value of the T1 deposit and reserve R1 has a high bonus_rate, the obligation collateral is liquidated faster than the borrow is repaid, and the malicious user drains their T1 deposit before they pay off the borrow in full.

The report does not include the individual transactions, instructions or account addresses used for these steps. The mechanism is the sequence above: the oversized T2 deposit makes the overall withdrawal check permissive, the full T2 withdrawal leaves only the T1 collateral backing a T2 borrow, and self-liquidation then turns the T1 collateral into repayment at a bonus rate that outpaces the debt.

Root cause

The error is in Obligation::max_withdraw_value. It computes the withdrawable amount from the overall borrowed_value, deposited_value and allowed_borrow_value only. It never considers the LTV of the reserve whose collateral is being withdrawn, so a withdrawal from a high-LTV reserve is allowed based on a ratio that was inflated by deposits in other reserves. The check therefore lets a position end up in a state that the protocol's own liquidation settings make profitable to unwind: with a high enough bonus_rate on the remaining collateral, liquidation seizes collateral faster than it repays debt.

The problem was that becoming liquidatable was the attacker's goal, not a failure of the attack.

Impact

If exploited, the vulnerability would have let a malicious attacker steal $20 to $25 million. No user funds were lost because the bug was responsibly disclosed. Port Finance patched the bug and paid the whitehat $180,000 USD and $450,000 in PORT tokens linearly vested over a year, the maximum payout for Port Finance's bounty programme. The attack requires the two-reserve precondition above (a high bonus_rate reserve and a high LTV reserve whose parameters sum to more than 100%), and the report frames the outcome in terms of what could have happened rather than a realised loss.

The fix

The Obligation::max_withdraw_value function was fixed by introducing a withdraw_collateral_ltv parameter, which denotes the LTV of the reserve corresponding to the withdrawn collateral, and by calculating the maximum withdraw value as the ratio of the difference between the allowed borrow value and the borrowed value, and the reserve LTV.

From the original on medium.com

Variants to test

If you want to hunt for similar bugs, these are the patterns worth trying:

  • Overall-ratio withdrawal checks in other lending protocols. Look for any withdraw or redeem path that computes a limit from total deposited value, total borrowed value and total allowed borrow value without the LTV of the specific reserve. A positive result is a position where withdrawing one collateral asset leaves the remaining collateral liquidatable at a bonus that exceeds the outstanding debt.
  • Cross-collateral parameter combinations. List the reserves and check whether any pair has a liquidation bonus plus an LTV greater than 100%. A positive result is a pair where self-liquidation of a small position repays less than the collateral seized.
  • Self-liquidation paths. Check whether an obligation owner can liquidate their own obligation. If so, test whether the bonus on the seized collateral can exceed the value of the debt being repaid, which is the condition the report describes.
  • Withdrawing the largest collateral first. In protocols that allow several collateral types, try depositing a very large amount of a high-LTV asset and a small amount of a high-bonus asset, borrowing against the high-LTV asset, then withdrawing the large deposit in full. A positive result is the position becoming liquidatable while the small high-bonus collateral remains.
  • Liquidation close-factor limits. The report notes that a maximum of 50% of the total borrowed_value can be withdrawn in one go. Test whether repeated partial liquidations, or a single liquidation sized to the cap, can still drain collateral faster than debt when the bonus is high enough.
  • Parameter changes after position creation. Check whether a position created under one set of reserve parameters can be withdrawn after those parameters change, and whether the withdrawal check uses current or cached values.

Glossary

  • APY: annual percentage yield, the interest a deposit or loan earns or costs over a year, expressed as a percentage.
  • Blockchain: a shared record of transactions kept by many computers at once, so no single party controls it.
  • Bug bounty: a public offer by a company to pay people who privately report flaws in its software.
  • Collateral: assets you lock up as security for a loan; they can be taken if you do not repay.
  • Collateral ratio: how much collateral you hold compared with how much you owe.
  • COption: a Rust type meaning "either a value or nothing", used here for an optional public key.
  • Decimal: a number type that stores fractions precisely, used for money amounts.
  • DeFi: decentralised finance, financial services built on blockchains instead of banks.
  • Discount (in liquidation): a price below market at which a liquidator may buy seized collateral.
  • Function: a named block of code that performs a task and can be called by other code.
  • Liquidation: the process where a liquidator repays part of an unhealthy loan and receives the borrower's collateral at a discount.
  • Liquidation bonus: the extra percentage a liquidator receives on top of what they pay when seizing collateral.
  • Liquidation threshold: the LTV level at which a position becomes eligible for liquidation.
  • Liquidator: a person or program that repays an unhealthy loan in exchange for discounted collateral.
  • LTV (Loan To Value): the ratio of the value of a loan to the value of the collateral backing it.
  • Non-custodial: a service that never holds your assets itself; code moves them by rules.
  • Obligation: Port Finance's record of one user's deposits and borrows.
  • Overcollateralized: a loan where the collateral is worth more than the amount borrowed.
  • Parameter: a setting or input value that controls how something behaves.
  • ProgramError: a Rust error type returned when a program operation fails.
  • Pubkey: a public identifier, like an account number on a blockchain.
  • Reserve: Port Finance's name for a lending pool for one asset.
  • Result: a Rust type that holds either a successful value or an error.
  • Rust: the programming language Port Finance's smart contracts are written in.
  • Smart contract: code that runs on a blockchain and moves assets according to rules.
  • Solana: a blockchain known for fast, low-cost transactions.
  • Struct: a labelled bundle of values, like a form with named fields.
  • Token: a digital asset issued on a blockchain.
  • Transaction: a single recorded action on a blockchain.
  • u8: an unsigned whole number from 0 to 255.
  • Vec: a growable list in Rust.
  • Vesting: releasing tokens gradually over time instead of all at once.
  • Whitehat: a security researcher who finds flaws and reports them responsibly rather than abusing them.
  • Withdraw: taking your collateral back out of a lending pool.

Similar reports

View all

Same bug class and techniques, clearest first.

Business logic flaws

The lesson behind this report.

The application works as coded but not as intended: a negative price, a skipped payment step, a limit that can be crossed.