Bitcoin Core 29.99.0
P2P Digital Currency
httprpc.cpp
Go to the documentation of this file.
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>
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
31
33static const char* WWW_AUTH_HEADER_DATA = "Basic realm=\"jsonrpc\"";
34
39{
40public:
41 HTTPRPCTimer(struct event_base* eventBase, std::function<void()>& func, int64_t millis) :
42 ev(eventBase, false, func)
43 {
44 struct timeval tv;
45 tv.tv_sec = millis/1000;
46 tv.tv_usec = (millis%1000)*1000;
47 ev.trigger(&tv);
48 }
49private:
51};
52
54{
55public:
56 explicit HTTPRPCTimerInterface(struct event_base* _base) : base(_base)
57 {
58 }
59 const char* Name() override
60 {
61 return "HTTP";
62 }
63 RPCTimerBase* NewTimer(std::function<void()>& func, int64_t millis) override
64 {
65 return new HTTPRPCTimer(base, func, millis);
66 }
67private:
68 struct event_base* base;
69};
70
71
72/* Stored RPC timer interface (for unregistration) */
73static std::unique_ptr<HTTPRPCTimerInterface> httpRPCTimerInterface;
74/* List of -rpcauth values */
75static std::vector<std::vector<std::string>> g_rpcauth;
76/* RPC Auth Whitelist */
77static std::map<std::string, std::set<std::string>> g_rpc_whitelist;
78static bool g_rpc_whitelist_default = false;
79
80static void JSONErrorReply(HTTPRequest* req, UniValue objError, const JSONRPCRequest& jreq)
81{
82 // Sending HTTP errors is a legacy JSON-RPC behavior.
84
85 // Send error reply from json-rpc error object
86 int nStatus = HTTP_INTERNAL_SERVER_ERROR;
87 int code = objError.find_value("code").getInt<int>();
88
89 if (code == RPC_INVALID_REQUEST)
90 nStatus = HTTP_BAD_REQUEST;
91 else if (code == RPC_METHOD_NOT_FOUND)
92 nStatus = HTTP_NOT_FOUND;
93
94 std::string strReply = JSONRPCReplyObj(NullUniValue, std::move(objError), jreq.id, jreq.m_json_version).write() + "\n";
95
96 req->WriteHeader("Content-Type", "application/json");
97 req->WriteReply(nStatus, strReply);
98}
99
100//This function checks username and password against -rpcauth
101//entries from config file.
102static bool CheckUserAuthorized(std::string_view user, std::string_view pass)
103{
104 for (const auto& fields : g_rpcauth) {
105 if (!TimingResistantEqual(std::string_view(fields[0]), user)) {
106 continue;
107 }
108
109 const std::string& salt = fields[1];
110 const std::string& hash = fields[2];
111
112 std::array<unsigned char, CHMAC_SHA256::OUTPUT_SIZE> out;
113 CHMAC_SHA256(UCharCast(salt.data()), salt.size()).Write(UCharCast(pass.data()), pass.size()).Finalize(out.data());
114 std::string hash_from_pass = HexStr(out);
115
116 if (TimingResistantEqual(hash_from_pass, hash)) {
117 return true;
118 }
119 }
120 return false;
121}
122
123static bool RPCAuthorized(const std::string& strAuth, std::string& strAuthUsernameOut)
124{
125 if (!strAuth.starts_with("Basic "))
126 return false;
127 std::string_view strUserPass64 = TrimStringView(std::string_view{strAuth}.substr(6));
128 auto userpass_data = DecodeBase64(strUserPass64);
129 std::string strUserPass;
130 if (!userpass_data) return false;
131 strUserPass.assign(userpass_data->begin(), userpass_data->end());
132
133 size_t colon_pos = strUserPass.find(':');
134 if (colon_pos == std::string::npos) {
135 return false; // Invalid basic auth.
136 }
137 std::string user = strUserPass.substr(0, colon_pos);
138 std::string pass = strUserPass.substr(colon_pos + 1);
139 strAuthUsernameOut = user;
140 return CheckUserAuthorized(user, pass);
141}
142
143static bool HTTPReq_JSONRPC(const std::any& context, HTTPRequest* req)
144{
145 // JSONRPC handles only POST
146 if (req->GetRequestMethod() != HTTPRequest::POST) {
147 req->WriteReply(HTTP_BAD_METHOD, "JSONRPC server handles only POST requests");
148 return false;
149 }
150 // Check authorization
151 std::pair<bool, std::string> authHeader = req->GetHeader("authorization");
152 if (!authHeader.first) {
153 req->WriteHeader("WWW-Authenticate", WWW_AUTH_HEADER_DATA);
155 return false;
156 }
157
158 JSONRPCRequest jreq;
159 jreq.context = context;
160 jreq.peerAddr = req->GetPeer().ToStringAddrPort();
161 if (!RPCAuthorized(authHeader.second, jreq.authUser)) {
162 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 UninterruptibleSleep(std::chrono::milliseconds{250});
168
169 req->WriteHeader("WWW-Authenticate", WWW_AUTH_HEADER_DATA);
171 return false;
172 }
173
174 try {
175 // Parse request
176 UniValue valRequest;
177 if (!valRequest.read(req->ReadBody()))
178 throw JSONRPCError(RPC_PARSE_ERROR, "Parse error");
179
180 // Set the URI
181 jreq.URI = req->GetURI();
182
183 UniValue reply;
184 bool user_has_whitelist = g_rpc_whitelist.count(jreq.authUser);
185 if (!user_has_whitelist && g_rpc_whitelist_default) {
186 LogPrintf("RPC User %s not allowed to call any methods\n", jreq.authUser);
188 return false;
189
190 // singleton request
191 } else if (valRequest.isObject()) {
192 jreq.parse(valRequest);
193 if (user_has_whitelist && !g_rpc_whitelist[jreq.authUser].count(jreq.strMethod)) {
194 LogPrintf("RPC User %s not allowed to call method %s\n", jreq.authUser, jreq.strMethod);
196 return false;
197 }
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 const bool catch_errors{jreq.m_json_version == JSONRPCVersion::V2};
204 reply = JSONRPCExec(jreq, catch_errors);
205
206 if (jreq.IsNotification()) {
207 // Even though we do execute notifications, we do not respond to them
209 return true;
210 }
211
212 // array of requests
213 } else if (valRequest.isArray()) {
214 // Check authorization for each request's method
215 if (user_has_whitelist) {
216 for (unsigned int reqIdx = 0; reqIdx < valRequest.size(); reqIdx++) {
217 if (!valRequest[reqIdx].isObject()) {
218 throw JSONRPCError(RPC_INVALID_REQUEST, "Invalid Request object");
219 } else {
220 const UniValue& request = valRequest[reqIdx].get_obj();
221 // Parse method
222 std::string strMethod = request.find_value("method").get_str();
223 if (!g_rpc_whitelist[jreq.authUser].count(strMethod)) {
224 LogPrintf("RPC User %s not allowed to call method %s\n", jreq.authUser, strMethod);
226 return false;
227 }
228 }
229 }
230 }
231
232 // Execute each request
233 reply = UniValue::VARR;
234 for (size_t i{0}; i < valRequest.size(); ++i) {
235 // Batches never throw HTTP errors, they are always just included
236 // in "HTTP OK" responses. Notifications never get any response.
237 UniValue response;
238 try {
239 jreq.parse(valRequest[i]);
240 response = JSONRPCExec(jreq, /*catch_errors=*/true);
241 } catch (UniValue& e) {
242 response = JSONRPCReplyObj(NullUniValue, std::move(e), jreq.id, jreq.m_json_version);
243 } catch (const std::exception& e) {
244 response = JSONRPCReplyObj(NullUniValue, JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id, jreq.m_json_version);
245 }
246 if (!jreq.IsNotification()) {
247 reply.push_back(std::move(response));
248 }
249 }
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 if (reply.size() == 0 && valRequest.size() > 0) {
261 return true;
262 }
263 }
264 else
265 throw JSONRPCError(RPC_PARSE_ERROR, "Top-level object parse error");
266
267 req->WriteHeader("Content-Type", "application/json");
268 req->WriteReply(HTTP_OK, reply.write() + "\n");
269 } catch (UniValue& e) {
270 JSONErrorReply(req, std::move(e), jreq);
271 return false;
272 } catch (const std::exception& e) {
273 JSONErrorReply(req, JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq);
274 return false;
275 }
276 return true;
277}
278
280{
281 std::string user;
282 std::string pass;
283
284 if (gArgs.GetArg("-rpcpassword", "") == "")
285 {
286 std::optional<fs::perms> cookie_perms{std::nullopt};
287 auto cookie_perms_arg{gArgs.GetArg("-rpccookieperms")};
288 if (cookie_perms_arg) {
289 auto perm_opt = InterpretPermString(*cookie_perms_arg);
290 if (!perm_opt) {
291 LogError("Invalid -rpccookieperms=%s; must be one of 'owner', 'group', or 'all'.", *cookie_perms_arg);
292 return false;
293 }
294 cookie_perms = *perm_opt;
295 }
296
297 switch (GenerateAuthCookie(cookie_perms, user, pass)) {
299 return false;
301 LogInfo("RPC authentication cookie file generation is disabled.");
302 break;
304 LogInfo("Using random cookie authentication.");
305 break;
306 }
307 } else {
308 LogInfo("Using rpcuser/rpcpassword authentication.");
309 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 user = gArgs.GetArg("-rpcuser", "");
311 pass = gArgs.GetArg("-rpcpassword", "");
312 }
313
314 // If there is a plaintext credential, hash it with a random salt before storage.
315 if (!user.empty() || !pass.empty()) {
316 // Generate a random 16 byte hex salt.
317 std::array<unsigned char, 16> raw_salt;
318 GetStrongRandBytes(raw_salt);
319 std::string salt = HexStr(raw_salt);
320
321 // Compute HMAC.
322 std::array<unsigned char, CHMAC_SHA256::OUTPUT_SIZE> out;
323 CHMAC_SHA256(UCharCast(salt.data()), salt.size()).Write(UCharCast(pass.data()), pass.size()).Finalize(out.data());
324 std::string hash = HexStr(out);
325
326 g_rpcauth.push_back({user, salt, hash});
327 }
328
329 if (!gArgs.GetArgs("-rpcauth").empty()) {
330 LogInfo("Using rpcauth authentication.\n");
331 for (const std::string& rpcauth : gArgs.GetArgs("-rpcauth")) {
332 std::vector<std::string> fields{SplitString(rpcauth, ':')};
333 const std::vector<std::string> salt_hmac{SplitString(fields.back(), '$')};
334 if (fields.size() == 2 && salt_hmac.size() == 2) {
335 fields.pop_back();
336 fields.insert(fields.end(), salt_hmac.begin(), salt_hmac.end());
337 g_rpcauth.push_back(fields);
338 } else {
339 LogPrintf("Invalid -rpcauth argument.\n");
340 return false;
341 }
342 }
343 }
344
345 g_rpc_whitelist_default = gArgs.GetBoolArg("-rpcwhitelistdefault", !gArgs.GetArgs("-rpcwhitelist").empty());
346 for (const std::string& strRPCWhitelist : gArgs.GetArgs("-rpcwhitelist")) {
347 auto pos = strRPCWhitelist.find(':');
348 std::string strUser = strRPCWhitelist.substr(0, pos);
349 bool intersect = g_rpc_whitelist.count(strUser);
350 std::set<std::string>& whitelist = g_rpc_whitelist[strUser];
351 if (pos != std::string::npos) {
352 std::string strWhitelist = strRPCWhitelist.substr(pos + 1);
353 std::vector<std::string> whitelist_split = SplitString(strWhitelist, ", ");
354 std::set<std::string> new_whitelist{
355 std::make_move_iterator(whitelist_split.begin()),
356 std::make_move_iterator(whitelist_split.end())};
357 if (intersect) {
358 std::set<std::string> tmp_whitelist;
359 std::set_intersection(new_whitelist.begin(), new_whitelist.end(),
360 whitelist.begin(), whitelist.end(), std::inserter(tmp_whitelist, tmp_whitelist.end()));
361 new_whitelist = std::move(tmp_whitelist);
362 }
363 whitelist = std::move(new_whitelist);
364 }
365 }
366
367 return true;
368}
369
370bool StartHTTPRPC(const std::any& context)
371{
372 LogDebug(BCLog::RPC, "Starting HTTP RPC server\n");
374 return false;
375
376 auto handle_rpc = [context](HTTPRequest* req, const std::string&) { return HTTPReq_JSONRPC(context, req); };
377 RegisterHTTPHandler("/", true, handle_rpc);
379 RegisterHTTPHandler("/wallet/", false, handle_rpc);
380 }
381 struct event_base* eventBase = EventBase();
383 httpRPCTimerInterface = std::make_unique<HTTPRPCTimerInterface>(eventBase);
385 return true;
386}
387
389{
390 LogDebug(BCLog::RPC, "Interrupting HTTP RPC server\n");
391}
392
394{
395 LogDebug(BCLog::RPC, "Stopping HTTP RPC server\n");
396 UnregisterHTTPHandler("/", true);
398 UnregisterHTTPHandler("/wallet/", false);
399 }
402 httpRPCTimerInterface.reset();
403 }
404}
ArgsManager gArgs
Definition: args.cpp:42
#define Assume(val)
Assume is the identity function.
Definition: check.h:118
std::vector< std::string > GetArgs(const std::string &strArg) const
Return a vector of strings of the given argument.
Definition: args.cpp:362
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: args.cpp:457
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: args.cpp:507
A hasher class for HMAC-SHA-256.
Definition: hmac_sha256.h:15
CHMAC_SHA256 & Write(const unsigned char *data, size_t len)
Definition: hmac_sha256.h:24
void Finalize(unsigned char hash[OUTPUT_SIZE])
Definition: hmac_sha256.cpp:29
std::string ToStringAddrPort() const
Definition: netaddress.cpp:907
Event class.
Definition: httpserver.h:174
void trigger(struct timeval *tv)
Trigger the event.
Definition: httpserver.cpp:589
Simple one-shot callback timer to be used by the RPC mechanism to e.g.
Definition: httprpc.cpp:39
HTTPRPCTimer(struct event_base *eventBase, std::function< void()> &func, int64_t millis)
Definition: httprpc.cpp:41
HTTPEvent ev
Definition: httprpc.cpp:50
const char * Name() override
Implementation name.
Definition: httprpc.cpp:59
RPCTimerBase * NewTimer(std::function< void()> &func, int64_t millis) override
Factory function for timers.
Definition: httprpc.cpp:63
struct event_base * base
Definition: httprpc.cpp:68
HTTPRPCTimerInterface(struct event_base *_base)
Definition: httprpc.cpp:56
In-flight HTTP request.
Definition: httpserver.h:71
std::pair< bool, std::string > GetHeader(const std::string &hdr) const
Get the request header specified by hdr, or an empty string.
Definition: httpserver.cpp:611
std::string GetURI() const
Get requested URI.
Definition: httpserver.cpp:704
void WriteReply(int nStatus, std::string_view reply="")
Write HTTP reply.
Definition: httpserver.h:141
void WriteHeader(const std::string &hdr, const std::string &value)
Write output header.
Definition: httpserver.cpp:642
RequestMethod GetRequestMethod() const
Get request method.
Definition: httpserver.cpp:709
std::string ReadBody()
Read request body.
Definition: httpserver.cpp:622
CService GetPeer() const
Get CService (address:ip) for the origin of the http request.
Definition: httpserver.cpp:684
std::string strMethod
Definition: request.h:56
JSONRPCVersion m_json_version
Definition: request.h:63
bool IsNotification() const
Definition: request.h:66
std::string peerAddr
Definition: request.h:61
void parse(const UniValue &valRequest)
Definition: request.cpp:199
std::string URI
Definition: request.h:59
std::optional< UniValue > id
Definition: request.h:55
std::string authUser
Definition: request.h:60
std::any context
Definition: request.h:62
Opaque base class for timers returned by NewTimerFunc.
Definition: server.h:43
RPC timer "driver".
Definition: server.h:52
void push_back(UniValue val)
Definition: univalue.cpp:104
const std::string & get_str() const
bool isArray() const
Definition: univalue.h:85
const UniValue & find_value(std::string_view key) const
Definition: univalue.cpp:233
@ VARR
Definition: univalue.h:24
std::string write(unsigned int prettyIndent=0, unsigned int indentLevel=0) const
const UniValue & get_obj() const
size_t size() const
Definition: univalue.h:71
bool read(std::string_view raw)
Int getInt() const
Definition: univalue.h:138
bool isObject() const
Definition: univalue.h:86
virtual bool HasWalletSupport() const =0
Is the wallet component enabled.
const WalletInitInterface & g_wallet_init_interface
Definition: dummywallet.cpp:56
std::optional< fs::perms > InterpretPermString(const std::string &s)
Interpret a custom permissions level string as fs::perms.
Definition: fs_helpers.cpp:297
std::string HexStr(const std::span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
Definition: hex_base.cpp:29
static const char * WWW_AUTH_HEADER_DATA
WWW-Authenticate to present with 401 Unauthorized response.
Definition: httprpc.cpp:33
void InterruptHTTPRPC()
Interrupt HTTP RPC subsystem.
Definition: httprpc.cpp:388
void StopHTTPRPC()
Stop HTTP RPC subsystem.
Definition: httprpc.cpp:393
static std::unique_ptr< HTTPRPCTimerInterface > httpRPCTimerInterface
Definition: httprpc.cpp:73
static bool CheckUserAuthorized(std::string_view user, std::string_view pass)
Definition: httprpc.cpp:102
bool StartHTTPRPC(const std::any &context)
Start HTTP RPC subsystem.
Definition: httprpc.cpp:370
static bool g_rpc_whitelist_default
Definition: httprpc.cpp:78
static bool RPCAuthorized(const std::string &strAuth, std::string &strAuthUsernameOut)
Definition: httprpc.cpp:123
static std::vector< std::vector< std::string > > g_rpcauth
Definition: httprpc.cpp:75
static bool HTTPReq_JSONRPC(const std::any &context, HTTPRequest *req)
Definition: httprpc.cpp:143
static bool InitRPCAuthentication()
Definition: httprpc.cpp:279
static std::map< std::string, std::set< std::string > > g_rpc_whitelist
Definition: httprpc.cpp:77
static void JSONErrorReply(HTTPRequest *req, UniValue objError, const JSONRPCRequest &jreq)
Definition: httprpc.cpp:80
void UnregisterHTTPHandler(const std::string &prefix, bool exactMatch)
Unregister handler for prefix.
Definition: httpserver.cpp:766
void RegisterHTTPHandler(const std::string &prefix, bool exactMatch, const HTTPRequestHandler &handler)
Register handler for prefix.
Definition: httpserver.cpp:759
static struct event_base * eventBase
HTTP module state.
Definition: httpserver.cpp:143
struct event_base * EventBase()
Return evhttp event base.
Definition: httpserver.cpp:565
#define LogWarning(...)
Definition: logging.h:262
#define LogInfo(...)
Definition: logging.h:261
#define LogError(...)
Definition: logging.h:263
#define LogDebug(category,...)
Definition: logging.h:280
#define LogPrintf(...)
Definition: logging.h:266
@ RPC
Definition: logging.h:50
std::vector< std::string > SplitString(std::string_view str, char sep)
Definition: string.h:136
std::string_view TrimStringView(std::string_view str, std::string_view pattern=" \f\n\r\t\v")
Definition: string.h:146
void GetStrongRandBytes(std::span< unsigned char > bytes) noexcept
Gather entropy from various sources, feed it into the internal PRNG, and generate random data using i...
Definition: random.cpp:607
GenerateAuthCookieResult GenerateAuthCookie(const std::optional< fs::perms > &cookie_perms, std::string &user, std::string &pass)
Generate a new RPC authentication cookie and write it to disk.
Definition: request.cpp:100
UniValue JSONRPCError(int code, const std::string &message)
Definition: request.cpp:70
UniValue JSONRPCReplyObj(UniValue result, UniValue error, std::optional< UniValue > id, JSONRPCVersion jsonrpc_version)
Definition: request.cpp:51
@ HTTP_BAD_REQUEST
Definition: protocol.h:14
@ HTTP_BAD_METHOD
Definition: protocol.h:18
@ HTTP_OK
Definition: protocol.h:12
@ HTTP_UNAUTHORIZED
Definition: protocol.h:15
@ HTTP_NOT_FOUND
Definition: protocol.h:17
@ HTTP_FORBIDDEN
Definition: protocol.h:16
@ HTTP_NO_CONTENT
Definition: protocol.h:13
@ HTTP_INTERNAL_SERVER_ERROR
Definition: protocol.h:19
@ RPC_PARSE_ERROR
Definition: protocol.h:37
@ RPC_METHOD_NOT_FOUND
Definition: protocol.h:32
@ RPC_INVALID_REQUEST
Standard JSON-RPC 2.0 errors.
Definition: protocol.h:29
void RPCUnsetTimerInterface(RPCTimerInterface *iface)
Unset factory function for timers.
Definition: server.cpp:561
UniValue JSONRPCExec(const JSONRPCRequest &jreq, bool catch_errors)
Definition: server.cpp:352
void RPCSetTimerInterface(RPCTimerInterface *iface)
Set the factory function for timers.
Definition: server.cpp:556
unsigned char * UCharCast(char *c)
Definition: span.h:95
bool TimingResistantEqual(const T &a, const T &b)
Timing-attack-resistant comparison.
Definition: strencodings.h:201
const UniValue NullUniValue
Definition: univalue.cpp:16
std::optional< std::vector< unsigned char > > DecodeBase64(std::string_view str)
void UninterruptibleSleep(const std::chrono::microseconds &n)
Definition: time.cpp:20
assert(!tx.IsCoinBase())