MarginTrading.sol: Missing flash loan initiator check allows attacker to open trades, close trades and steal funds
The `MarginTrading.executeOperation` function is called when a flash loan is made (and it can only be called by the lendingPool).\\nThe wrong assumption by the protocol is that the flash loan can only be initiated by the `MarginTrading` contract itself.\\nHowever this is not true. A flash loan can be initiated for any `receiverAddress`.\\n\\nSo an attacker can execute a flash loan with the `MarginTrading` contract as `receiverAddress`. Also the funds that are needed to pay back the flash loan are pulled from the `receiverAddress` and NOT from the initiator:\\nThis means the attacker can close a position or repay a position in the `MarginTrading` contract.\\nBy crafting a malicious swap, the attacker can even steal funds.\\nLet's assume there is an ongoing trade in a `MarginTrading` contract:\\n```\\ndaiAToken balance = 30000\\nwethDebtToken balance = 10\\n\\nThe price of WETH when the trade was opened was ~ 3000 DAI\\n```\\n\\nIn order to profit from this the attacker does the following (not considering fees for simplicity):\\nTake a flash loan of 30000 DAI with `MarginTrading` as `receiverAddress` with `mode=0` (flash loan is paid back in the same transaction)\\nPrice of WETH has dropped to 2000 DAI. The attacker uses a malicious swap contract that pockets 10000 DAI for the attacker and swaps the remaining 20000 DAI to 10 WETH (the attacker can freely choose the swap contract in the `_params` of the flash loan).\\nThe 10 WETH debt is repaid\\nWithdraw 30000 DAI from Aave to pay back the flash loan
The fix is straightforward:\\n```\\ndiff --git a/dodo-margin-trading-contracts/contracts/marginTrading/MarginTrading.sol b/dodo-margin-trading-contracts/contracts/marginTrading/MarginTrading.sol\\nindex f68c1f3..5b4b485 100644\\n--- a/dodo-margin-trading-contracts/contracts/marginTrading/MarginTrading.sol\\n// Add the line below\\n// Add the line below\\n// Add the line below\\n b/dodo-margin-trading-contracts/contracts/marginTrading/MarginTrading.sol\\n@@ -125,6 // Add the line below\\n125,7 @@ contract MarginTrading is OwnableUpgradeable, IMarginTrading, IFlashLoanReceiver\\n         address _initiator,\\n         bytes calldata _params\\n     ) external override onlyLendingPool returns (bool) {\\n// Add the line below\\n        require(_initiator == address(this));\\n         //decode params exe swap and deposit\\n         {\\n```\\n\\nThis ensures that the flash loan has been initiated by the `MarginTrading.executeFlashLoans` function which is the intended initiator.
The attacker can close trades, partially close trades and even steal funds.\\n(Note: It's not possible for the attacker to open trades because he cannot incur debt on behalf of the `MarginTrading` contract)
```\\ndaiAToken balance = 30000\\nwethDebtToken balance = 10\\n\\nThe price of WETH when the trade was opened was ~ 3000 DAI\\n```\\n