Prepared by:
HALBORN
Last Updated 10/01/2024
Date of Engagement: September 9th, 2024 - September 20th, 2024
100% of all REPORTED Findings have been addressed
All findings
10
Critical
0
High
1
Medium
0
Low
4
Informational
5
Pepper Team
engaged Halborn
to conduct a security assessment on their smart contracts beginning on September 9th, 2024, and ending on September 20th, 2024. The security assessments were scoped to the smart contracts provided in the pepper-token
GitHub repository. Commit hashes and further details can be found in the Scope section of this report.
Halborn
was provided 11 (eleven) days for the engagement, and assigned 1 (one) full-time security engineers to review the security of the smart contracts in scope. The engineer is a blockchain and smart contract security expert with advanced penetration testing and smart contract hacking skills, and deep knowledge of multiple blockchain protocols.
The purpose of the assessment is to:
Identify potential security issues within the smart contracts.
Ensure that smart contract functionality operates as intended.
In summary, Halborn
identified some security issues, that were mostly addressed by the Pepper team
. The main security issues were:
Allowing the airdrop contract to mint tokens to the users without reverting.
Input validations for critical setter functions.
Gas saving suggestions.
Halborn
performed a combination of manual, semi-automated and automated security testing to balance efficiency, timeliness, practicality, and accuracy regarding 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 security best practices. The following phases and associated tools were used throughout the term of the assessment:
Research into architecture and purpose.
Smart contract manual code review and walk-through.
Manual assessment of use and safety for the critical Solidity variables and functions in scope to identify any vulnerability classes
Manual testing by custom scripts.
Static Analysis of security for scoped contract, and imported functions. (Slither
)
Local deployment and testing ( Foundry
)
EXPLOITABILITY 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
0
High
1
Medium
0
Low
4
Informational
5
Security analysis | Risk level | Remediation Date |
---|---|---|
Minting Limit Calculation May Prevent Legitimate Claims | High | Solved - 09/20/2024 |
Missing Zero-Value Check in changeEpochLength Function | Low | Solved - 09/20/2024 |
Insufficient Validation of Claim Start Block | Low | Solved - 09/20/2024 |
Modification of Claim Start Block After Claiming Begins | Low | Solved - 09/20/2024 |
Modification of Epoch Length After Claiming Begins | Low | Solved - 09/20/2024 |
Lack of two-step ownership transfer pattern | Informational | Acknowledged - 09/20/2024 |
Lack of Null Value Validation | Informational | Solved - 09/20/2024 |
Suboptimal Gas Usage in removeValidator Function | Informational | Solved - 09/20/2024 |
Code Duplication in getPendingClaim and claim Functions | Informational | Solved - 09/20/2024 |
Minor Reward Discrepancy Between calculateRewards and calculateRewards2 | Informational | Acknowledged - 09/27/2024 |
//
In the Pepper contract, the mint
function implements a cap on minting that is intended to limit mints to 40% of the total supply.
function mint(address to, uint256 amount) public {
require(hasRole(MINTER_ROLE, msg.sender), "Must have minter role to mint");
uint256 _amount = totalSupply() + amount;
require(_amount <= MINT_LIMIT, "Minting exceeds 40% of total supply");
require(_amount <= MAX_SUPPLY, "Max supply reached");
_mint(to, amount);
}
The issue lies in using the total supply to calculate the minting limit. This approach doesn't distinguish between tokens minted through the mint
function and those minted through other means, such as claims. As a result, once the total supply reaches 40% of MAX_SUPPLY
, the minting operations through mint
function will revert.
This can lead to a scenario where the PepperAirdrop::mintPepper
function, which relies on this mint
function, starts to revert unexpectedly. This could disrupt planned airdrops and prevent users from receiving their entitled tokens.
Add the following function to Pepper.t.sol
function test_ClaimRevert_PoC() public {
uint256 amount = pepper.MINT_LIMIT() / 250;
address user1 = vm.addr(1);
// give 3000 CHZ to user
vm.deal(user1, amount);
// user stakes on validator 2
vm.prank(user1);
stakingPool.stake{value: amount}(vm.addr(6));
//claim
vm.prank(user1);
pepper.claim();
//Mocking a call from PepperAirdrop to mint 500 Pepper to a user
vm.expectRevert("Minting exceeds 40% of total supply");
pepper.mint(user1, 500e18);
}
Run with forge test --mt "test_ClaimRevert_PoC" -vvvv
To address this issue, implement a separate tracker for mints performed by accounts with the MINTER_ROLE
. This allows for proper enforcement of the 40% limit on controlled mints while allowing claims to proceed normally. Here's a revised implementation:
// Add this state variable
uint256 public minterRoleMintedAmount;
function mint(address to, uint256 amount) public {
require(hasRole(MINTER_ROLE, msg.sender), "Must have minter role to mint");
uint256 newMinterRoleMintedAmount = minterRoleMintedAmount + amount;
require(newMinterRoleMintedAmount <= MINT_LIMIT, "Minting exceeds 40% of total supply for minter role");
uint256 newTotalSupply = totalSupply() + amount;
require(newTotalSupply <= MAX_SUPPLY, "Max supply reached");
minterRoleMintedAmount = newMinterRoleMintedAmount;
_mint(to, amount);
}
SOLVED: The suggested mitigation was implemented by the Pepper team.
//
The changeEpochLength
function in the Pepper contract allows the owner to set the EPOCH_LENGTH
without validating that the new value is non-zero. This oversight can lead to a critical issue in the contract's functionality, specifically:
If EPOCH_LENGTH
is set to zero, it will cause a divide-by-zero error in the getCurrentEpoch
function:
function getCurrentEpoch() public view returns (uint256 _epoch) {
return (block.number - claimStartBlock) / EPOCH_LENGTH;
}
This divide-by-zero error would cause all calls to getCurrentEpoch
to revert, effectively breaking core functionalities of the contract that rely on epoch calculations, such as the claiming mechanism.
This vulnerability could potentially render the contract unusable if the epoch length is accidentally set to zero.
To address this issue, implement a non-zero check in the changeEpochLength
function.
function changeEpochLength(uint16 epochLength) public onlyOwner {
require(epochLength != 0, "Epoch length cannot be zero");
EPOCH_LENGTH = epochLength;
emit EpochLengthChanged(epochLength);
}
This change ensures that:
The EPOCH_LENGTH
can never be set to zero, preventing potential divide-by-zero errors.
The contract maintains its integrity and functionality, particularly in epoch-based calculations.
SOLVED: The Pepper team decided to remove the changeEpochLength
function from the Pepper
contract.
//
The constructor of the Pepper contract allows setting the claimStartBlock
without proper validation. Currently, there's no check to ensure that the provided _claimStartBlock
is either set to the current block number or a future block number.
constructor(
uint256 _claimStartBlock,
string memory _tokenName,
string memory _tokenSymbol,
address[] memory initialValidators
) ERC20(_tokenName, _tokenSymbol) ERC20Capped(MAX_SUPPLY) {
claimStartBlock = _claimStartBlock;
// Set initial validators
validators = initialValidators;
// Grant the contract deployer the default admin role: it will be able to grant and revoke any roles
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setupRole(MINTER_ROLE, msg.sender);
}
This oversight could potentially lead to issues if the _claimStartBlock
is mistakenly set to a past block number, which might enable premature claiming of rewards or cause other unexpected behaviors in the contract's timing-dependent functions.
A similar issue in changeClaimStartBlock
function:
function changeClaimStartBlock(uint256 newStartBlock) public onlyOwner {
claimStartBlock = newStartBlock;
emit ClaimStartBlockChanged(newStartBlock);
}
To address this issue, implement a check in the constructor
and changeClaimStartBlock
function to ensure that the _claimStartBlock
is either equal to or greater than the current block number.
require(_claimStartBlock >= block.number, "Claim start block must be current or future block");
SOLVED: The suggested check was added to changeClaimStartBlock
function. It was not added in the constructor
as the check exists in the deployment script for the Pepper
contract.
//
The changeClaimStartBlock
function in the Pepper contract allows the owner to modify the claimStartBlock
at any time, even after the claiming process has begun.
function changeClaimStartBlock(uint256 newStartBlock) public onlyOwner {
claimStartBlock = newStartBlock;
emit ClaimStartBlockChanged(newStartBlock);
}
This unrestricted ability to change the start block can lead to significant issues in the contract's accounting and fairness mechanisms. Specifically:
It can disrupt the epoch calculation, potentially causing inconsistencies in reward distributions.
It may invalidate previous claims or allow double-claiming if the new start block is set to a past value.
It could unfairly advantage or disadvantage users depending on how the start block is changed.
This undermines the integrity and predictability of the claiming process, which is crucial for user trust and proper contract functionality.
To address this issue, implement a check in the changeClaimStartBlock
function to prevent modifications after the claiming process has started.
function changeClaimStartBlock(uint256 newStartBlock) public onlyOwner {
require(block.number < claimStartBlock, "Claiming has already begun, cannot change start block");
require(newStartBlock > block.number, "New claim start block must be a future block");
claimStartBlock = newStartBlock;
emit ClaimStartBlockChanged(newStartBlock);
}
SOLVED: The suggested mitigation was implemented along with adding a new variable, claimEnabled
, which when set to true
will prevent modification to claimStartBlock.
require(!claimEnabled, "Claim currently active");
//
The changeEpochLength
function in the Pepper contract allows the owner to modify the EPOCH_LENGTH
at any time, even after the claiming process has begun. This unrestricted ability to change the epoch length can lead to significant issues in the contract's accounting and fairness mechanisms, as pointed out in the issue "Modification of Claim Start Block After Claiming Begins".
function changeEpochLength(uint16 epochLength) public onlyOwner {
EPOCH_LENGTH = epochLength;
emit EpochLengthChanged(epochLength);
}
To address this issue, implement a check in the changeEpochLength
function to prevent modifications after the claiming process has started.
SOLVED: The Pepper team decided to remove the changeEpochLength
function from the Pepper
contract.
//
Pepper.sol
and Pepperairdrop.sol
implements the Ownable pattern. However, the assessment revealed that the solution does not support the two-step-ownership-transfer pattern. The ownership transfer might be accidentally set to an inactive EOA account. In the case of account hijacking, all functionalities get under permanent control of the attacker.
It is recommended to implement a two-step process (Openzeppelin's Ownable2Step.sol
) where the owner nominates an account and the nominated account needs to call an acceptOwnership()
function for the transfer of the ownership to fully succeed. This ensures the nominated EOA account is a valid and active account.
ACKNOWLEDGED: The Pepper team acknowledged the above finding.
//
Here are the functions that lack these checks:
In the constructor:
_claimStartBlock
: While this is a uint256 and not an address, it's still important to validate that it's not 0.
In the changeStakingContract
function:
newStakingContract
: This should be checked to ensure it's not address(0).
In the changeStakingPoolContract
function:
newStakingPoolContract
: This should be checked to ensure it's not address(0).
In the addValidator
function:
validator
: This should be checked to ensure it's not address(0).
In the removeValidator
function:
validator
: While less critical here, it's still good practice to check that it's not address(0).
Every input address should be checked not to be zero, especially the ones that could lead to rendering the contract unusable, lock tokens, etc. This is considered a best practice.
SOLVED: All the necessary null value checks were added to the Pepper
contract.
//
The removeValidator
function in the Pepper contract iterates through the validators
array to find and remove a specific validator. While the function correctly implements the removal process, it does not optimize for gas efficiency. The current implementation accesses the validators.length
property in each iteration of the loop, which can be costly in terms of gas, especially for larger arrays.
function removeValidator(address validator) external onlyOwner {
for (uint256 i = 0; i < validators.length; i++) {
if (validators[i] == validator) {
validators[i] = validators[validators.length - 1];
validators.pop();
break;
}
}
}
In Solidity, accessing an array's length in each iteration of a loop is considered inefficient, as it requires an extra storage read operation each time. This inefficiency becomes more pronounced as the array grows larger.
To improve gas efficiency, it's recommended to cache the array length before entering the loop. This reduces the number of storage reads and can lead to noticeable gas savings, especially for larger validator sets.
Here's an optimized version of the function:
function removeValidator(address validator) external onlyOwner {
uint256 validatorCount = validators.length;
for (uint256 i = 0; i < validatorCount; i++) {
if (validators[i] == validator) {
validators[i] = validators[validatorCount - 1];
validators.pop();
break;
}
}
}
SOLVED: The suggested mitigation was implemented by the Pepper team.
//
The Pepper contract contains two functions, getPendingClaim
and claim
, which share significant portions of identical logic.
function getPendingClaim() external view returns (uint256 pendingHarvest) {
require(block.number >= claimStartBlock, "Claim is not enabled");
uint256 currentEpoch = getCurrentEpoch();
require(claims[msg.sender][currentEpoch].blockNumber == 0, "Already claimed for this epoch");
(uint256 rewardStakingPool, uint256 rewardStaking) = calculateRewards(msg.sender);
uint256 totalReward = rewardStakingPool + rewardStaking;
return totalReward;
}
function claim() external nonReentrant {
require(block.number >= claimStartBlock, "Claim is not enabled");
uint256 currentEpoch = getCurrentEpoch();
require(claims[msg.sender][currentEpoch].blockNumber == 0, "Already claimed for this epoch");
(uint256 rewardStakingPool, uint256 rewardStaking) = calculateRewards(msg.sender);
uint256 totalReward = rewardStakingPool + rewardStaking;
claims[msg.sender][currentEpoch] = Claim({
amountStakingPoolClaimed: rewardStakingPool,
amountStakingClaimed: rewardStaking,
blockNumber: block.number
});
emit Claimed(msg.sender, rewardStakingPool, rewardStaking);
_mint(msg.sender, totalReward);
}
The duplicated logic includes:
Checking if claiming is enabled
Calculating the current epoch
Verifying if a claim has already been made for the current epoch
Calculating rewards
This duplication increases the contract's complexity and the potential for errors during future modifications.
To address this issue, refactor the common logic.
Here's an example of how to implement this:
function getPendingClaim(address user) public view returns (uint256 pendingHarvest) {
require(block.number >= claimStartBlock, "Claim is not enabled");
uint256 currentEpoch = getCurrentEpoch();
require(claims[user][currentEpoch].blockNumber == 0, "Already claimed for this epoch");
(uint256 rewardStakingPool, uint256 rewardStaking) = _calculatePendingClaim(user);
return rewardStakingPool + rewardStaking;
}
function claim() external nonReentrant {
uint256 totalReward = getPendingClaim(msg.sender);
uint256 currentEpoch = getCurrentEpoch();
claims[msg.sender][currentEpoch] = Claim({
amountStakingPoolClaimed: rewardStakingPool,
amountStakingClaimed: rewardStaking,
blockNumber: block.number
});
emit Claimed(msg.sender, rewardStakingPool, rewardStaking);
_mint(msg.sender, totalReward);
}
SOLVED: A new internal function was added which contains the common logic between both functions:
function _calculateRewards(
address account
) private view returns (uint256 rewardStakingPoolAmount, uint256 rewardStakingAmount) {
require(getClaimStatus(), "Claim is not enabled");
uint256 currentEpoch = getCurrentEpoch();
require(claims[account][currentEpoch].blockNumber == 0, "Already claimed for this epoch");
return calculateRewards(account);
}
//
The calculateRewards2
function does not account for the amountToStake
returned by _calcUnclaimedDelegatorFee
, which results in a slightly lower totalStakedInPool
and consequently reduces the stakingPoolStakes
for a user. In contrast, users who use calculateRewards
might receive slightly higher rewards, causing a small discrepancy in reward distribution.
This behavior should be documented to inform users about the potential difference in reward calculations between the two functions.
ACKNOWLEDGED: The Pepper team acknowledged this finding with the following comment: "We decided to make this compromise to reduce the transaction fee. so basically user may get less (just slightly less) Peppers but they will pay 10x less in transaction fee."
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.
Most of the issues found were false positives, including the reentrancy. One suggestion related to caching the array length to save gas was included in the final report.
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