Bitcoin Core Fuzz Coverage Report

Coverage Report

Created: 2026-03-24 13:57

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/root/bitcoin/src/httprpc.cpp
Line
Count
Source
1
// Copyright (c) 2015-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 <httprpc.h>
6
7
#include <common/args.h>
8
#include <crypto/hmac_sha256.h>
9
#include <httpserver.h>
10
#include <logging.h>
11
#include <netaddress.h>
12
#include <rpc/protocol.h>
13
#include <rpc/server.h>
14
#include <util/fs.h>
15
#include <util/fs_helpers.h>
16
#include <util/strencodings.h>
17
#include <util/string.h>
18
#include <walletinitinterface.h>
19
20
#include <algorithm>
21
#include <iterator>
22
#include <map>
23
#include <memory>
24
#include <optional>
25
#include <set>
26
#include <string>
27
#include <vector>
28
29
using http_bitcoin::HTTPRequest;
30
using util::SplitString;
31
using util::TrimStringView;
32
33
/** WWW-Authenticate to present with 401 Unauthorized response */
34
static const char* WWW_AUTH_HEADER_DATA = "Basic realm=\"jsonrpc\"";
35
36
/* List of -rpcauth values */
37
static std::vector<std::vector<std::string>> g_rpcauth;
38
/* RPC Auth Whitelist */
39
static std::map<std::string, std::set<std::string>> g_rpc_whitelist;
40
static bool g_rpc_whitelist_default = false;
41
42
static void JSONErrorReply(HTTPRequest* req, UniValue objError, const JSONRPCRequest& jreq)
43
0
{
44
    // Sending HTTP errors is a legacy JSON-RPC behavior.
45
0
    Assume(jreq.m_json_version != JSONRPCVersion::V2);
Line
Count
Source
125
0
#define Assume(val) inline_assertion_check<false>(val, std::source_location::current(), #val)
46
47
    // Send error reply from json-rpc error object
48
0
    HTTPStatusCode nStatus = HTTP_INTERNAL_SERVER_ERROR;
49
0
    int code = objError.find_value("code").getInt<int>();
50
51
0
    if (code == RPC_INVALID_REQUEST)
52
0
        nStatus = HTTP_BAD_REQUEST;
53
0
    else if (code == RPC_METHOD_NOT_FOUND)
54
0
        nStatus = HTTP_NOT_FOUND;
55
56
0
    std::string strReply = JSONRPCReplyObj(NullUniValue, std::move(objError), jreq.id, jreq.m_json_version).write() + "\n";
57
58
0
    req->WriteHeader("Content-Type", "application/json");
59
0
    req->WriteReply(nStatus, strReply);
60
0
}
61
62
//This function checks username and password against -rpcauth
63
//entries from config file.
64
static bool CheckUserAuthorized(std::string_view user, std::string_view pass)
65
0
{
66
0
    for (const auto& fields : g_rpcauth) {
67
0
        if (!TimingResistantEqual(std::string_view(fields[0]), user)) {
68
0
            continue;
69
0
        }
70
71
0
        const std::string& salt = fields[1];
72
0
        const std::string& hash = fields[2];
73
74
0
        std::array<unsigned char, CHMAC_SHA256::OUTPUT_SIZE> out;
75
0
        CHMAC_SHA256(UCharCast(salt.data()), salt.size()).Write(UCharCast(pass.data()), pass.size()).Finalize(out.data());
76
0
        std::string hash_from_pass = HexStr(out);
77
78
0
        if (TimingResistantEqual(hash_from_pass, hash)) {
79
0
            return true;
80
0
        }
81
0
    }
82
0
    return false;
83
0
}
84
85
static bool RPCAuthorized(const std::string& strAuth, std::string& strAuthUsernameOut)
86
0
{
87
0
    if (!strAuth.starts_with("Basic "))
88
0
        return false;
89
0
    std::string_view strUserPass64 = TrimStringView(std::string_view{strAuth}.substr(6));
90
0
    auto userpass_data = DecodeBase64(strUserPass64);
91
0
    std::string strUserPass;
92
0
    if (!userpass_data) return false;
93
0
    strUserPass.assign(userpass_data->begin(), userpass_data->end());
94
95
0
    size_t colon_pos = strUserPass.find(':');
96
0
    if (colon_pos == std::string::npos) {
97
0
        return false; // Invalid basic auth.
98
0
    }
99
0
    std::string user = strUserPass.substr(0, colon_pos);
100
0
    std::string pass = strUserPass.substr(colon_pos + 1);
101
0
    strAuthUsernameOut = user;
102
0
    return CheckUserAuthorized(user, pass);
103
0
}
104
105
static bool HTTPReq_JSONRPC(const std::any& context, HTTPRequest* req)
106
0
{
107
    // JSONRPC handles only POST
108
0
    if (req->GetRequestMethod() != HTTPRequestMethod::POST) {
109
0
        req->WriteReply(HTTP_BAD_METHOD, "JSONRPC server handles only POST requests");
110
0
        return false;
111
0
    }
112
    // Check authorization
113
0
    std::pair<bool, std::string> authHeader = req->GetHeader("authorization");
114
0
    if (!authHeader.first) {
115
0
        req->WriteHeader("WWW-Authenticate", WWW_AUTH_HEADER_DATA);
116
0
        req->WriteReply(HTTP_UNAUTHORIZED);
117
0
        return false;
118
0
    }
119
120
0
    JSONRPCRequest jreq;
121
0
    jreq.context = context;
122
0
    jreq.peerAddr = req->GetPeer().ToStringAddrPort();
123
0
    if (!RPCAuthorized(authHeader.second, jreq.authUser)) {
124
0
        LogWarning("ThreadRPCServer incorrect password attempt from %s", jreq.peerAddr);
Line
Count
Source
96
0
#define LogWarning(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Warning, /*should_ratelimit=*/true, __VA_ARGS__)
Line
Count
Source
89
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(SourceLocation{__func__}, category, level, should_ratelimit, __VA_ARGS__)
125
126
        /* Deter brute-forcing
127
           If this results in a DoS the user really
128
           shouldn't have their RPC port exposed. */
129
0
        UninterruptibleSleep(std::chrono::milliseconds{250});
130
131
0
        req->WriteHeader("WWW-Authenticate", WWW_AUTH_HEADER_DATA);
132
0
        req->WriteReply(HTTP_UNAUTHORIZED);
133
0
        return false;
134
0
    }
135
136
0
    try {
137
        // Parse request
138
0
        UniValue valRequest;
139
0
        if (!valRequest.read(req->ReadBody()))
140
0
            throw JSONRPCError(RPC_PARSE_ERROR, "Parse error");
141
142
        // Set the URI
143
0
        jreq.URI = req->GetURI();
144
145
0
        UniValue reply;
146
0
        bool user_has_whitelist = g_rpc_whitelist.contains(jreq.authUser);
147
0
        if (!user_has_whitelist && g_rpc_whitelist_default) {
148
0
            LogWarning("RPC User %s not allowed to call any methods", jreq.authUser);
Line
Count
Source
96
0
#define LogWarning(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Warning, /*should_ratelimit=*/true, __VA_ARGS__)
Line
Count
Source
89
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(SourceLocation{__func__}, category, level, should_ratelimit, __VA_ARGS__)
149
0
            req->WriteReply(HTTP_FORBIDDEN);
150
0
            return false;
151
152
        // singleton request
153
0
        } else if (valRequest.isObject()) {
154
0
            jreq.parse(valRequest);
155
0
            if (user_has_whitelist && !g_rpc_whitelist[jreq.authUser].contains(jreq.strMethod)) {
156
0
                LogWarning("RPC User %s not allowed to call method %s", jreq.authUser, jreq.strMethod);
Line
Count
Source
96
0
#define LogWarning(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Warning, /*should_ratelimit=*/true, __VA_ARGS__)
Line
Count
Source
89
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(SourceLocation{__func__}, category, level, should_ratelimit, __VA_ARGS__)
157
0
                req->WriteReply(HTTP_FORBIDDEN);
158
0
                return false;
159
0
            }
160
161
            // Legacy 1.0/1.1 behavior is for failed requests to throw
162
            // exceptions which return HTTP errors and RPC errors to the client.
163
            // 2.0 behavior is to catch exceptions and return HTTP success with
164
            // RPC errors, as long as there is not an actual HTTP server error.
165
0
            const bool catch_errors{jreq.m_json_version == JSONRPCVersion::V2};
166
0
            reply = JSONRPCExec(jreq, catch_errors);
167
168
0
            if (jreq.IsNotification()) {
169
                // Even though we do execute notifications, we do not respond to them
170
0
                req->WriteReply(HTTP_NO_CONTENT);
171
0
                return true;
172
0
            }
173
174
        // array of requests
175
0
        } else if (valRequest.isArray()) {
176
            // Check authorization for each request's method
177
0
            if (user_has_whitelist) {
178
0
                for (unsigned int reqIdx = 0; reqIdx < valRequest.size(); reqIdx++) {
179
0
                    if (!valRequest[reqIdx].isObject()) {
180
0
                        throw JSONRPCError(RPC_INVALID_REQUEST, "Invalid Request object");
181
0
                    } else {
182
0
                        const UniValue& request = valRequest[reqIdx].get_obj();
183
                        // Parse method
184
0
                        std::string strMethod = request.find_value("method").get_str();
185
0
                        if (!g_rpc_whitelist[jreq.authUser].contains(strMethod)) {
186
0
                            LogWarning("RPC User %s not allowed to call method %s", jreq.authUser, strMethod);
Line
Count
Source
96
0
#define LogWarning(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Warning, /*should_ratelimit=*/true, __VA_ARGS__)
Line
Count
Source
89
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(SourceLocation{__func__}, category, level, should_ratelimit, __VA_ARGS__)
187
0
                            req->WriteReply(HTTP_FORBIDDEN);
188
0
                            return false;
189
0
                        }
190
0
                    }
191
0
                }
192
0
            }
193
194
            // Execute each request
195
0
            reply = UniValue::VARR;
196
0
            for (size_t i{0}; i < valRequest.size(); ++i) {
197
                // Batches never throw HTTP errors, they are always just included
198
                // in "HTTP OK" responses. Notifications never get any response.
199
0
                UniValue response;
200
0
                try {
201
0
                    jreq.parse(valRequest[i]);
202
0
                    response = JSONRPCExec(jreq, /*catch_errors=*/true);
203
0
                } catch (UniValue& e) {
204
0
                    response = JSONRPCReplyObj(NullUniValue, std::move(e), jreq.id, jreq.m_json_version);
205
0
                } catch (const std::exception& e) {
206
0
                    response = JSONRPCReplyObj(NullUniValue, JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id, jreq.m_json_version);
207
0
                }
208
0
                if (!jreq.IsNotification()) {
209
0
                    reply.push_back(std::move(response));
210
0
                }
211
0
            }
212
            // Return no response for an all-notification batch, but only if the
213
            // batch request is non-empty. Technically according to the JSON-RPC
214
            // 2.0 spec, an empty batch request should also return no response,
215
            // However, if the batch request is empty, it means the request did
216
            // not contain any JSON-RPC version numbers, so returning an empty
217
            // response could break backwards compatibility with old RPC clients
218
            // relying on previous behavior. Return an empty array instead of an
219
            // empty response in this case to favor being backwards compatible
220
            // over complying with the JSON-RPC 2.0 spec in this case.
221
0
            if (reply.size() == 0 && valRequest.size() > 0) {
222
0
                req->WriteReply(HTTP_NO_CONTENT);
223
0
                return true;
224
0
            }
225
0
        }
226
0
        else
227
0
            throw JSONRPCError(RPC_PARSE_ERROR, "Top-level object parse error");
228
229
0
        req->WriteHeader("Content-Type", "application/json");
230
0
        req->WriteReply(HTTP_OK, reply.write() + "\n");
231
0
    } catch (UniValue& e) {
232
0
        JSONErrorReply(req, std::move(e), jreq);
233
0
        return false;
234
0
    } catch (const std::exception& e) {
235
0
        JSONErrorReply(req, JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq);
236
0
        return false;
237
0
    }
238
0
    return true;
239
0
}
240
241
static bool InitRPCAuthentication()
242
0
{
243
0
    std::string user;
244
0
    std::string pass;
245
246
0
    if (gArgs.GetArg("-rpcpassword", "") == "")
247
0
    {
248
0
        std::optional<fs::perms> cookie_perms{std::nullopt};
249
0
        auto cookie_perms_arg{gArgs.GetArg("-rpccookieperms")};
250
0
        if (cookie_perms_arg) {
251
0
            auto perm_opt = InterpretPermString(*cookie_perms_arg);
252
0
            if (!perm_opt) {
253
0
                LogError("Invalid -rpccookieperms=%s; must be one of 'owner', 'group', or 'all'.", *cookie_perms_arg);
Line
Count
Source
97
0
#define LogError(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Error, /*should_ratelimit=*/true, __VA_ARGS__)
Line
Count
Source
89
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(SourceLocation{__func__}, category, level, should_ratelimit, __VA_ARGS__)
254
0
                return false;
255
0
            }
256
0
            cookie_perms = *perm_opt;
257
0
        }
258
259
0
        switch (GenerateAuthCookie(cookie_perms, user, pass)) {
260
0
        case GenerateAuthCookieResult::ERR:
261
0
            return false;
262
0
        case GenerateAuthCookieResult::DISABLED:
263
0
            LogInfo("RPC authentication cookie file generation is disabled.");
Line
Count
Source
95
0
#define LogInfo(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Info, /*should_ratelimit=*/true, __VA_ARGS__)
Line
Count
Source
89
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(SourceLocation{__func__}, category, level, should_ratelimit, __VA_ARGS__)
264
0
            break;
265
0
        case GenerateAuthCookieResult::OK:
266
0
            LogInfo("Using random cookie authentication.");
Line
Count
Source
95
0
#define LogInfo(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Info, /*should_ratelimit=*/true, __VA_ARGS__)
Line
Count
Source
89
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(SourceLocation{__func__}, category, level, should_ratelimit, __VA_ARGS__)
267
0
            break;
268
0
        }
269
0
    } else {
270
0
        LogInfo("Using rpcuser/rpcpassword authentication.");
Line
Count
Source
95
0
#define LogInfo(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Info, /*should_ratelimit=*/true, __VA_ARGS__)
Line
Count
Source
89
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(SourceLocation{__func__}, category, level, should_ratelimit, __VA_ARGS__)
271
0
        LogWarning("The use of rpcuser/rpcpassword is less secure, because credentials are configured in plain text. It is recommended that locally-run instances switch to cookie-based auth, or otherwise to use hashed rpcauth credentials. See share/rpcauth in the source directory for more information.");
Line
Count
Source
96
0
#define LogWarning(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Warning, /*should_ratelimit=*/true, __VA_ARGS__)
Line
Count
Source
89
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(SourceLocation{__func__}, category, level, should_ratelimit, __VA_ARGS__)
272
0
        user = gArgs.GetArg("-rpcuser", "");
273
0
        pass = gArgs.GetArg("-rpcpassword", "");
274
0
    }
275
276
    // If there is a plaintext credential, hash it with a random salt before storage.
277
0
    if (!user.empty() || !pass.empty()) {
278
        // Generate a random 16 byte hex salt.
279
0
        std::array<unsigned char, 16> raw_salt;
280
0
        GetStrongRandBytes(raw_salt);
281
0
        std::string salt = HexStr(raw_salt);
282
283
        // Compute HMAC.
284
0
        std::array<unsigned char, CHMAC_SHA256::OUTPUT_SIZE> out;
285
0
        CHMAC_SHA256(UCharCast(salt.data()), salt.size()).Write(UCharCast(pass.data()), pass.size()).Finalize(out.data());
286
0
        std::string hash = HexStr(out);
287
288
0
        g_rpcauth.push_back({user, salt, hash});
289
0
    }
290
291
0
    if (!gArgs.GetArgs("-rpcauth").empty()) {
292
0
        LogInfo("Using rpcauth authentication.\n");
Line
Count
Source
95
0
#define LogInfo(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Info, /*should_ratelimit=*/true, __VA_ARGS__)
Line
Count
Source
89
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(SourceLocation{__func__}, category, level, should_ratelimit, __VA_ARGS__)
293
0
        for (const std::string& rpcauth : gArgs.GetArgs("-rpcauth")) {
294
0
            std::vector<std::string> fields{SplitString(rpcauth, ':')};
295
0
            const std::vector<std::string> salt_hmac{SplitString(fields.back(), '$')};
296
0
            if (fields.size() == 2 && salt_hmac.size() == 2) {
297
0
                fields.pop_back();
298
0
                fields.insert(fields.end(), salt_hmac.begin(), salt_hmac.end());
299
0
                g_rpcauth.push_back(fields);
300
0
            } else {
301
0
                LogWarning("Invalid -rpcauth argument.");
Line
Count
Source
96
0
#define LogWarning(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Warning, /*should_ratelimit=*/true, __VA_ARGS__)
Line
Count
Source
89
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(SourceLocation{__func__}, category, level, should_ratelimit, __VA_ARGS__)
302
0
                return false;
303
0
            }
304
0
        }
305
0
    }
306
307
0
    g_rpc_whitelist_default = gArgs.GetBoolArg("-rpcwhitelistdefault", !gArgs.GetArgs("-rpcwhitelist").empty());
308
0
    for (const std::string& strRPCWhitelist : gArgs.GetArgs("-rpcwhitelist")) {
309
0
        auto pos = strRPCWhitelist.find(':');
310
0
        std::string strUser = strRPCWhitelist.substr(0, pos);
311
0
        bool intersect = g_rpc_whitelist.contains(strUser);
312
0
        std::set<std::string>& whitelist = g_rpc_whitelist[strUser];
313
0
        if (pos != std::string::npos) {
314
0
            std::string strWhitelist = strRPCWhitelist.substr(pos + 1);
315
0
            std::vector<std::string> whitelist_split = SplitString(strWhitelist, ", ");
316
0
            std::set<std::string> new_whitelist{
317
0
                std::make_move_iterator(whitelist_split.begin()),
318
0
                std::make_move_iterator(whitelist_split.end())};
319
0
            if (intersect) {
320
0
                std::set<std::string> tmp_whitelist;
321
0
                std::set_intersection(new_whitelist.begin(), new_whitelist.end(),
322
0
                       whitelist.begin(), whitelist.end(), std::inserter(tmp_whitelist, tmp_whitelist.end()));
323
0
                new_whitelist = std::move(tmp_whitelist);
324
0
            }
325
0
            whitelist = std::move(new_whitelist);
326
0
        }
327
0
    }
328
329
0
    return true;
330
0
}
331
332
bool StartHTTPRPC(const std::any& context)
333
0
{
334
0
    LogDebug(BCLog::RPC, "Starting HTTP RPC server\n");
Line
Count
Source
115
0
#define LogDebug(category, ...) detail_LogIfCategoryAndLevelEnabled(category, BCLog::Level::Debug, __VA_ARGS__)
Line
Count
Source
106
0
    do {                                                               \
107
0
        if (util::log::ShouldLog((category), (level))) {               \
108
0
            bool rate_limit{level >= BCLog::Level::Info};              \
109
0
            Assume(!rate_limit); /*Only called with the levels below*/ \
Line
Count
Source
125
0
#define Assume(val) inline_assertion_check<false>(val, std::source_location::current(), #val)
110
0
            LogPrintLevel_(category, level, rate_limit, __VA_ARGS__);  \
Line
Count
Source
89
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(SourceLocation{__func__}, category, level, should_ratelimit, __VA_ARGS__)
111
0
        }                                                              \
112
0
    } while (0)
335
0
    if (!InitRPCAuthentication())
336
0
        return false;
337
338
0
    auto handle_rpc = [context](HTTPRequest* req, const std::string&) { return HTTPReq_JSONRPC(context, req); };
339
0
    RegisterHTTPHandler("/", true, handle_rpc);
340
0
    if (g_wallet_init_interface.HasWalletSupport()) {
341
0
        RegisterHTTPHandler("/wallet/", false, handle_rpc);
342
0
    }
343
0
    return true;
344
0
}
345
346
void InterruptHTTPRPC()
347
0
{
348
0
    LogDebug(BCLog::RPC, "Interrupting HTTP RPC server\n");
Line
Count
Source
115
0
#define LogDebug(category, ...) detail_LogIfCategoryAndLevelEnabled(category, BCLog::Level::Debug, __VA_ARGS__)
Line
Count
Source
106
0
    do {                                                               \
107
0
        if (util::log::ShouldLog((category), (level))) {               \
108
0
            bool rate_limit{level >= BCLog::Level::Info};              \
109
0
            Assume(!rate_limit); /*Only called with the levels below*/ \
Line
Count
Source
125
0
#define Assume(val) inline_assertion_check<false>(val, std::source_location::current(), #val)
110
0
            LogPrintLevel_(category, level, rate_limit, __VA_ARGS__);  \
Line
Count
Source
89
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(SourceLocation{__func__}, category, level, should_ratelimit, __VA_ARGS__)
111
0
        }                                                              \
112
0
    } while (0)
349
0
}
350
351
void StopHTTPRPC()
352
0
{
353
0
    LogDebug(BCLog::RPC, "Stopping HTTP RPC server\n");
Line
Count
Source
115
0
#define LogDebug(category, ...) detail_LogIfCategoryAndLevelEnabled(category, BCLog::Level::Debug, __VA_ARGS__)
Line
Count
Source
106
0
    do {                                                               \
107
0
        if (util::log::ShouldLog((category), (level))) {               \
108
0
            bool rate_limit{level >= BCLog::Level::Info};              \
109
0
            Assume(!rate_limit); /*Only called with the levels below*/ \
Line
Count
Source
125
0
#define Assume(val) inline_assertion_check<false>(val, std::source_location::current(), #val)
110
0
            LogPrintLevel_(category, level, rate_limit, __VA_ARGS__);  \
Line
Count
Source
89
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(SourceLocation{__func__}, category, level, should_ratelimit, __VA_ARGS__)
111
0
        }                                                              \
112
0
    } while (0)
354
0
    UnregisterHTTPHandler("/", true);
355
0
    if (g_wallet_init_interface.HasWalletSupport()) {
356
0
        UnregisterHTTPHandler("/wallet/", false);
357
0
    }
358
0
}