Incorrect implementation of `BPF` leads to kicker losing rewards in a `take` action
The bond payment factor calculation in the Ajna protocol's take function incorrectly sets the sign to zero when the threshold price is greater than or equal to the neutral price and the auction price equals the neutral price, resulting in a bond payment factor of zero instead of the bond factor. This causes the kicker to lose rewards and the borrower to face higher penalties.
Source: https://github.com/sherlock-audit/2023-09-ajna-judging/issues/18
Found by
santipu_
When a take action takes place, if ThresholdPrice >= NeutralPrice and PriceTake = NeutralPrice, the Bond Payment Factor (BPF) should be bondFactor but it will be 0, causing the loss of rewards of the kicker in that action.
Vulnerability Detail
The Bond Payment Factor (BPF) is the formula that determines the reward/penalty over the bond of a kicker in each take action. According to the whitepaper, the formula is described as:
// If TP < NP
BPF = bondFactor * min(1, max(-1, (NP - price) / (NP - TP)))
// If TP >= NP
BPF = bondFactor (if price <= NP)
BPF = -bondFactor (if price > NP)
The implementation of this formula is the following: https://github.com/sherlock-audit/2023-09-ajna/blob/main/ajna-core/src/libraries/helpers/PoolHelper.sol#L382-L411
function _bpf(
uint256 debt_,
uint256 collateral_,
uint256 neutralPrice_,
uint256 bondFactor_,
uint256 auctionPrice_
) pure returns (int256) {
int256 thresholdPrice = int256(Maths.wdiv(debt_, collateral_));
int256 sign;
if (thresholdPrice < int256(neutralPrice_)) {
// BPF = BondFactor * min(1, max(-1, (neutralPrice - price) / (neutralPrice - thresholdPrice)))
sign = Maths.minInt(
1e18,
Maths.maxInt(
-1 * 1e18,
PRBMathSD59x18.div(
int256(neutralPrice_) - int256(auctionPrice_),
int256(neutralPrice_) - thresholdPrice
)
)
);
} else {
int256 val = int256(neutralPrice_) - int256(auctionPrice_);
if (val < 0 ) sign = -1e18;
else if (val != 0) sign = 1e18; // @audit Sign will be zero when NP = auctionPrice
}
return PRBMathSD59x18.mul(int256(bondFactor_), sign);
}
The issue is that the implementation of the BPF formula in the code doesn't match the specification, leading to the loss of rewards in that take action in cases where TP >= NP and price = NP.
As showed in the above snippet, in cases where TP >= NP and NP = price (thus val = 0) the function won't set a value for sign (will be 0 by default) so that will result in a computed BPF of 0, instead of bondFactor that would be the correct BPF.
Impact
The kicker will lose the rewards in that take action if the previous conditions are satisfied.
While the probability of this conditions to be met is not usual, the impact is the loss of rewards for that kicker and that may cause to lose part of the bond if later a take is performed with a negative BPF.
Code Snippet
Tool used
Manual Review
Recommendation
Change the _bpf function to match the specification in order to fairly distribute the rewards in a take action:
function _bpf(
uint256 debt_,
uint256 collateral_,
uint256 neutralPrice_,
uint256 bondFactor_,
uint256 auctionPrice_
) pure returns (int256) {
int256 thresholdPrice = int256(Maths.wdiv(debt_, collateral_));
int256 sign;
if (thresholdPrice < int256(neutralPrice_)) {
// BPF = BondFactor * min(1, max(-1, (neutralPrice - price) / (neutralPrice - thresholdPrice)))
sign = Maths.minInt(
1e18,
Maths.maxInt(
-1 * 1e18,
PRBMathSD59x18.div(
int256(neutralPrice_) - int256(auctionPrice_),
int256(neutralPrice_) - thresholdPrice
)
)
);
} else {
int256 val = int256(neutralPrice_) - int256(auctionPrice_);
if (val < 0 ) sign = -1e18;
- else if (val != 0) sign = 1e18;
+ else sign = 1e18;
}
return PRBMathSD59x18.mul(int256(bondFactor_), sign);
}
Discussion
sherlock-admin2
1 comment(s) were left on this issue during the judging contest.
n33k commented:
"consistent with the whitepaper, sign could be 0"
santipu03
Escalate
This issue has been erroneously excluded and should be high severity because the _bpf function DOES NOT adhere to the specification and it causes the loss of rewards for a kicker. This was confirmed by the sponsors during the contest.
As a summary, the whitepaper states the following:
If 𝑇𝑃 ≥ 𝑁𝑃, then the second factor in this equation is replaced with the step function that returns +1 if the take price is less than or equal to the NP, and -1 otherwise: 𝐵𝑃𝐹 = 𝐵𝑜𝑛𝑑𝐹𝑎𝑐𝑡𝑜𝑟 if 𝑃𝑟𝑖𝑐𝑒𝑡𝑎𝑘𝑒 ≤ 𝑁𝑃 𝐵𝑃𝐹 = − 𝐵𝑜𝑛𝑑𝐹𝑎𝑐𝑡𝑜𝑟 if 𝑃𝑟𝑖𝑐𝑒𝑡𝑎𝑘𝑒 > 𝑁𝑃
Therefore, following the specification, in cases when TP ≥ NP and PriceTake = NP, then the correct BPF should be: BPF = BondFactor.
But in these cases, the implementation erroneously sets BPF = 0. The impact will be that the kicker will lose all the rewards on that take action because BPF is set to 0 instead of BondFactor.
If the auction is completed in one take, the kicker will lose all the rewards from that auction that should belong to him. If the auction is settled later in time after this action, then the auctionPrice (priceTake) will be lower than NP so the kicker will lose part of the bond because of this issue (because the lost rewards would cancel out the later losses).
sherlock-admin2
Escalate
This issue has been erroneously excluded and should be high severity because the
_bpffunction DOES NOT adhere to the specification and it causes the loss of rewards for a kicker. This was confirmed by the sponsors during the contest.As a summary, the whitepaper states the following:
If 𝑇𝑃 ≥ 𝑁𝑃, then the second factor in this equation is replaced with the step function that returns +1 if the take price is less than or equal to the NP, and -1 otherwise: 𝐵𝑃𝐹 = 𝐵𝑜𝑛𝑑𝐹𝑎𝑐𝑡𝑜𝑟 if 𝑃𝑟𝑖𝑐𝑒𝑡𝑎𝑘𝑒 ≤ 𝑁𝑃 𝐵𝑃𝐹 = − 𝐵𝑜𝑛𝑑𝐹𝑎𝑐𝑡𝑜𝑟 if 𝑃𝑟𝑖𝑐𝑒𝑡𝑎𝑘𝑒 > 𝑁𝑃
Therefore, following the specification, in cases when
TP ≥ NPandPriceTake = NP, then the correct BPF should be:BPF = BondFactor. But in these cases, the implementation erroneously setsBPF = 0. The impact will be that the kicker will lose all the rewards on thattakeaction becauseBPFis set to0instead ofBondFactor.If the auction is completed in one take, the kicker will lose all the rewards from that auction that should belong to him. If the auction is settled later in time after this action, then the
auctionPrice(priceTake) will be lower thanNPso the kicker will lose part of the bond because of this issue (because the lost rewards would cancel out the later losses).
You've created a valid escalation!
To remove the escalation from consideration: Delete your comment.
You may delete or edit your escalation comment anytime before the 48-hour escalation window closes. After that, the escalation becomes final.
neeksec
This is a valid one.
I suggest to set severity to Medium because the probability of meeting the condition NP=TP is pretty low.
kadenzipfel
This should be low severity as it's a slight inconsistency from the specification which has an extremely low chance of occurring considering the fact that two independently varying 18 decimal numbers are extremely unlikely to collide.
Furthermore, there's no loss of funds as one wei in each direction would be a gain or a loss in bond reward or penalty respectively. There's no flaw in the design of making the reward 0 in this circumstance as it would be just as reasonable for the protocol to deem NP == price as a penalized circumstance as it is to make it rewarded or neutral.
santipu03
It's correct that it's highly unlikely for this scenario to happen, but in case it occurs, the impact is high because is causing the kicker to lose all the rewards in that take action.
This issue doesn't argue wether the design is flawed or not, it simply points out a scenario where the kicker should be winning a reward over the bond but actually doesn't because of an error on the code.
kadenzipfel
Given the level of precision, 1/1,000,000,000 is probably an optimistic likelihood of this occurring. We can reasonably write off the impact of it actually happening with these odds.
See judging docs for medium severity: "The attack path is possible with assumptions that either mimic on-chain conditions or reflect conditions that have a reasonable chance of becoming true in the future."
Evert0x
If the 1/1,000,000,000 odds are optimistic, I plan to reject escalation and keep issues state as is.
@santipu03 please follow up with a comment if you see a more realistic scenario or attack path where NP will be equal to TP
Czar102
@santipu03 is there any reason why could NP = TP with a larger probability? Could this be manipulated easily? What happens with the kicker's reward, is it locked forever or is it owned by anyone?
santipu03
I want to emphasize that this issue has significant implications not only for the kicker but also for the borrower. Specifically, the borrower faces the risk of receiving less repayment from the taker than deserved. This situation arises if the Bond Payment Factor (BPF) is erroneously set to 0 (like in this case), which in turn increases the Take Penalty Factor (TPF). Consequently, the taker repays a lesser portion of the borrower's debt for the same token amount in the take action. Then, the tokens intended for the kicker and borrower will be mistakenly redirected to reserves.
The severity of this issue is undeniably high, though is difficult to predict its likelihood.
Ajna's goal is to operate as an immutable, trustless protocol. Over time, it's probable that this issue will eventually manifest, leading to significant disruptions, such as kickers losing rewards and borrowers facing undue penalties.
The issue has been confirmed by the sponsors via DMs, and they are likely to have already addressed it. However, given the uncertainty surrounding its probability, I'll leave the judges with the final decision and will respect that.
Czar102
@santipu03 please provide information if it is possible to influence the result of NP = TP. If those values are like random numbers of order 1e18 then I will classify this as a Medium. Otherwise please explain in detail how could the attacker change the values of any/both of these variables so that they could collide in a real-life scenario.
santipu03
To recap, this issue arises because when TP >= NP and NP = auctionPrice. In such cases, the kicker should receive full rewards (bondFactor) as per the specification, but due to a bug, the kicker will earn nothing. Additionally, this bug results in increased penalties for the borrower.
The scenario of TP >= NP is likely, but NP equalling auctionPrice is less probable. However, it's still possible and can be exploited by an attacker.
NP (Neutral Price) is fixed at the time a borrower is kicked and remains unchanged throughout the auction. In contrast, auctionPrice starts at referencePrice and decreases over time. An attacker can manipulate this by calling take shortly before it should be due to market conditions, to keep the auctionPrice high, or by delaying it, allowing the auctionPrice to lower. This way an attacker can game the value of auctionPrice griefing the kicker and borrower.
Czar102
@neeksec would you agree with the above statement that the attacker can manipulate the auctionPrice by carefully using take? Or is it more difficult?
neeksec
I agree that the taker can control auctionPrice to some extent. But making auctionPrice equal to NP is still very difficult.
_auctionPrice involves complex computations, and the taker can only control the block.timestamp within it by delaying the call to take. The final result returned is difficult to be manipluted to be equal to NP with this limited control over block.timestamp.
Czar102
I don't know the codebase, but I would think that for certain situations (like very low price), the probability of a collision is larger. If the two parameters that need to equal can be manipulated by changing a timestamp parameter, this allows the attacker for only 1e3 - 1e4 additional "trials", which doesn't change the probability to any reasonable level (hence it's of the order of 1e-14 now). @santipu03 are you sure you can't come up for any reasons to increase the probability? PoC or an extremely detailed explanation appreciated.
This issue surely won't be of high severity, but it still has an opportunity to qualify for medium.
santipu03
I've just realised we've been missing a critical factor in this issue.
To clarify, the _auctionPrice function is designed so that 18 hours after kickTime (equivalent to 64,800 seconds), it will return a value equal to referencePrice. The calculation of referencePrice is determined as the maximum of NP and HTP, and typically NP is higher than HTP. This means that once 18 hours have elapsed in the auction, the auctionPrice will align exactly with the value of NP.
I found out this by playing with a variation of the _auctionPrice function:
function _auctionPrice(
uint256 referencePrice_,
- uint256 kickTime_
+ uint256 secondsElapsed
) view returns (uint256 price_) {
- uint256 elapsedMinutes = Maths.wdiv((block.timestamp - kickTime_) * 1e18, 1 minutes * 1e18);
+ uint256 elapsedMinutes = Maths.wdiv(secondsElapsed * 1e18, 1 minutes * 1e18);
// ...
}
If we paste this variation of _auctionPrice into chisel it reveals that when secondsElapsed = 64800, the value returned is referencePrice / 256, which is essentially the same as NP:
➜ _auctionPrice(256e18, 64800) == 1e18
Type: bool
└ Value: true
What this implies is that the likelihood of NP matching auctionPrice is not as low as previously thought. Specifically, at the exact 18-hour mark since the auction started, NP will equal auctionPrice. This collision will trigger the impact we discussed earlier. Given that Ethereum blocks are generated approximately every 12 seconds, it means that for every auction reaching 18 hours (most of them), there's about a 1 in 12 chance that NP will coincide with auctionPrice, posing a significant risk.
Czar102
@neeksec can you confirm?
neeksec
@Czar102 After reviewing the relevant code along with Section 7.2 'Liquidation Call' of the whitepaper, I can confirm that @santipu03 is correct in his https://github.com/sherlock-audit/2023-09-ajna-judging/issues/18#issuecomment-1821310337.
The auctionPrice_ will intersect with neutralPrice_ at a predetermined time, within the 72 hour auction. This issue is highly likely to occur.
kadenzipfel
In the case that NP > HTP and referencePrice = NP, it is true that the auctionPrice == referencePrice, and thus the BPF will unexpectedly be 0. Furthermore, the likelihood is even higher than suggested here where the block time doesn't have to be perfectly timed, it just has to be within the two hour window before the next halving. The likelihood is thus reasonably high to constitute a valid issue on the basis of likelihood.
To be clear though, this should certainly not be classified as a high severity as initially suggested in the escalation, and arguably not even a medium, for the following reason:
- If the auctionPrice > NP, the kicker earns a fee and the taker pays a fee.
- If the auctionPrice < NP, the taker earns a fee and the kicker pays a fee.
- Thus, it would be a reasonable design decision to make it such that if the auctionPrice == NP, that no one pays a fee.
Note the criteria for medium and high severity vulnerabilities: "The vulnerability must be something that is not considered an acceptable risk by a reasonable protocol team." This being said, perhaps the deviation of the implementation from the specification warrants it being a medium risk finding regardless.
Edit: To be extra clear, there is no attack vector here. The vulnerability is simply that the kicker/taker will not receive/pay the amount of fees that they expect according to the white paper. There is no way to exploit it for profit.
neeksec
I think @kadenzipfel is right, there is no attack vector here.
Thus, it would be a reasonable design decision to make it such that if the auctionPrice == NP, that no one pays a fee.
There is no deviation of the implementation from the specification. This behavior is described in Section 7.3 Liquidation Bonds of the whitepaper. The graph in that section clearly shows that when auction price equals NP, the profit/loss to kicker should be zero.
Czar102
@santipu03 would you agree with the above?
santipu03
There is no deviation of the implementation from the specification. This behavior is described in Section 7.3 Liquidation Bonds of the whitepaper. The graph in that section clearly shows that when auction price equals NP, the profit/loss to kicker should be zero.
It's critical to understand that BPF is not determined by only one formula. The graph from above represents the BPF curve in case TP < NP, but my report is highlighting an inconsistency in the implementation in the cases where TP >= NP. The formulas used to calculate the BPF in both cases are not the same, refer to section 7.3.3 Determining the Reward or Penalty on the whitepaper for clarification.
Thus, it would be a reasonable design decision to make it such that if the auctionPrice == NP, that no one pays a fee.
As @Czar102 remarked on other issues, considerations about design choices are out of scope. The specification explicitly states that when TP >= NP and NP = auctionPrice then BPF must be bondFactor, instead the implementation makes BPF = 0 in those cases.
This discrepancy leads to significant consequences: kickers lose rewards and borrowers lose assets, as TPF (Take Penalty Factor) is higher than it should be. Furthermore, this creates an attack vector: with an inflated TPF, takers are incentivized to exploit the situation, paying less for borrower collateral when auctionPrice = NP, as well as griefing the kicker.
neeksec
I agree that the graph is for case TP < NP and is not relevant to this issue.
The specification explicitly states that when TP >= NP and NP = auctionPrice then BPF must be bondFactor
@santipu03 Can you show where this is stated?
santipu03
As outlined in my previous message, section 7.3.3 Determining the Reward or Penalty:
dmitriia
By definition of NP, which is neutral price level, when AP == NP the reward have to be zero.
I don't like drastic swings the formula produces when TP is at or above NP either, but this is a corner case state, achievable on the series of subsequent takes only as initially NP to TP ratio NP defined with is above 1.
This corner case should ideally go away when TP becomes snapshotted.
Czar102
It seems that the issue is the difference between the implementation and the documentation. The loss of funds @santipu03 refers to is the loss of funds that happens when parties have an expectation for the contract to behave as described in the documentation. If the documentation was different (stating that BPF == 0 for auctionPrice == NP), there wouldn't be an issue.
Is that right? @dmitriia @santipu03
dmitriia
Yes, as per base NP definition from 7.3 of 10-12-2023 whitepaper
the NP is the price at which a kicker will have their bond returned to them without penalty or reward (thus being considered a neutral outcome from the kicker's perspective)
any deviations from that are issues by themselves, and in this case it looks like it's the documentation one, where it needs to be corrected.
santipu03
During the contest, I encountered this issue and immediately reached out to the sponsors to clarify whether it was a discrepancy in the documentation or an actual flaw in the implementation. The response I received was this:
It's important to note that the determination of whether an issue is a documentation mistake or an implementation flaw rests with the development team, not the auditors. Considering the high likelihood and potential for fund loss, I believe this issue deserves a medium/high severity rating.
In comparison, when I reported issue #19, it was classified as informational since it was merely a documentation error. However, this current issue clearly stems from an implementation mistake as per the sponsor's comment, setting it apart from the previous one.
Czar102
I wanted to decide whether it should be medium or high. If the contracts work properly for both options, but the implementation is different than the documentation and the expectation of a different behavior can implicitly make users lose funds, the issue will be considered medium severity.
Czar102
Result: Medium Unique
sherlock-admin2
Escalations have been resolved successfully!
Escalation status:
- santipu03: accepted
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
Likely, the conditional logic in the _bpf function fails to set the sign variable when the neutral price equals the auction price and the threshold price is greater than or equal to the neutral price, defaulting to zero.
Impact
The kicker could lose rewards in that take action, and the borrower may receive less repayment because the take penalty factor increases, but the text notes the probability of the exact price equality is low, though it can occur at a specific time in the auction.
What the attacker needed
Auction reaches 18-hour mark; TP >= NP; auctionPrice equals NP
The fix
The _bpf function should be changed to set the sign to 1e18 when the neutral price equals the auction price, matching the specification.
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.
In a liquidation auction, a 'kicker' starts the auction and posts a bond. When someone 'takes' the collateral, the kicker may get a reward or penalty based on a formula. The code had a mistake: in a specific case where two prices were equal, the reward was set to zero instead of the full reward, so the kicker lost out.
What is Business logic?
The application works as coded but not as intended: a negative price, a skipped payment step, a limit that can be crossed.