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
364
365
366
367
368
369
370
371
372
373
374
375
376
|
// Copyright (c) 2021 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <base58.h>
#include <core_io.h>
#include <key.h>
#include <key_io.h>
#include <node/context.h>
#include <primitives/block.h>
#include <primitives/transaction.h>
#include <psbt.h>
#include <rpc/blockchain.h>
#include <rpc/client.h>
#include <rpc/request.h>
#include <rpc/server.h>
#include <rpc/util.h>
#include <span.h>
#include <streams.h>
#include <test/fuzz/FuzzedDataProvider.h>
#include <test/fuzz/fuzz.h>
#include <test/fuzz/util.h>
#include <test/util/setup_common.h>
#include <tinyformat.h>
#include <univalue.h>
#include <util/strencodings.h>
#include <util/string.h>
#include <util/time.h>
#include <cstdint>
#include <iostream>
#include <memory>
#include <optional>
#include <stdexcept>
#include <string>
#include <vector>
namespace {
struct RPCFuzzTestingSetup : public TestingSetup {
RPCFuzzTestingSetup(const std::string& chain_name, const std::vector<const char*>& extra_args) : TestingSetup{chain_name, extra_args}
{
}
UniValue CallRPC(const std::string& rpc_method, const std::vector<std::string>& arguments)
{
JSONRPCRequest request;
request.context = &m_node;
request.strMethod = rpc_method;
request.params = RPCConvertValues(rpc_method, arguments);
return tableRPC.execute(request);
}
std::vector<std::string> GetRPCCommands() const
{
return tableRPC.listCommands();
}
};
RPCFuzzTestingSetup* rpc_testing_setup = nullptr;
std::string g_limit_to_rpc_command;
// RPC commands which are not appropriate for fuzzing: such as RPC commands
// reading or writing to a filename passed as an RPC parameter, RPC commands
// resulting in network activity, etc.
const std::vector<std::string> RPC_COMMANDS_NOT_SAFE_FOR_FUZZING{
"addconnection", // avoid DNS lookups
"addnode", // avoid DNS lookups
"addpeeraddress", // avoid DNS lookups
"analyzepsbt", // avoid signed integer overflow in CFeeRate::GetFee(unsigned long) (https://github.com/bitcoin/bitcoin/issues/20607)
"dumptxoutset", // avoid writing to disk
#ifdef ENABLE_WALLET
"dumpwallet", // avoid writing to disk
#endif
"echoipc", // avoid assertion failure (Assertion `"EnsureAnyNodeContext(request.context).init" && check' failed.)
"generatetoaddress", // avoid prohibitively slow execution (when `num_blocks` is large)
"generatetodescriptor", // avoid prohibitively slow execution (when `nblocks` is large)
"gettxoutproof", // avoid prohibitively slow execution
#ifdef ENABLE_WALLET
"importwallet", // avoid reading from disk
"loadwallet", // avoid reading from disk
#endif
"prioritisetransaction", // avoid signed integer overflow in CTxMemPool::PrioritiseTransaction(uint256 const&, long const&) (https://github.com/bitcoin/bitcoin/issues/20626)
"savemempool", // disabled as a precautionary measure: may take a file path argument in the future
"setban", // avoid DNS lookups
"stop", // avoid shutdown state
};
// RPC commands which are safe for fuzzing.
const std::vector<std::string> RPC_COMMANDS_SAFE_FOR_FUZZING{
"clearbanned",
"combinepsbt",
"combinerawtransaction",
"converttopsbt",
"createmultisig",
"createpsbt",
"createrawtransaction",
"decodepsbt",
"decoderawtransaction",
"decodescript",
"deriveaddresses",
"disconnectnode",
"echo",
"echojson",
"estimaterawfee",
"estimatesmartfee",
"finalizepsbt",
"generate",
"generateblock",
"getaddednodeinfo",
"getbestblockhash",
"getblock",
"getblockchaininfo",
"getblockcount",
"getblockfilter",
"getblockhash",
"getblockheader",
"getblockstats",
"getblocktemplate",
"getchaintips",
"getchaintxstats",
"getconnectioncount",
"getdescriptorinfo",
"getdifficulty",
"getindexinfo",
"getmemoryinfo",
"getmempoolancestors",
"getmempooldescendants",
"getmempoolentry",
"getmempoolinfo",
"getmininginfo",
"getnettotals",
"getnetworkhashps",
"getnetworkinfo",
"getnodeaddresses",
"getpeerinfo",
"getrawmempool",
"getrawtransaction",
"getrpcinfo",
"gettxout",
"gettxoutsetinfo",
"help",
"invalidateblock",
"joinpsbts",
"listbanned",
"logging",
"mockscheduler",
"ping",
"preciousblock",
"pruneblockchain",
"reconsiderblock",
"scantxoutset",
"sendrawtransaction",
"setmocktime",
"setnetworkactive",
"signmessagewithprivkey",
"signrawtransactionwithkey",
"submitblock",
"submitheader",
"syncwithvalidationinterfacequeue",
"testmempoolaccept",
"uptime",
"utxoupdatepsbt",
"validateaddress",
"verifychain",
"verifymessage",
"verifytxoutproof",
"waitforblock",
"waitforblockheight",
"waitfornewblock",
};
std::string ConsumeScalarRPCArgument(FuzzedDataProvider& fuzzed_data_provider)
{
const size_t max_string_length = 4096;
std::string r;
CallOneOf(
fuzzed_data_provider,
[&] {
// string argument
r = fuzzed_data_provider.ConsumeRandomLengthString(max_string_length);
},
[&] {
// base64 argument
r = EncodeBase64(fuzzed_data_provider.ConsumeRandomLengthString(max_string_length));
},
[&] {
// hex argument
r = HexStr(fuzzed_data_provider.ConsumeRandomLengthString(max_string_length));
},
[&] {
// bool argument
r = fuzzed_data_provider.ConsumeBool() ? "true" : "false";
},
[&] {
// range argument
r = "[" + ToString(fuzzed_data_provider.ConsumeIntegral<int64_t>()) + "," + ToString(fuzzed_data_provider.ConsumeIntegral<int64_t>()) + "]";
},
[&] {
// integral argument (int64_t)
r = ToString(fuzzed_data_provider.ConsumeIntegral<int64_t>());
},
[&] {
// integral argument (uint64_t)
r = ToString(fuzzed_data_provider.ConsumeIntegral<uint64_t>());
},
[&] {
// floating point argument
r = strprintf("%f", fuzzed_data_provider.ConsumeFloatingPoint<double>());
},
[&] {
// tx destination argument
r = EncodeDestination(ConsumeTxDestination(fuzzed_data_provider));
},
[&] {
// uint160 argument
r = ConsumeUInt160(fuzzed_data_provider).ToString();
},
[&] {
// uint256 argument
r = ConsumeUInt256(fuzzed_data_provider).ToString();
},
[&] {
// base32 argument
r = EncodeBase32(fuzzed_data_provider.ConsumeRandomLengthString(max_string_length));
},
[&] {
// base58 argument
r = EncodeBase58(MakeUCharSpan(fuzzed_data_provider.ConsumeRandomLengthString(max_string_length)));
},
[&] {
// base58 argument with checksum
r = EncodeBase58Check(MakeUCharSpan(fuzzed_data_provider.ConsumeRandomLengthString(max_string_length)));
},
[&] {
// hex encoded block
std::optional<CBlock> opt_block = ConsumeDeserializable<CBlock>(fuzzed_data_provider);
if (!opt_block) {
return;
}
CDataStream data_stream{SER_NETWORK, PROTOCOL_VERSION};
data_stream << *opt_block;
r = HexStr(data_stream);
},
[&] {
// hex encoded block header
std::optional<CBlockHeader> opt_block_header = ConsumeDeserializable<CBlockHeader>(fuzzed_data_provider);
if (!opt_block_header) {
return;
}
CDataStream data_stream{SER_NETWORK, PROTOCOL_VERSION};
data_stream << *opt_block_header;
r = HexStr(data_stream);
},
[&] {
// hex encoded tx
std::optional<CMutableTransaction> opt_tx = ConsumeDeserializable<CMutableTransaction>(fuzzed_data_provider);
if (!opt_tx) {
return;
}
CDataStream data_stream{SER_NETWORK, fuzzed_data_provider.ConsumeBool() ? PROTOCOL_VERSION : (PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS)};
data_stream << *opt_tx;
r = HexStr(data_stream);
},
[&] {
// base64 encoded psbt
std::optional<PartiallySignedTransaction> opt_psbt = ConsumeDeserializable<PartiallySignedTransaction>(fuzzed_data_provider);
if (!opt_psbt) {
return;
}
CDataStream data_stream{SER_NETWORK, PROTOCOL_VERSION};
data_stream << *opt_psbt;
r = EncodeBase64({data_stream.begin(), data_stream.end()});
},
[&] {
// base58 encoded key
const std::vector<uint8_t> random_bytes = fuzzed_data_provider.ConsumeBytes<uint8_t>(32);
CKey key;
key.Set(random_bytes.begin(), random_bytes.end(), fuzzed_data_provider.ConsumeBool());
if (!key.IsValid()) {
return;
}
r = EncodeSecret(key);
},
[&] {
// hex encoded pubkey
const std::vector<uint8_t> random_bytes = fuzzed_data_provider.ConsumeBytes<uint8_t>(32);
CKey key;
key.Set(random_bytes.begin(), random_bytes.end(), fuzzed_data_provider.ConsumeBool());
if (!key.IsValid()) {
return;
}
r = HexStr(key.GetPubKey());
});
return r;
}
std::string ConsumeArrayRPCArgument(FuzzedDataProvider& fuzzed_data_provider)
{
std::vector<std::string> scalar_arguments;
while (fuzzed_data_provider.ConsumeBool()) {
scalar_arguments.push_back(ConsumeScalarRPCArgument(fuzzed_data_provider));
}
return "[\"" + Join(scalar_arguments, "\",\"") + "\"]";
}
std::string ConsumeRPCArgument(FuzzedDataProvider& fuzzed_data_provider)
{
return fuzzed_data_provider.ConsumeBool() ? ConsumeScalarRPCArgument(fuzzed_data_provider) : ConsumeArrayRPCArgument(fuzzed_data_provider);
}
RPCFuzzTestingSetup* InitializeRPCFuzzTestingSetup()
{
static const auto setup = MakeNoLogFileContext<RPCFuzzTestingSetup>();
SetRPCWarmupFinished();
return setup.get();
}
}; // namespace
void initialize_rpc()
{
rpc_testing_setup = InitializeRPCFuzzTestingSetup();
const std::vector<std::string> supported_rpc_commands = rpc_testing_setup->GetRPCCommands();
for (const std::string& rpc_command : supported_rpc_commands) {
const bool safe_for_fuzzing = std::find(RPC_COMMANDS_SAFE_FOR_FUZZING.begin(), RPC_COMMANDS_SAFE_FOR_FUZZING.end(), rpc_command) != RPC_COMMANDS_SAFE_FOR_FUZZING.end();
const bool not_safe_for_fuzzing = std::find(RPC_COMMANDS_NOT_SAFE_FOR_FUZZING.begin(), RPC_COMMANDS_NOT_SAFE_FOR_FUZZING.end(), rpc_command) != RPC_COMMANDS_NOT_SAFE_FOR_FUZZING.end();
if (!(safe_for_fuzzing || not_safe_for_fuzzing)) {
std::cerr << "Error: RPC command \"" << rpc_command << "\" not found in RPC_COMMANDS_SAFE_FOR_FUZZING or RPC_COMMANDS_NOT_SAFE_FOR_FUZZING. Please update " << __FILE__ << ".\n";
std::terminate();
}
if (safe_for_fuzzing && not_safe_for_fuzzing) {
std::cerr << "Error: RPC command \"" << rpc_command << "\" found in *both* RPC_COMMANDS_SAFE_FOR_FUZZING and RPC_COMMANDS_NOT_SAFE_FOR_FUZZING. Please update " << __FILE__ << ".\n";
std::terminate();
}
}
for (const std::string& rpc_command : RPC_COMMANDS_SAFE_FOR_FUZZING) {
const bool supported_rpc_command = std::find(supported_rpc_commands.begin(), supported_rpc_commands.end(), rpc_command) != supported_rpc_commands.end();
if (!supported_rpc_command) {
std::cerr << "Error: Unknown RPC command \"" << rpc_command << "\" found in RPC_COMMANDS_SAFE_FOR_FUZZING. Please update " << __FILE__ << ".\n";
std::terminate();
}
}
for (const std::string& rpc_command : RPC_COMMANDS_NOT_SAFE_FOR_FUZZING) {
const bool supported_rpc_command = std::find(supported_rpc_commands.begin(), supported_rpc_commands.end(), rpc_command) != supported_rpc_commands.end();
if (!supported_rpc_command) {
std::cerr << "Error: Unknown RPC command \"" << rpc_command << "\" found in RPC_COMMANDS_NOT_SAFE_FOR_FUZZING. Please update " << __FILE__ << ".\n";
std::terminate();
}
}
const char* limit_to_rpc_command_env = std::getenv("LIMIT_TO_RPC_COMMAND");
if (limit_to_rpc_command_env != nullptr) {
g_limit_to_rpc_command = std::string{limit_to_rpc_command_env};
}
}
FUZZ_TARGET_INIT(rpc, initialize_rpc)
{
FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
SetMockTime(ConsumeTime(fuzzed_data_provider));
const std::string rpc_command = fuzzed_data_provider.ConsumeRandomLengthString(64);
if (!g_limit_to_rpc_command.empty() && rpc_command != g_limit_to_rpc_command) {
return;
}
const bool safe_for_fuzzing = std::find(RPC_COMMANDS_SAFE_FOR_FUZZING.begin(), RPC_COMMANDS_SAFE_FOR_FUZZING.end(), rpc_command) != RPC_COMMANDS_SAFE_FOR_FUZZING.end();
if (!safe_for_fuzzing) {
return;
}
std::vector<std::string> arguments;
while (fuzzed_data_provider.ConsumeBool()) {
arguments.push_back(ConsumeRPCArgument(fuzzed_data_provider));
}
try {
rpc_testing_setup->CallRPC(rpc_command, arguments);
} catch (const UniValue&) {
} catch (const std::runtime_error&) {
}
}
|