Prepared by:
HALBORN
Last Updated 05/07/2024
Date of Engagement by: February 16th, 2024 - February 28th, 2024
100% of all REPORTED Findings have been addressed
All findings
7
Critical
1
High
2
Medium
0
Low
0
Informational
4
A security assessment on smart contracts was performed on the scoped smart contracts provided to the Halborn team.
The team at Halborn was provided three weeks for the engagement and assigned a full-time security engineer to verify the security of the smart contract. The security engineer is a blockchain and smart-contract security expert with advanced penetration testing, smart-contract hacking, and deep knowledge of multiple blockchain protocols.
The purpose of this assessment is to:
Ensure that smart contract functions operate as intended
Identify potential security issues with the smart contracts
In summary, Halborn identified some security risks that were mostly addressed.
Halborn performed a combination of manual and automated security testing to balance efficiency, timeliness, practicality, and accuracy in regard to the scope of this assessment. While manual testing is recommended to uncover flaws in logic, process, and implementation; automated testing techniques help enhance coverage of the code and can quickly identify items that do not follow the security best practices. The following phases and associated tools were used during the assessment:
Research into architecture and purpose.
Smart contract manual code review and walkthrough.
Graphing out functionality and contract logic/connectivity/functions (solgraph).
Manual assessment of use and safety for the critical Solidity variables and functions in scope to identify any arithmetic related vulnerability classes.
Manual testing by custom scripts.
Testnet deployment (Foundry).
Repository URL : https://github.com/plural-energy/plural-protocol
Commit ID : 2b24130e5efd5fc3513f35b757e92994a6383f82
In-scope contracts :
src/Offering.sol
src/OfferingPrivate.sol
src/AssetTokenVendor.sol
EXPLOITABILIY METRIC () | METRIC VALUE | NUMERICAL VALUE |
---|---|---|
Attack Origin (AO) | Arbitrary (AO:A) Specific (AO:S) | 1 0.2 |
Attack Cost (AC) | Low (AC:L) Medium (AC:M) High (AC:H) | 1 0.67 0.33 |
Attack Complexity (AX) | Low (AX:L) Medium (AX:M) High (AX:H) | 1 0.67 0.33 |
IMPACT METRIC () | METRIC VALUE | NUMERICAL VALUE |
---|---|---|
Confidentiality (C) | None (I:N) Low (I:L) Medium (I:M) High (I:H) Critical (I:C) | 0 0.25 0.5 0.75 1 |
Integrity (I) | None (I:N) Low (I:L) Medium (I:M) High (I:H) Critical (I:C) | 0 0.25 0.5 0.75 1 |
Availability (A) | None (A:N) Low (A:L) Medium (A:M) High (A:H) Critical (A:C) | 0 0.25 0.5 0.75 1 |
Deposit (D) | None (D:N) Low (D:L) Medium (D:M) High (D:H) Critical (D:C) | 0 0.25 0.5 0.75 1 |
Yield (Y) | None (Y:N) Low (Y:L) Medium (Y:M) High (Y:H) Critical (Y:C) | 0 0.25 0.5 0.75 1 |
SEVERITY COEFFICIENT () | COEFFICIENT VALUE | NUMERICAL VALUE |
---|---|---|
Reversibility () | None (R:N) Partial (R:P) Full (R:F) | 1 0.5 0.25 |
Scope () | Changed (S:C) Unchanged (S:U) | 1.25 1 |
Severity | Score Value Range |
---|---|
Critical | 9 - 10 |
High | 7 - 8.9 |
Medium | 4.5 - 6.9 |
Low | 2 - 4.4 |
Informational | 0 - 1.9 |
Critical
1
High
2
Medium
0
Low
0
Informational
4
Security analysis | Risk level | Remediation Date |
---|---|---|
Unauthorized Transfer of Remaining Issuer Asset Tokens | Critical | Solved - 02/23/2024 |
Any user could extend the offering purchase time | High | Solved - 05/06/2024 |
orderId is not properly validated | High | Solved - 02/20/2024 |
Incompatibility with Fee-On-Transfer & Rebase Tokens | Informational | Solved - 05/06/2024 |
Usage of block.timestamp | Informational | Acknowledged |
Missing offering address zero checks on the approval | Informational | Solved - 05/06/2024 |
Checked increments in for loops increases gas consumption | Informational | Acknowledged |
// Critical
It was found a critical issue on the offering.sol code. The returnRemainderToIssuer
onlyOwner
access control modifier is missing. A malicious actor could call that function to get the 40% of remainder issued supply asset tokens. When such a function is called with the issuerAddress
parameter as the attacker ones, the _transferToIssuer
function will do a safeTransferFrom
from tokenTreasury
to the attacker address. As you can see, the 40% of asset tokens were transferred to the attacker. Since the 40% of issued asset tokens are transferred to the attacker, it cannot be possible to perform any purchase by the buyers due to no asset tokens are available with the revert “Remaining tokens for sale is less than amount remaining”.
/// @inheritdoc IOffering
function returnRemainderToIssuer(address issuerAddress) public {
_transferToIssuer(issuerAddress, numTokensForSale - numTokensSold);
}
Before any purchases and after the admin setupInitialIssuance
call, the attacker could call the public returnRemainderToIssuer
function using as issuerAddress
the malicious address.
Exploit:
function purchase(bytes16 buyerStakeholderId) public returns (uint) {
vm.assume(buyerStakeholderId != bytes16(0));
vm.assume(buyerStakeholderId != issuerStakeholderId);
vm.assume(buyerStakeholderId != offeringStakeholderId);
// Setup the initial issuance of the offering
vm.startPrank(_admin);
_offering.setupInitialIssuance(_issuedSupply, _issuer, _issuerAmount);
vm.stopPrank();
//attacker wanted to get the remainder 40% for free of the _issuedSupply.
vm.startPrank(_attacker);
_offering.returnRemainderToIssuer(_attacker);
console2.log(IERC20(_token).balanceOf(_attacker)); // 40% of the _token
vm.stopPrank();
// buyer purchases
uint64 tokensToPurchase1 = 25;
uint64 tokensToPurchase2 = 25;
uint64 tokensToPurchase3 = 50;
uint64 tokensToPurchase = 100;
uint tokensToPurchaseWithDecimals = tokensToPurchase *
(10 ** IERC20(_token).decimals());
uint pricePerToken = 10e6; // $1
uint paymentAmount = tokensToPurchase * pricePerToken;
string memory orderId = "123";
// Issuer approves Vendor contract to transfer tokens
setupPurchaser(_buyer, buyerStakeholderId);
// Buyer approves Vendor contract to purchase tokens with usdc
// Vendor contract == _offering.
vm.startPrank(_buyer);
_usdc.approve(address(_offering), paymentAmount);
assertEq(IERC20(_token).balanceOf(address(_offering)), 0);
//will be reverted, due to no asset tokens on the treasury.
_offering.purchase(_buyer, tokensToPurchase1, orderId);
vm.stopPrank();
return tokensToPurchaseWithDecimals;
}
Ensure the use of onlyOwner
modifier on that function.
SOLVED: The Plural Energy team solved the issue by adding onlyOwner
modifier.
function returnRemainderToIssuer() public onlyOwner {
_transferToIssuer(issuer, numTokensForSale - numTokensSold);
}
// High
Any user could call the extendTime
of the offering created by the admin. There was a lack of onlyOwner
modifier in the extendTime
public function. Ensure that administration mechanism as extend the offering timestamp when purchasing should no controlled by malicious actors.
The following test showed how the attacker could extend the time on a particular offer created by the admin.
Exploit:
function purchase(bytes16 buyerStakeholderId) public returns (uint) {
vm.assume(buyerStakeholderId != bytes16(0));
vm.assume(buyerStakeholderId != issuerStakeholderId);
vm.assume(buyerStakeholderId != offeringStakeholderId);
// Setup the initial issuance of the offering
vm.startPrank(_admin);
_offering.setupInitialIssuance(_issuedSupply, _issuer, _issuerAmount);
vm.stopPrank();
// buyer purchases
uint64 tokensToPurchase1 = 25;
uint64 tokensToPurchase2 = 25;
uint64 tokensToPurchase3 = 50;
uint64 tokensToPurchase = 100;
uint tokensToPurchaseWithDecimals = tokensToPurchase *
(10 ** IERC20(_token).decimals());
uint pricePerToken = 10e6; // $1
uint paymentAmount = tokensToPurchase * pricePerToken;
string memory orderId = "123";
// Issuer approves Vendor contract to transfer tokens
setupPurchaser(_buyer, buyerStakeholderId);
// Buyer approves Vendor contract to purchase tokens with usdc
// Vendor contract == _offering.
vm.startPrank(_buyer);
_usdc.approve(address(_offering), paymentAmount);
assertEq(IERC20(_token).balanceOf(address(_offering)), 0);
_offering.purchase(_buyer, tokensToPurchase1, orderId);
_offering.purchase(_buyer, tokensToPurchase2, orderId);
_offering.extendTime(1672531311); //changing the time as attacker.
_offering.isOpen();
console2.log(_offering.closingTime()); //check that the attacker extend the time.
_offering.purchase(_buyer, tokensToPurchase3, orderId);
vm.stopPrank();
return tokensToPurchaseWithDecimals;
}
Ensure the use of onlyOwner
modifier on that function.
SOLVED: The Plural Energy team solved the issue by adding onlyOwner
modifier.
function extendTime(uint40 newClosingTime) public override onlyOwner {
require(isOpen(), "Offering already closed");
// solhint-disable-next-line max-line-length
require(
newClosingTime > closingTime,
"TimedCrowdsale: new closing time is before current closing time"
);
closingTime = newClosingTime;
}
// High
The orderId
is not properly validated on the Token purchase if it already exists in previous purchases by the buyers. Basically, the orderId
is not validated on the purchase function. This issue arises in the emit event that the orderId
is not checked if already purchases exists or not before. Moreover, the buyer user could purchase using the same orderId
parameter twice. If the emit event is used in an off chain application could be a critical issue that the same orderId
could be treated as the same from different buyers.
After confirmation with the client, the issue is valid because currently the event would be used directly. Basically, the order ID maps to the id of an order record in their database. Through the purchase event containing the order id, they can link the on chain transaction to the order in their systems and confirm that the asset tokens were transferred from treasury to purchaser and payment tokens from purchaser to the payment router. This is important from a regulatory standpoint as they can use this to prove that the transfer of assets happened (settlement, in the process of execution, clearing, and settlement of a security transaction).
The following test showed how a buyer could use the same orderId in each purchase. That event would be use on the offchain component and several same orderId existing could allow errors on the database queries.
Exploit:
function purchase(bytes16 buyerStakeholderId) public returns (uint) {
vm.assume(buyerStakeholderId != bytes16(0));
vm.assume(buyerStakeholderId != issuerStakeholderId);
vm.assume(buyerStakeholderId != offeringStakeholderId);
// Setup the initial issuance of the offering
vm.startPrank(_admin);
_offering.setupInitialIssuance(_issuedSupply, _issuer, _issuerAmount);
vm.stopPrank();
// buyer purchases
uint64 tokensToPurchase1 = 25;
uint64 tokensToPurchase2 = 25;
uint64 tokensToPurchase3 = 50;
uint64 tokensToPurchase = 100;
uint tokensToPurchaseWithDecimals = tokensToPurchase *
(10 ** IERC20(_token).decimals());
uint pricePerToken = 10e6; // $1
uint paymentAmount = tokensToPurchase * pricePerToken;
string memory orderId = "123";
// Issuer approves Vendor contract to transfer tokens
setupPurchaser(_buyer, buyerStakeholderId);
// Buyer approves Vendor contract to purchase tokens with usdc
// Vendor contract == _offering.
vm.startPrank(_buyer);
_usdc.approve(address(_offering), paymentAmount);
assertEq(IERC20(_token).balanceOf(address(_offering)), 0);
_offering.purchase(_buyer, tokensToPurchase1, orderId);
_offering.purchase(_buyer, tokensToPurchase2, orderId); //using same order id.
_offering.purchase(_buyer, tokensToPurchase3, orderId); //using same order id.
vm.stopPrank();
return tokensToPurchaseWithDecimals;
}
Implementing proper validation on the orderId
.
SOLVED : The Plural Energy team solved the issue by adding proper validation on validatePurchase
function.
function validatePurchase(
address purchaser,
uint paymentAmount,
uint64 amountRequested,
string calldata orderId
) public view override {
validateTransfer(purchaser, amountRequested);
require(
paymentRouter != address(0),
"Payment router is the zero address"
);
require(paymentAmount != 0, "Payment amount is 0");
require(
IERC20(paymentToken).allowance(purchaser, address(this)) >=
paymentAmount,
"Payment allowance too low"
);
if (orders[orderId].purchaser != purchaser) {
revert OrderWrongBuyer(purchaser, orders[orderId].purchaser);
}
if (orders[orderId].assetTokenAmount != amountRequested) {
revert OrderWrongAmount(
amountRequested,
orders[orderId].assetTokenAmount
);
}
if (orders[orderId].purchased) {
revert OrderAlreadyPurchased(orderId);
}
// TODO: check any cap table restrictions (e.g. limits for certain stakeholders)
// offering.validatePurchase();
}
// Informational
Some ERC20 token implementations have a fee that is charged on each token transfer. This means that the transferred amount isn't exactly what the receiver will get. The main issue then lies in that the protocol will pull funds from arbitrary ERC20 token implementation using transferFrom
, assuming that the receiving amount matches the amount sent as the parameter to the transfer call, which is not always the case.
/// @inheritdoc IOffering
function purchase(
address purchaser,
uint64 assetTokenAmount,
string calldata orderId
) external override nonReentrant whenNotPaused {
IERC20 _paymentToken = IERC20(paymentToken);
uint paymentAmount = sharePrice * assetTokenAmount;
validatePurchase(purchaser, paymentAmount, assetTokenAmount);
// Take payment from purchaser and transfer to the payment router.
require(
_paymentToken.transferFrom(purchaser, paymentRouter, paymentAmount),
"Payment failed"
);
_transferFromVendor(purchaser, assetTokenAmount, orderId);
}
It is recommended to improve support for USDT type of ERC20. When pulling funds from the user using transferFrom
the usual approach is to compare balances pre/post-transfer, like so:
// Take payment from purchaser and transfer to the payment router.
uint256 balanceBefore = IERC20(paymentToken).balanceOf(address(this));
require(
_paymentToken.transferFrom(purchaser, paymentRouter, paymentAmount),
"Payment failed"
);
uint256 transferred = IERC20(paymentToken).balanceOf(address(this)) - balanceBefore;
SOLVED : The Plural Energy team solved the issue by adding safeTransferFrom
function.
function purchase(
address purchaser,
uint64 assetTokenAmount,
string calldata orderId
) external override nonReentrant whenNotPaused {
IERC20 _paymentToken = IERC20(paymentToken);
uint paymentAmount = sharePrice * assetTokenAmount;
validatePurchase(purchaser, paymentAmount, assetTokenAmount, orderId);
// Take payment from purchaser and transfer to the payment router
IERC20(_paymentToken).safeTransferFrom(
purchaser,
paymentRouter,
paymentAmount
);
_transferFromVendor(purchaser, assetTokenAmount, orderId);
}
// Informational
The contract uses block.timestamp
. The global variable block.timestamp
does not necessarily hold the current time, and may not be accurate. Miners can influence the value of block.timestamp to perform Maximal Extractable Value (MEV) attacks. There is no guarantee that the value is correct, only that it is higher than the previous block’s timestamp.
Use block.number
instead of block.timestamp
to reduce the risk of MEV attacks. If possible, use an oracle.
ACKNOWLEDGED : The Plural Energy team acknowledged the issue.
// Informational
During the assessment it has been observed than the offeringAddress
is not properly validated. If the offering is deleted and after approved, the EVM revert is triggered due to the safeApprove
function is using as second parameter the address zero due to empty index mapping after deletion getter (getOffering
function).
/// @inheritdoc IAssetTokenVendor
function approveOffering(
address assetToken,
uint32 offeringNum
) public override onlyOwner {
address offeringAddress = getOffering(assetToken, offeringNum);
// Ensure compliance rules are updated for the new offering
IAssetToken _assetToken = IAssetToken(assetToken);
ICompliance compliance = ICompliance(_assetToken.compliance());
address[] memory tokenAddresses = new address[](1);
tokenAddresses[0] = assetToken;
string memory allowedRole = Roles.OFFERING;
string[] memory roles = new string[](1);
roles[0] = allowedRole;
compliance.addAllowedRolesToTokens(tokenAddresses, roles);
compliance.addRoleToAccount(allowedRole, offeringAddress);
// Approve offering to transfer up to the number of tokens for sale
IERC20(assetToken).safeApprove(
offeringAddress,
IOffering(offeringAddress).numTokensForSale()
);
}
Ensure zero address check in the case the offering is 0 due to deletion or not existing offering.
SOLVED : The Plural Energy team solved the issue by adding proper checks.
if (offeringAddress == address(0)) {
revert OfferingNotFound(assetToken, offeringNum);
}
// Informational
Most of the solidity for loops use an uint256 variable counter that increments by 1 and starts at 0. These increments don't need to be checked for over/underflow because the variable will never reach the max capacity of uint256 as it would run out of gas long before that happens.
It is recommended to uncheck the increments in for loops to save gas. For example, instead of:
for (uint i = 0; i < allowedTokenRolesLength; i++) {
byteRoles[i + 1] = compliance.tokenAllowedRoles(assetToken, i);
}
Use:
for (uint i = 0; i < allowedTokenRolesLength;) {
byteRoles[i + 1] = compliance.tokenAllowedRoles(assetToken, i);
unchecked {++i};
}
ACKNOWLEDGED : The Plural Energy team acknowledged the issue.
Halborn used automated testing techniques to enhance the coverage of certain areas of the smart contracts in scope. Among the tools used was Slither, a Solidity static analysis framework. After Halborn verified the smart contracts in the repository and was able to compile them correctly into their ABIs and binary format, Slither was run against the contracts. This tool can statically verify mathematical relationships between Solidity variables to detect invalid or inconsistent usage of the contracts' APIs across the entire code-base.
The security team assessed all findings identified by the Slither software, however, findings with severity Information
and Optimization
are not included in the below results for the sake of report readability.
HIGH:
Offering.purchase(address,uint64,string) (src/Offering.sol#72-89) uses arbitrary from in transferFrom: require(bool,string)(_paymentToken.transferFrom(purchaser,paymentRouter,paymentAmount),Payment failed) (src/Offering.sol#83-86)
Offering._transferToIssuer(address,uint256) (src/Offering.sol#227-240) uses arbitrary from in transferFrom: IERC20(assetToken).safeTransferFrom(tokenTreasury,issuerAddress,amount) (src/Offering.sol#234-238)
Offering._transferToPurchaser(address,uint256) (src/Offering.sol#243-252) uses arbitrary from in transferFrom: IERC20(assetToken).safeTransferFrom(tokenTreasury,receiverAddress,amount) (src/Offering.sol#247-251)
Reference: https://github.com/crytic/slither/wiki/Detector-Documentation#arbitrary-from-in-transferfrom
MathUpgradeable.mulDiv(uint256,uint256,uint256) (lib/openzeppelin-contracts-upgradeable/contracts/utils/math/MathUpgradeable.sol#55-134) has bitwise-xor operator ^ instead of the exponentiation operator **:
inverse = (3 * denominator) ^ 2 (lib/openzeppelin-contracts-upgradeable/contracts/utils/math/MathUpgradeable.sol#116)
Math.mulDiv(uint256,uint256,uint256) (lib/openzeppelin-contracts/contracts/utils/math/Math.sol#55-134) has bitwise-xor operator ^ instead of the exponentiation operator **:
inverse = (3 * denominator) ^ 2 (lib/openzeppelin-contracts/contracts/utils/math/Math.sol#116)
Reference: https://github.com/crytic/slither/wiki/Detector-Documentation#incorrect-exponentiation
MEDIUM:
Reentrancy in AssetTokenVendor.createOffering(address,uint32,OfferingParams) (src/AssetTokenVendor.sol#56-87):
External calls:
_offering = IOffering(address(new BeaconProxy(offeringBeacon,abi.encodeCall(IOffering.initialize,(offeringParams))))) (src/AssetTokenVendor.sol#75-82)
State variables written after the call(s):
offerings[offeringKey] = address(_offering) (src/AssetTokenVendor.sol#83)
AssetTokenVendor.offerings (src/AssetTokenVendor.sol#27) can be used in cross function reentrancies:
AssetTokenVendor.createOffering(address,uint32,OfferingParams) (src/AssetTokenVendor.sol#56-87)
AssetTokenVendor.deleteOffering(address,uint32) (src/AssetTokenVendor.sol#116-121)
AssetTokenVendor.getOffering(address,uint32) (src/AssetTokenVendor.sol#132-137)
AssetTokenVendor.offerings (src/AssetTokenVendor.sol#27)
Reference: https://github.com/crytic/slither/wiki/Detector-Documentation#reentrancy-vulnerabilities-1
Halborn strongly recommends conducting a follow-up assessment of the project either within six months or immediately following any material changes to the codebase, whichever comes first. This approach is crucial for maintaining the project’s integrity and addressing potential vulnerabilities introduced by code modifications.
// Download the full report
* Use Google Chrome for best results
** Check "Background Graphics" in the print settings if needed