Coverage Report

Created: 2025-06-10 13:21

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