Bitcoin Core 32.99.0
P2P Digital Currency
Loading...
Searching...
No Matches
httprpc.cpp
Go to the documentation of this file.
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>
9#include <httpserver.h>
10#include <netaddress.h>
11#include <rpc/protocol.h>
12#include <rpc/server.h>
13#include <util/fs.h>
14#include <util/fs_helpers.h>
15#include <util/log.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
35/* List of -rpcauth values */
36static std::vector<std::vector<std::string>> g_rpcauth;
37/* RPC Auth Whitelist */
38static std::map<std::string, std::set<std::string>> g_rpc_whitelist;
39static bool g_rpc_whitelist_default = false;
40
42{
43 // HTTP errors should never be returned if JSON-RPC v2 was requested. This
44 // function should only be called when a v1 request fails or when a request
45 // cannot be parsed, so the version is unknown.
46 Assume(jreq.m_json_version != JSONRPCVersion::V2);
47
48 // Send error reply from json-rpc error object
50 int code = objError.find_value("code").getInt<int>();
51
52 if (code == RPC_INVALID_REQUEST)
54 else if (code == RPC_METHOD_NOT_FOUND)
56
57 return JSONRPCReplyObj(NullUniValue, std::move(objError), jreq.id, jreq.m_json_version);
58}
59
60//This function checks username and password against -rpcauth
61//entries from config file.
62static bool CheckUserAuthorized(std::string_view user, std::string_view pass)
63{
64 for (const auto& fields : g_rpcauth) {
65 if (!TimingResistantEqual(std::string_view(fields[0]), user)) {
66 continue;
67 }
68
69 const std::string& salt = fields[1];
70 const std::string& hash = fields[2];
71
72 std::array<unsigned char, CHMAC_SHA256::OUTPUT_SIZE> out;
73 CHMAC_SHA256(UCharCast(salt.data()), salt.size()).Write(UCharCast(pass.data()), pass.size()).Finalize(out.data());
74 std::string hash_from_pass = HexStr(out);
75
77 return true;
78 }
79 }
80 return false;
81}
82
83static bool RPCAuthorized(const std::string& strAuth, std::string& strAuthUsernameOut)
84{
85 if (!strAuth.starts_with("Basic "))
86 return false;
87 std::string_view strUserPass64 = TrimStringView(std::string_view{strAuth}.substr(6));
89 std::string strUserPass;
90 if (!userpass_data) return false;
91 strUserPass.assign(userpass_data->begin(), userpass_data->end());
92
93 size_t colon_pos = strUserPass.find(':');
94 if (colon_pos == std::string::npos) {
95 return false; // Invalid basic auth.
96 }
97 std::string user = strUserPass.substr(0, colon_pos);
98 std::string pass = strUserPass.substr(colon_pos + 1);
100 return CheckUserAuthorized(user, pass);
101}
102
104{
105 status = HTTP_OK;
106 try {
107 bool user_has_whitelist = g_rpc_whitelist.contains(jreq.authUser);
109 LogWarning("RPC User %s not allowed to call any methods", jreq.authUser);
110 status = HTTP_FORBIDDEN;
111 return {};
112
113 // singleton request
114 } else if (valRequest.isObject()) {
115 jreq.parse(valRequest);
116 if (user_has_whitelist && !g_rpc_whitelist[jreq.authUser].contains(jreq.strMethod)) {
117 LogWarning("RPC User %s not allowed to call method %s", jreq.authUser, jreq.strMethod);
118 status = HTTP_FORBIDDEN;
119 return {};
120 }
121
122 // Legacy 1.0/1.1 behavior is for failed requests to throw
123 // exceptions which return HTTP errors and RPC errors to the client.
124 // 2.0 behavior is to catch exceptions and return HTTP success with
125 // RPC errors, as long as there is not an actual HTTP server error.
126 const bool catch_errors{jreq.m_json_version == JSONRPCVersion::V2};
128 if (jreq.IsNotification()) {
129 // Even though we do execute notifications, we do not respond to them
130 status = HTTP_NO_CONTENT;
131 return {};
132 }
133 return reply;
134 // array of requests
135 } else if (valRequest.isArray()) {
136 // Check authorization for each request's method
137 if (user_has_whitelist) {
138 for (unsigned int reqIdx = 0; reqIdx < valRequest.size(); reqIdx++) {
139 if (!valRequest[reqIdx].isObject()) {
140 throw JSONRPCError(RPC_INVALID_REQUEST, "Invalid Request object");
141 } else {
142 const UniValue& request = valRequest[reqIdx].get_obj();
143 // Parse method
144 std::string strMethod = request.find_value("method").get_str();
145 if (!g_rpc_whitelist[jreq.authUser].contains(strMethod)) {
146 LogWarning("RPC User %s not allowed to call method %s", jreq.authUser, strMethod);
147 status = HTTP_FORBIDDEN;
148 return {};
149 }
150 }
151 }
152 }
153
154 // Execute each request
155 UniValue reply = UniValue::VARR;
156 for (size_t i{0}; i < valRequest.size(); ++i) {
157 // Batches never throw HTTP errors, they are always just included
158 // in "HTTP OK" responses. Notifications never get any response.
160 // Each element gets its own copy of the unparsed request, so
161 // that nothing parsed from one element ends up in the reply to
162 // the next
164 try {
166 response = JSONRPCExec(elem_jreq, /*catch_errors=*/true);
167 } catch (UniValue& e) {
168 response = JSONRPCReplyObj(NullUniValue, std::move(e), elem_jreq.id, elem_jreq.m_json_version);
169 } catch (const std::exception& e) {
171 }
172 if (!elem_jreq.IsNotification()) {
173 reply.push_back(std::move(response));
174 }
175 }
176 // Return no response for an all-notification batch, but only if the
177 // batch request is non-empty. Technically according to the JSON-RPC
178 // 2.0 spec, an empty batch request should also return no response,
179 // However, if the batch request is empty, it means the request did
180 // not contain any JSON-RPC version numbers, so returning an empty
181 // response could break backwards compatibility with old RPC clients
182 // relying on previous behavior. Return an empty array instead of an
183 // empty response in this case to favor being backwards compatible
184 // over complying with the JSON-RPC 2.0 spec in this case.
185 if (reply.size() == 0 && valRequest.size() > 0) {
186 status = HTTP_NO_CONTENT;
187 return {};
188 }
189 return reply;
190 }
191 else
192 throw JSONRPCError(RPC_PARSE_ERROR, "Top-level object parse error");
193 } catch (UniValue& e) {
194 return JSONErrorReply(std::move(e), jreq, status);
195 } catch (const std::exception& e) {
196 return JSONErrorReply(JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq, status);
197 }
198}
199
200static void HTTPReq_JSONRPC(const std::any& context, HTTPRequest* req)
201{
202 // JSONRPC handles only POST
204 req->WriteReply(HTTP_BAD_METHOD, "JSONRPC server handles only POST requests");
205 return;
206 }
207 // Check authorization
208 std::optional<std::string> auth_header = req->GetHeader("authorization");
209 if (!auth_header) {
210 req->WriteHeader("WWW-Authenticate", WWW_AUTH_HEADER_DATA);
212 return;
213 }
214
217 jreq.peerAddr = req->GetPeer().ToStringAddrPort();
218 jreq.URI = req->GetURI();
219 if (!RPCAuthorized(*auth_header, jreq.authUser)) {
220 LogWarning("ThreadRPCServer incorrect password attempt from %s", jreq.peerAddr);
221
222 /* Deter brute-forcing
223 If this results in a DoS the user really
224 shouldn't have their RPC port exposed. */
225 UninterruptibleSleep(std::chrono::milliseconds{250});
226
227 req->WriteHeader("WWW-Authenticate", WWW_AUTH_HEADER_DATA);
229 return;
230 }
231
232 // Generate reply
233 HTTPStatusCode status;
234 UniValue reply;
235 UniValue request;
236 if (request.read(req->ReadBody())) {
237 reply = ExecuteHTTPRPC(request, jreq, status);
238 } else {
239 reply = JSONErrorReply(JSONRPCError(RPC_PARSE_ERROR, "Parse error"), jreq, status);
240 }
241
242 // Write reply
243 if (reply.isNull()) {
244 // Error case or no-content notification reply.
245 req->WriteReply(status);
246 } else {
247 req->WriteHeader("Content-Type", "application/json");
248 req->WriteReply(status, reply.write() + "\n");
249 }
250}
251
253{
254 std::string user;
255 std::string pass;
256
257 if (gArgs.GetArg("-rpcpassword", "") == "")
258 {
259 std::optional<fs::perms> cookie_perms{std::nullopt};
260 auto cookie_perms_arg{gArgs.GetArg("-rpccookieperms")};
261 if (cookie_perms_arg) {
263 if (!perm_opt) {
264 LogError("Invalid -rpccookieperms=%s; must be one of 'owner', 'group', or 'all'.", *cookie_perms_arg);
265 return false;
266 }
268 }
269
270 switch (GenerateAuthCookie(cookie_perms, user, pass)) {
272 return false;
274 LogInfo("RPC authentication cookie file generation is disabled.");
275 break;
277 LogInfo("Using random cookie authentication.");
278 break;
279 }
280 } else {
281 LogInfo("Using rpcuser/rpcpassword authentication.");
282 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.");
283 user = gArgs.GetArg("-rpcuser", "");
284 pass = gArgs.GetArg("-rpcpassword", "");
285 }
286
287 // If there is a plaintext credential, hash it with a random salt before storage.
288 if (!user.empty() || !pass.empty()) {
289 // Generate a random 16 byte hex salt.
290 std::array<unsigned char, 16> raw_salt;
292 std::string salt = HexStr(raw_salt);
293
294 // Compute HMAC.
295 std::array<unsigned char, CHMAC_SHA256::OUTPUT_SIZE> out;
296 CHMAC_SHA256(UCharCast(salt.data()), salt.size()).Write(UCharCast(pass.data()), pass.size()).Finalize(out.data());
297 std::string hash = HexStr(out);
298
299 g_rpcauth.push_back({user, salt, hash});
300 }
301
302 if (!gArgs.GetArgs("-rpcauth").empty()) {
303 LogInfo("Using rpcauth authentication.\n");
304 for (const std::string& rpcauth : gArgs.GetArgs("-rpcauth")) {
305 std::vector<std::string> fields{SplitString(rpcauth, ':')};
306 const std::vector<std::string> salt_hmac{SplitString(fields.back(), '$')};
307 if (fields.size() == 2 && salt_hmac.size() == 2) {
308 fields.pop_back();
309 fields.insert(fields.end(), salt_hmac.begin(), salt_hmac.end());
310 g_rpcauth.push_back(fields);
311 } else {
312 LogWarning("Invalid -rpcauth argument.");
313 return false;
314 }
315 }
316 }
317
318 g_rpc_whitelist_default = gArgs.GetBoolArg("-rpcwhitelistdefault", !gArgs.GetArgs("-rpcwhitelist").empty());
319 for (const std::string& strRPCWhitelist : gArgs.GetArgs("-rpcwhitelist")) {
320 auto pos = strRPCWhitelist.find(':');
321 std::string strUser = strRPCWhitelist.substr(0, pos);
322 bool intersect = g_rpc_whitelist.contains(strUser);
323 std::set<std::string>& whitelist = g_rpc_whitelist[strUser];
324 if (pos != std::string::npos) {
325 std::string strWhitelist = strRPCWhitelist.substr(pos + 1);
326 std::vector<std::string> whitelist_split = SplitString(strWhitelist, ", ");
327 std::set<std::string> new_whitelist{
328 std::make_move_iterator(whitelist_split.begin()),
329 std::make_move_iterator(whitelist_split.end())};
330 if (intersect) {
331 std::set<std::string> tmp_whitelist;
332 std::set_intersection(new_whitelist.begin(), new_whitelist.end(),
333 whitelist.begin(), whitelist.end(), std::inserter(tmp_whitelist, tmp_whitelist.end()));
334 new_whitelist = std::move(tmp_whitelist);
335 }
336 whitelist = std::move(new_whitelist);
337 }
338 }
339
340 return true;
341}
342
343bool StartHTTPRPC(const std::any& context)
344{
345 LogDebug(BCLog::RPC, "Starting HTTP RPC server\n");
347 return false;
348
349 auto handle_rpc = [context](HTTPRequest* req, const std::string&) { return HTTPReq_JSONRPC(context, req); };
352 RegisterHTTPHandler("/wallet/", false, handle_rpc);
353 }
354 return true;
355}
356
358{
359 LogDebug(BCLog::RPC, "Interrupting HTTP RPC server\n");
360}
361
363{
364 LogDebug(BCLog::RPC, "Stopping HTTP RPC server\n");
365 UnregisterHTTPHandler("/", true);
367 UnregisterHTTPHandler("/wallet/", false);
368 }
369}
ArgsManager gArgs
Definition args.cpp:39
#define Assume(val)
Assume is the identity function.
Definition check.h:131
std::vector< std::string > GetArgs(const std::string &strArg) const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Return a vector of strings of the given argument.
Definition args.cpp:423
std::string GetArg(const std::string &strArg, const std::string &strDefault) const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Return string argument or default value.
Definition args.cpp:518
bool GetBoolArg(const std::string &strArg, bool fDefault) const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Return boolean argument or default value.
Definition args.cpp:561
A hasher class for HMAC-SHA-256.
Definition hmac_sha256.h:14
CHMAC_SHA256 & Write(const unsigned char *data, size_t len)
Definition hmac_sha256.h:23
void Finalize(unsigned char hash[OUTPUT_SIZE])
std::string ToStringAddrPort() const
void WriteHeader(std::string &&hdr, std::string &&value)
std::string GetURI() const
Definition httpserver.h:189
std::optional< std::string > GetHeader(std::string_view hdr) const
HTTPRequestMethod GetRequestMethod() const
Definition httpserver.h:191
std::string ReadBody() const
Definition httpserver.h:194
void WriteReply(HTTPStatusCode status, std::span< const std::byte > reply_body={})
CService GetPeer() const
void parse(const UniValue &valRequest)
Definition request.cpp:201
std::any context
Definition request.h:64
void push_back(UniValue val)
Definition univalue.cpp:103
const std::string & get_str() const
const UniValue & find_value(std::string_view key) const
Definition univalue.cpp:232
std::string write(unsigned int prettyIndent=0, unsigned int indentLevel=0) const
bool isNull() const
Definition univalue.h:81
const UniValue & get_obj() const
size_t size() const
Definition univalue.h:71
bool read(std::string_view json)
Parse JSON; set value to null on failure.
virtual bool HasWalletSupport() const =0
Is the wallet component enabled.
const WalletInitInterface & g_wallet_init_interface
std::optional< fs::perms > InterpretPermString(const std::string &s)
Interpret a custom permissions level string as fs::perms.
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:30
static const char * WWW_AUTH_HEADER_DATA
WWW-Authenticate to present with 401 Unauthorized response.
Definition httprpc.cpp:33
UniValue ExecuteHTTPRPC(const UniValue &valRequest, JSONRPCRequest &jreq, HTTPStatusCode &status)
Execute a single HTTP request containing one or more JSONRPC requests.
Definition httprpc.cpp:103
void InterruptHTTPRPC()
Interrupt HTTP RPC subsystem.
Definition httprpc.cpp:357
void StopHTTPRPC()
Stop HTTP RPC subsystem.
Definition httprpc.cpp:362
static bool CheckUserAuthorized(std::string_view user, std::string_view pass)
Definition httprpc.cpp:62
bool StartHTTPRPC(const std::any &context)
Start HTTP RPC subsystem.
Definition httprpc.cpp:343
static bool g_rpc_whitelist_default
Definition httprpc.cpp:39
static void HTTPReq_JSONRPC(const std::any &context, HTTPRequest *req)
Definition httprpc.cpp:200
static bool RPCAuthorized(const std::string &strAuth, std::string &strAuthUsernameOut)
Definition httprpc.cpp:83
static std::vector< std::vector< std::string > > g_rpcauth
Definition httprpc.cpp:36
static bool InitRPCAuthentication()
Definition httprpc.cpp:252
static std::map< std::string, std::set< std::string > > g_rpc_whitelist
Definition httprpc.cpp:38
static UniValue JSONErrorReply(UniValue objError, const JSONRPCRequest &jreq, HTTPStatusCode &nStatus)
Definition httprpc.cpp:41
void UnregisterHTTPHandler(const std::string &prefix, bool exactMatch)
Unregister handler for prefix.
void RegisterHTTPHandler(const std::string &prefix, bool exactMatch, const HTTPRequestHandler &handler)
Register handler for prefix.
#define LogWarning(...)
Definition log.h:137
#define LogInfo(...)
Definition log.h:136
#define LogError(...)
Definition log.h:138
#define LogDebug(category,...)
Definition log.h:154
std::vector< std::string > SplitString(std::string_view str, char sep)
Definition string.h:153
std::string_view TrimStringView(std::string_view str LIFETIMEBOUND, std::string_view pattern=" \f\n\r\t\v")
Definition string.h:163
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
UniValue JSONRPCError(int code, const std::string &message)
Definition request.cpp:75
AuthCookieResult 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:105
UniValue JSONRPCReplyObj(UniValue result, UniValue error, std::optional< UniValue > id, JSONRPCVersion jsonrpc_version)
Definition request.cpp:56
HTTPStatusCode
HTTP status codes.
Definition protocol.h:13
@ HTTP_BAD_REQUEST
Definition protocol.h:16
@ HTTP_BAD_METHOD
Definition protocol.h:20
@ HTTP_OK
Definition protocol.h:14
@ HTTP_UNAUTHORIZED
Definition protocol.h:17
@ HTTP_NOT_FOUND
Definition protocol.h:19
@ HTTP_FORBIDDEN
Definition protocol.h:18
@ HTTP_NO_CONTENT
Definition protocol.h:15
@ HTTP_INTERNAL_SERVER_ERROR
Definition protocol.h:22
@ RPC_PARSE_ERROR
Definition protocol.h:62
@ RPC_METHOD_NOT_FOUND
Definition protocol.h:57
@ RPC_INVALID_REQUEST
Standard JSON-RPC 2.0 errors.
Definition protocol.h:54
UniValue JSONRPCExec(const JSONRPCRequest &jreq, bool catch_errors)
Definition server.cpp:722
unsigned char * UCharCast(char *c)
Definition span.h:95
Utilities for converting data from/to strings.
bool TimingResistantEqual(const T &a, const T &b)
Timing-attack-resistant comparison.
const UniValue NullUniValue
Definition univalue.cpp:15
std::optional< std::vector< unsigned char > > DecodeBase64(std::string_view str)
void UninterruptibleSleep(const std::chrono::microseconds &n)
Definition time.cpp:30
constexpr auto Ticks(Dur2 d)
Helper to count the seconds of a duration/time_point.
Definition time.h:82
WalletContext context