Branch data Line data Source code
1 : : // Copyright (c) 2021-present The Bitcoin Core developers
2 : : // Distributed under the MIT software license, see the accompanying
3 : : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4 : :
5 : : #include <base58.h>
6 : : #include <key.h>
7 : : #include <key_io.h>
8 : : #include <primitives/block.h>
9 : : #include <primitives/transaction.h>
10 : : #include <psbt.h>
11 : : #include <rpc/request.h>
12 : : #include <rpc/server.h>
13 : : #include <span.h>
14 : : #include <streams.h>
15 : : #include <test/fuzz/FuzzedDataProvider.h>
16 : : #include <test/fuzz/fuzz.h>
17 : : #include <test/fuzz/util.h>
18 : : #include <test/util/setup_common.h>
19 : : #include <test/util/time.h>
20 : : #include <tinyformat.h>
21 : : #include <uint256.h>
22 : : #include <univalue.h>
23 : : #include <util/check.h>
24 : : #include <util/strencodings.h>
25 : : #include <util/string.h>
26 : : #include <util/time.h>
27 : :
28 : : #include <algorithm>
29 : : #include <cstdint>
30 : : #include <cstdlib>
31 : : #include <exception>
32 : : #include <iostream>
33 : : #include <memory>
34 : : #include <optional>
35 : : #include <stdexcept>
36 : : #include <utility>
37 : : #include <vector>
38 : :
39 : : enum class ChainType;
40 : :
41 : : namespace {
42 : 1 : struct RPCFuzzTestingSetup : public TestingSetup {
43 [ + - ]: 1 : RPCFuzzTestingSetup(const ChainType chain_type, TestOpts opts) : TestingSetup{chain_type, opts}
44 : : {
45 : 1 : }
46 : :
47 : 15376 : void CallRPC(const std::string& rpc_method, UniValue&& params)
48 : : {
49 : 15376 : JSONRPCRequest request;
50 : 15376 : request.context = &m_node;
51 [ + - ]: 15376 : request.strMethod = rpc_method;
52 : 15376 : request.params = std::move(params);
53 [ + + ]: 15376 : tableRPC.execute(request);
54 : 15376 : }
55 : :
56 : 1 : std::vector<std::string> GetRPCCommands() const
57 : : {
58 : 1 : return tableRPC.listCommands();
59 : : }
60 : : };
61 : :
62 : : RPCFuzzTestingSetup* rpc_testing_setup = nullptr;
63 : : std::string g_limit_to_rpc_command;
64 : :
65 : : // RPC commands which are not appropriate for fuzzing: such as RPC commands
66 : : // reading or writing to a filename passed as an RPC parameter, RPC commands
67 : : // resulting in network activity, etc.
68 : : const std::vector<std::string> RPC_COMMANDS_NOT_SAFE_FOR_FUZZING{
69 : : "addconnection", // avoid DNS lookups
70 : : "addnode", // avoid DNS lookups
71 : : "addpeeraddress", // avoid DNS lookups
72 : : "dumptxoutset", // avoid writing to disk
73 : : "enumeratesigners",
74 : : "echoipc", // avoid assertion failure (Assertion `"EnsureAnyNodeContext(request.context).init" && check' failed.)
75 : : "exportasmap", // avoid writing to disk
76 : : "generateblock", // avoid chain state changes and disk writes (mines and submits a block)
77 : : "generatetoaddress", // avoid prohibitively slow execution (when `num_blocks` is large)
78 : : "generatetodescriptor", // avoid prohibitively slow execution (when `nblocks` is large)
79 : : "gettxoutproof", // avoid prohibitively slow execution
80 : : "importmempool", // avoid reading from disk
81 : : "loadtxoutset", // avoid reading from disk
82 : : "loadwallet", // avoid reading from disk
83 : : "savemempool", // disabled as a precautionary measure: may take a file path argument in the future
84 : : "setban", // avoid DNS lookups
85 : : "stop", // avoid shutdown state
86 : : "waitforblock", // avoid blocking forever (tip never changes during fuzzing; no timeout by default)
87 : : "waitforblockheight", // avoid blocking forever (tip never changes during fuzzing; no timeout by default)
88 : : "waitfornewblock", // avoid blocking forever (tip never changes during fuzzing; no timeout by default)
89 : : };
90 : :
91 : : // RPC commands which are safe for fuzzing.
92 : : const std::vector<std::string> RPC_COMMANDS_SAFE_FOR_FUZZING{
93 : : "abortprivatebroadcast",
94 : : "analyzepsbt",
95 : : "clearbanned",
96 : : "combinepsbt",
97 : : "combinerawtransaction",
98 : : "converttopsbt",
99 : : "createmultisig",
100 : : "createpsbt",
101 : : "createrawtransaction",
102 : : "decodepsbt",
103 : : "decoderawtransaction",
104 : : "decodescript",
105 : : "deriveaddresses",
106 : : "descriptorprocesspsbt",
107 : : "disconnectnode",
108 : : "echo",
109 : : "echojson",
110 : : "estimaterawfee",
111 : : "estimatesmartfee",
112 : : "finalizepsbt",
113 : : "generate",
114 : : "getaddednodeinfo",
115 : : "getaddrmaninfo",
116 : : "getbestblockhash",
117 : : "getblock",
118 : : "getblockchaininfo",
119 : : "getblockcount",
120 : : "getblockfilter",
121 : : "getblockfrompeer", // when no peers are connected, no p2p message is sent
122 : : "getblockhash",
123 : : "getblockheader",
124 : : "getblockstats",
125 : : "getblocktemplate",
126 : : "getchaintips",
127 : : "getchainstates",
128 : : "getchaintxstats",
129 : : "getconnectioncount",
130 : : "getdeploymentinfo",
131 : : "getdescriptoractivity",
132 : : "getdescriptorinfo",
133 : : "getdifficulty",
134 : : "getindexinfo",
135 : : "getmemoryinfo",
136 : : "getmempoolancestors",
137 : : "getmempooldescendants",
138 : : "getmempoolentry",
139 : : "getmempoolfeeratediagram",
140 : : "getmempoolcluster",
141 : : "getmempoolinfo",
142 : : "getmininginfo",
143 : : "getnettotals",
144 : : "getnetworkhashps",
145 : : "getnetworkinfo",
146 : : "getnodeaddresses",
147 : : "getopenrpcinfo",
148 : : "getorphantxs",
149 : : "getpeerinfo",
150 : : "getprioritisedtransactions",
151 : : "getprivatebroadcastinfo",
152 : : "getrawaddrman",
153 : : "getrawmempool",
154 : : "getrawtransaction",
155 : : "getrpcinfo",
156 : : "gettxout",
157 : : "gettxoutsetinfo",
158 : : "gettxspendingprevout",
159 : : "help",
160 : : "invalidateblock",
161 : : "joinpsbts",
162 : : "listbanned",
163 : : "logging",
164 : : "mockscheduler",
165 : : "ping",
166 : : "preciousblock",
167 : : "prioritisetransaction",
168 : : "pruneblockchain",
169 : : "reconsiderblock",
170 : : "rpc.discover",
171 : : "scanblocks",
172 : : "scantxoutset",
173 : : "sendmsgtopeer", // when no peers are connected, no p2p message is sent
174 : : "sendrawtransaction",
175 : : "setmocktime",
176 : : "setnetworkactive",
177 : : "signmessagewithprivkey",
178 : : "signrawtransactionwithkey",
179 : : "submitblock",
180 : : "submitheader",
181 : : "submitpackage",
182 : : "syncwithvalidationinterfacequeue",
183 : : "testmempoolaccept",
184 : : "uptime",
185 : : "utxoupdatepsbt",
186 : : "validateaddress",
187 : : "verifychain",
188 : : "verifymessage",
189 : : "verifytxoutproof",
190 : : };
191 : :
192 : 529714 : UniValue ConsumeBasicRPCArgument(FuzzedDataProvider& fuzzed_data_provider, bool& good_data)
193 : : {
194 : 529714 : const size_t max_string_length = 4096;
195 : 529714 : const size_t max_base58_bytes_length{64};
196 [ + - ]: 529714 : UniValue r{};
197 [ + - ]: 529714 : CallOneOf(
198 : : fuzzed_data_provider,
199 : 2897 : [&] {
200 : : // arbitrary JSON argument
201 [ - + + - : 2897 : if (!r.read(fuzzed_data_provider.ConsumeRandomLengthString(max_string_length))) {
+ + ]
202 : 2381 : good_data = false;
203 : : }
204 : 2897 : },
205 : 313862 : [&] {
206 : : // null argument
207 : 313862 : r = UniValue{UniValue::VNULL};
208 : 313862 : },
209 : 3907 : [&] {
210 : : // string argument
211 [ + - ]: 3907 : r = UniValue{fuzzed_data_provider.ConsumeRandomLengthString(max_string_length)};
212 : 3907 : },
213 : 12048 : [&] {
214 : : // base64 argument
215 [ - + + - : 12048 : r = UniValue{EncodeBase64(fuzzed_data_provider.ConsumeRandomLengthString(max_string_length))};
+ - ]
216 : 12048 : },
217 : 2523 : [&] {
218 : : // hex argument
219 [ - + + - : 2523 : r = UniValue{HexStr(fuzzed_data_provider.ConsumeRandomLengthString(max_string_length))};
+ - ]
220 : 2523 : },
221 : 5681 : [&] {
222 : : // bool argument
223 : 5681 : r = UniValue{fuzzed_data_provider.ConsumeBool()};
224 : 5681 : },
225 : 1494 : [&] {
226 : : // integral argument (int64_t)
227 : 1494 : r = UniValue{fuzzed_data_provider.ConsumeIntegral<int64_t>()};
228 : 1494 : },
229 : 9715 : [&] {
230 : : // integral argument (uint64_t)
231 : 9715 : r = UniValue{fuzzed_data_provider.ConsumeIntegral<uint64_t>()};
232 : 9715 : },
233 : 32953 : [&] {
234 : : // floating point argument
235 : 32953 : r = UniValue{fuzzed_data_provider.ConsumeFloatingPoint<double>()};
236 : 32953 : },
237 : 42061 : [&] {
238 : : // tx destination argument
239 [ + - + - ]: 42061 : r = UniValue{EncodeDestination(ConsumeTxDestination(fuzzed_data_provider))};
240 : 42061 : },
241 : 16390 : [&] {
242 : : // uint160 argument
243 [ + - ]: 16390 : r = UniValue{ConsumeUInt160(fuzzed_data_provider).ToString()};
244 : 16390 : },
245 : 3463 : [&] {
246 : : // uint256 argument
247 [ + - ]: 3463 : r = UniValue{ConsumeUInt256(fuzzed_data_provider).ToString()};
248 : 3463 : },
249 : 3606 : [&] {
250 : : // base32 argument
251 [ - + + - : 3606 : r = UniValue{EncodeBase32(fuzzed_data_provider.ConsumeRandomLengthString(max_string_length))};
+ - ]
252 : 3606 : },
253 : 29916 : [&] {
254 : : // base58 argument
255 [ + - + - ]: 29916 : r = UniValue{EncodeBase58(MakeUCharSpan(fuzzed_data_provider.ConsumeRandomLengthString(max_base58_bytes_length)))};
256 : 29916 : },
257 : 14918 : [&] {
258 : : // base58 argument with checksum
259 [ + - + - ]: 14918 : r = UniValue{EncodeBase58Check(MakeUCharSpan(fuzzed_data_provider.ConsumeRandomLengthString(max_base58_bytes_length)))};
260 : 14918 : },
261 : 509 : [&] {
262 : : // hex encoded block
263 : 509 : std::optional<CBlock> opt_block = ConsumeDeserializable<CBlock>(fuzzed_data_provider, TX_WITH_WITNESS);
264 [ + + ]: 509 : if (!opt_block) {
265 : 271 : good_data = false;
266 : 271 : return;
267 : : }
268 [ + - ]: 238 : DataStream data_stream{};
269 [ + - ]: 238 : data_stream << TX_WITH_WITNESS(*opt_block);
270 [ - + + - : 238 : r = UniValue{HexStr(data_stream)};
+ - ]
271 : 509 : },
272 : 1301 : [&] {
273 : : // hex encoded block header
274 : 1301 : std::optional<CBlockHeader> opt_block_header = ConsumeDeserializable<CBlockHeader>(fuzzed_data_provider);
275 [ + + ]: 1301 : if (!opt_block_header) {
276 : 120 : good_data = false;
277 : 120 : return;
278 : : }
279 [ + - ]: 1181 : DataStream data_stream{};
280 [ + - ]: 1181 : data_stream << *opt_block_header;
281 [ - + + - : 1181 : r = UniValue{HexStr(data_stream)};
+ - ]
282 : 1181 : },
283 : 2089 : [&] {
284 : : // hex encoded tx
285 : 2089 : std::optional<CMutableTransaction> opt_tx = ConsumeDeserializable<CMutableTransaction>(fuzzed_data_provider, TX_WITH_WITNESS);
286 [ + + ]: 2089 : if (!opt_tx) {
287 : 542 : good_data = false;
288 [ - + ]: 542 : return;
289 : : }
290 : 1547 : DataStream data_stream;
291 [ + + ]: 1547 : auto allow_witness = (fuzzed_data_provider.ConsumeBool() ? TX_WITH_WITNESS : TX_NO_WITNESS);
292 [ + - ]: 1547 : data_stream << allow_witness(*opt_tx);
293 [ - + + - : 1547 : r = UniValue{HexStr(data_stream)};
+ - ]
294 [ + - ]: 3636 : },
295 : 20167 : [&] {
296 : : // base64 encoded psbt
297 : 20167 : std::optional<PartiallySignedTransaction> opt_psbt = ConsumeDeserializableConstructor<PartiallySignedTransaction>(fuzzed_data_provider);
298 [ + + ]: 20167 : if (!opt_psbt) {
299 : 1409 : good_data = false;
300 : 1409 : return;
301 : : }
302 [ + - ]: 18758 : DataStream data_stream{};
303 [ + - ]: 18758 : data_stream << *opt_psbt;
304 [ - + + - : 18758 : r = UniValue{EncodeBase64(data_stream)};
+ - ]
305 : 20167 : },
306 : 6511 : [&] {
307 : : // base58 encoded key
308 : 6511 : CKey key = ConsumePrivateKey(fuzzed_data_provider);
309 [ + + ]: 6511 : if (!key.IsValid()) {
310 : 11 : good_data = false;
311 : 11 : return;
312 : : }
313 [ + - + - ]: 6500 : r = UniValue{EncodeSecret(key)};
314 : 6511 : },
315 : 3703 : [&] {
316 : : // hex encoded pubkey
317 : 3703 : CKey key = ConsumePrivateKey(fuzzed_data_provider);
318 [ + + ]: 3703 : if (!key.IsValid()) {
319 : 4 : good_data = false;
320 : 4 : return;
321 : : }
322 [ + - + - : 3699 : r = UniValue{HexStr(key.GetPubKey())};
+ - ]
323 : 3703 : });
324 : 529714 : return r;
325 : 0 : }
326 : :
327 : : constexpr int MAX_RPC_ARGUMENT_NESTING{9};
328 : :
329 : : // NOLINTBEGIN(misc-no-recursion)
330 : 757591 : UniValue ConsumeRPCArgument(FuzzedDataProvider& fuzzed_data_provider, bool& good_data, int nesting_depth)
331 : : {
332 [ + + ]: 757591 : if (nesting_depth == 0) {
333 : 453902 : return ConsumeBasicRPCArgument(fuzzed_data_provider, good_data);
334 : : }
335 [ + - ]: 303689 : UniValue argument{};
336 : 303689 : std::vector<std::function<void()>> mks{
337 : 75812 : [&] { argument = ConsumeBasicRPCArgument(fuzzed_data_provider, good_data); },
338 : 428771 : [&] {
339 : 125082 : argument = UniValue(UniValue::VARR);
340 [ + + + + : 551456 : LIMITED_WHILE (good_data && fuzzed_data_provider.ConsumeBool(), 100) {
+ + ]
341 [ + - ]: 426374 : argument.push_back(ConsumeRPCArgument(fuzzed_data_provider, good_data, nesting_depth - 1));
342 : : }
343 : 125082 : },
344 : 406484 : [&] {
345 : 102795 : argument = UniValue(UniValue::VOBJ);
346 [ + + + + : 409962 : LIMITED_WHILE (good_data && fuzzed_data_provider.ConsumeBool(), 100) {
+ + ]
347 [ + - + - ]: 307167 : argument.pushKV(fuzzed_data_provider.ConsumeRandomLengthString(128),
348 : 614334 : ConsumeRPCArgument(fuzzed_data_provider, good_data, nesting_depth - 1));
349 : : }
350 : 102795 : },
351 [ + - + + : 1518445 : };
- - ]
352 [ + - ]: 303689 : PickValue(fuzzed_data_provider, mks)();
353 : 303689 : return argument;
354 [ + - + - : 607378 : }
+ - - - ]
355 : : // NOLINTEND(misc-no-recursion)
356 : :
357 : 1 : RPCFuzzTestingSetup* InitializeRPCFuzzTestingSetup()
358 : : {
359 [ + - + - : 1 : static const auto setup = MakeNoLogFileContext<RPCFuzzTestingSetup>();
+ - ]
360 : 1 : SetRPCWarmupFinished();
361 : 1 : return setup.get();
362 : : }
363 : : }; // namespace
364 : :
365 : 1 : void initialize_rpc()
366 : : {
367 : 1 : rpc_testing_setup = InitializeRPCFuzzTestingSetup();
368 : 1 : const std::vector<std::string> supported_rpc_commands = rpc_testing_setup->GetRPCCommands();
369 [ + + ]: 116 : for (const std::string& rpc_command : supported_rpc_commands) {
370 : 115 : 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();
371 [ - + ]: 115 : 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();
372 [ - + ]: 115 : if (!(safe_for_fuzzing || not_safe_for_fuzzing)) {
373 [ # # # # : 0 : 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";
# # # # #
# ]
374 : 0 : std::terminate();
375 : : }
376 [ - + ]: 115 : if (safe_for_fuzzing && not_safe_for_fuzzing) {
377 [ # # # # : 0 : 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";
# # # # #
# ]
378 : 0 : std::terminate();
379 : : }
380 : : }
381 : 1 : const char* limit_to_rpc_command_env = std::getenv("LIMIT_TO_RPC_COMMAND");
382 [ - + ]: 1 : if (limit_to_rpc_command_env != nullptr) {
383 [ # # ]: 0 : g_limit_to_rpc_command = std::string{limit_to_rpc_command_env};
384 : : }
385 : 1 : }
386 : :
387 [ + - ]: 16353 : FUZZ_TARGET(rpc, .init = initialize_rpc)
388 : : {
389 : 15877 : SeedRandomStateForTest(SeedRand::ZEROS);
390 : 15877 : FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
391 : 15877 : bool good_data{true};
392 : 15877 : FakeNodeClock clock{ConsumeTime(fuzzed_data_provider)};
393 [ + - ]: 15877 : const std::string rpc_command = fuzzed_data_provider.ConsumeRandomLengthString(64);
394 [ - + - - ]: 15877 : if (!g_limit_to_rpc_command.empty() && rpc_command != g_limit_to_rpc_command) {
395 : : return;
396 : : }
397 [ + + ]: 15877 : 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();
398 [ + + ]: 15877 : if (!safe_for_fuzzing) {
399 : : return;
400 : : }
401 : 15376 : UniValue arguments(UniValue::VARR);
402 [ + + + + : 74114 : LIMITED_WHILE (good_data && fuzzed_data_provider.ConsumeBool(), 100) {
+ + ]
403 [ + - + - ]: 24050 : arguments.push_back(ConsumeRPCArgument(fuzzed_data_provider, good_data, MAX_RPC_ARGUMENT_NESTING));
404 : : }
405 : 15376 : try {
406 : 15376 : std::optional<test_only_CheckFailuresAreExceptionsNotAborts> maybe_mock{};
407 [ + + ]: 15376 : if (rpc_command == "echo") {
408 : : // Avoid aborting fuzzing for this specific test-only RPC with an
409 : : // intentional trigger_internal_bug
410 : 157 : maybe_mock.emplace();
411 : : }
412 [ + + ]: 15376 : rpc_testing_setup->CallRPC(rpc_command, std::move(arguments));
413 [ - + ]: 15376 : } catch (const UniValue& json_rpc_error) {
414 [ + - + - : 10710 : const std::string error_msg{json_rpc_error.find_value("message").get_str()};
- + ]
415 [ - + - + ]: 10710 : if (error_msg.starts_with("Internal bug detected")) {
416 : : // Only allow the intentional internal bug
417 [ - - ]: 0 : assert(error_msg.find("trigger_internal_bug") != std::string::npos);
418 : : }
419 : 10710 : }
420 : 15877 : }
|