Coverage Report

Created: 2024-08-21 05:08

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