Security Audit
October 28, 2024
Version 1.0.0
Presented by 0xMacro
This document includes the results of the security audit for Kwenta's smart contract code as found in the section titled ‘Source Code’. The security audit was performed by the Macro security team intermittently from September 17th to October 14th, 2024.
The purpose of this audit is to review the source code of certain Kwenta Solidity contracts, and provide feedback on the design, architecture, and quality of the source code with an emphasis on validating the correctness and security of the software in its entirety.
Disclaimer: While Macro’s review is comprehensive and has surfaced some changes that should be made to the source code, this audit should not solely be relied upon for security, as no single audit is guaranteed to catch all possible bugs.
The following is an aggregation of issues found by the Macro Audit team:
Severity | Count | Acknowledged | Won't Do | Addressed |
---|---|---|---|---|
Critical | 2 | - | - | 2 |
Medium | 1 | - | - | 1 |
Kwenta was quick to respond to these issues.
Our understanding of the specification was based on the following sources:
The following source code was reviewed during the audit:
73ffbef6231961f544c25af5a8c50e3cf0b1fc07
Specifically, we audited the following contracts within this repository:
Source Code | SHA256 |
---|---|
src/Engine.sol |
|
src/interfaces/IEngine.sol |
|
src/utils/EIP7412.sol |
|
src/utils/MulticallablePayable.sol |
|
src/utils/MulticallerWithSender.sol |
|
src/utils/zap/Zap.sol |
|
Note: This document contains an audit solely of the Solidity contracts listed above. Specifically, the audit pertains only to the contracts themselves, and does not pertain to any other programs or scripts, including deployment scripts.
Click on an issue to jump to it, or scroll down to see them all.
We quantify issues in three parts:
This third part – the severity level – is a summary of how much consideration the client should give to fixing the issue. We assign severity according to the table of guidelines below:
Severity | Description |
---|---|
(C-x) Critical |
We recommend the client must fix the issue, no matter what, because not fixing would mean significant funds/assets WILL be lost. |
(H-x) High |
We recommend the client must address the issue, no matter what, because not fixing would be very bad, or some funds/assets will be lost, or the code’s behavior is against the provided spec. |
(M-x) Medium |
We recommend the client to seriously consider fixing the issue, as the implications of not fixing the issue are severe enough to impact the project significantly, albiet not in an existential manner. |
(L-x) Low |
The risk is small, unlikely, or may not relevant to the project in a meaningful way. Whether or not the project wants to develop a fix is up to the goals and needs of the project. |
(Q-x) Code Quality |
The issue identified does not pose any obvious risk, but fixing could improve overall code quality, on-chain composability, developer ergonomics, or even certain aspects of protocol design. |
(I-x) Informational |
Warnings and things to keep in mind when operating the protocol. No immediate action required. |
(G-x) Gas Optimizations |
The presented optimization suggestion would save an amount of gas significant enough, in our opinion, to be worth the development cost of implementing it. |
Credit is a balance of SUSD
that can be used to cover conditional order execution fees. Credit can be added to an accountId by calling either creditAccount()
or the new creditAccountZap()
function. These end of transferring SUSD
to the engine and credit the account id for that amount. If multiple accounts have credit, the engine’s SUSD
balance should be the sum of the total credit (unless tokens are directly sent in).
This credit is used when executing conditional orders in order to pay the executor, by debiting the fee from their set credit via _debit()
:
/// @dev impose a fee for executing the conditional order
/// @dev the fee is denoted in $sUSD and is
/// paid to the caller (conditional order executor)
/// @dev the fee does not exceed the max fee set by
/// the conditional order and
/// this is enforced by the `canExecute` function
if (_fee > 0) _debit(msg.sender, _co.orderDetails.accountId, _fee);
Reference: Engine.sol#L690-L696
If there was a way for credit
to be increased by more than what is deposited into the engine contract, then via this fee mechanism the SUSD
can be drained from the contract.
The new creditAccountZap()
function allows for this to happen, as the amount credited isn’t set to the amount transferred in, but rather sets it to the entire balance of SUSD
in the contract:
/// @inheritdoc IEngine
function creditAccountZap(
uint128 _accountId,
uint256 _amount,
IERC20 _collateral,
uint128 _marketId,
uint256 _tolerableWrapAmount,
uint256 _tolerableSwapAmount
) external payable override {
Zap.ZapData memory zapData = Zap.ZapData({
spotMarket: SPOT_MARKET_PROXY,
collateral: _collateral,
marketId: _marketId,
amount: _amount,
tolerance: Zap.Tolerance({
tolerableWrapAmount: _tolerableWrapAmount,
tolerableSwapAmount: _tolerableSwapAmount
}),
direction: Zap.Direction.In,
receiver: address(this),
referrer: address(0)
});
_collateral.transferFrom(msg.sender, address(this), _amount);
_collateral.approve(address(zap), _amount);
// zap $Collateral -> $sUSD
zap.zap(zapData);
//@audit: the susdAmount is set as the balance contained in the engine
// and set as the credit for the account, now sum of credit > balance
uint256 susdAmount = SUSD.balanceOf(address(this));
credit[_accountId] += susdAmount;
emit Credited(_accountId, susdAmount);
}
Reference: Engine.sol#L565-L599
This allows anyone that calls creditAccountZap()
to receive the entire SUSD balance as credit, then set this credit as a fee for a conditional order execution. This would then drain all USDC from the engine, losing users assets and disrupting conditional order execution.
Additionally, credit
can be stolen in the call to modifyCollateralZap()
due to a similar issue:
if (_direction == Zap.Direction.In) {
_collateral.transferFrom(msg.sender, address(this), _amount);
_collateral.approve(address(zap), _amount);
// zap $Collateral -> $sUSD
zap.zap(zapData);
//@audit: the susdAmount is set as the balance contained in the engine
// and is then added as collateral for the account id, which can then be stolen
// when collateral is removed
uint256 susdAmount = SUSD.balanceOf(address(this));
SUSD.approve(address(PERPS_MARKET_PROXY), susdAmount);
PERPS_MARKET_PROXY.modifyCollateral(
_accountId, USD_SYNTH_ID, susdAmount.toInt256()
);
}
Reference: Engine.sol#L367-L380
Here all SUSD held is added to the account’s collateral, which is then able to be withdrawn and stolen when collateral is removed.
Remediations to Consider
Either:
zap.zap()
return the amount received and use that as credit.zap.zap()
.This should also be resolved here.
Both unwindCollateral()
and unwindCollateralETH()
unwind a users Synthetix Perp position by using Zap
's unwind()
function. unwind()
uses an Aave flash loan to receive enough USDC which is used to cover the Perp account’s debt, then the collateral is withdrawn, and sold via swap for USDC to cover the loan, with the remaining collateral being sent to the set _receiver
.
However, there are no permission requirements to initiate this process via unwindCollateralETH()
or unwindCollateral()
, and the receiver of this accounts collateral is set to msg.sender
, or ETH is sent to msg.sender
in the case of unwindCollateralETH()
. This allows for anyone to unwind and take the collateral of any Perp account that has granted the Engine contract Admin permission, which any account using the Engine would have given.
An attacker an easily call unwindCollateral() on any account and steal all the accounts collateral minus debt.
Remediations to Consider
Add a check to ensure the caller is the account owner, or sufficiently permissioned user, for both unwindCollateral()
and unwindCollateralETH()
similar to what is done when withdrawing collateral from an account.
This ensures that only authorized users can unwind a position and up up with an accounts collateral.
Zap.sol
allows to either sell a token for SUSD
or by a token with SUSD
via SynthetixV3
’s associated spot markets. It does this by either wrapping or unwrapping the token with its synthetic version that the Synthetix spot market interacts with.
In the case of _zapOut(), SUSD
is used to buy the synthetic version of the desired token out, which is defined by the marketId
value, which is then unwrapped, exchanging the purchased synth for its associated collateral token, which then is assumed that the provided collateral
param is the token received. However, there is no check to ensure that the collateral
is associated with the synth marketId
which could lead to issues when they are not related.
In the case where a user intends to receive a valuable token like WETH
, but accidentally sets the collateral
value to something like SUSD
, then WETH
will be sent into the contract but it will attempt to send an amount of SUSD
out, which is valued much less. Typically this transaction would fail since Zap
wouldn’t have a balance of SUSD
, but if someone were to front-run this transaction, sending enough SUSD
into Zap
, then the transaction would execute. Then the WETH
now in the Zap
contract could be taken in a similar method by using a less valuable syth’s market id, and setting the collateral
to be WETH
, curating the parameters so the amount swapped equals the WETH
held.
Remediations to Consider
Validate that the provided collateral
is used by the spot market id by calling getWrapper() to ensure the tokens received are as expected.
Macro makes no warranties, either express, implied, statutory, or otherwise, with respect to the services or deliverables provided in this report, and Macro specifically disclaims all implied warranties of merchantability, fitness for a particular purpose, noninfringement and those arising from a course of dealing, usage or trade with respect thereto, and all such warranties are hereby excluded to the fullest extent permitted by law.
Macro will not be liable for any lost profits, business, contracts, revenue, goodwill, production, anticipated savings, loss of data, or costs of procurement of substitute goods or services or for any claim or demand by any other party. In no event will Macro be liable for consequential, incidental, special, indirect, or exemplary damages arising out of this agreement or any work statement, however caused and (to the fullest extent permitted by law) under any theory of liability (including negligence), even if Macro has been advised of the possibility of such damages.
The scope of this report and review is limited to a review of only the code presented by the Kwenta team and only the source code Macro notes as being within the scope of Macro’s review within this report. This report does not include an audit of the deployment scripts used to deploy the Solidity contracts in the repository corresponding to this audit. Specifically, for the avoidance of doubt, this report does not constitute investment advice, is not intended to be relied upon as investment advice, is not an endorsement of this project or team, and it is not a guarantee as to the absolute security of the project. In this report you may through hypertext or other computer links, gain access to websites operated by persons other than Macro. Such hyperlinks are provided for your reference and convenience only, and are the exclusive responsibility of such websites’ owners. You agree that Macro is not responsible for the content or operation of such websites, and that Macro shall have no liability to your or any other person or entity for the use of third party websites. Macro assumes no responsibility for the use of third party software and shall have no liability whatsoever to any person or entity for the accuracy or completeness of any outcome generated by such software.