Bitcoin Core  24.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 <crypto/hmac_sha256.h>
8 #include <httpserver.h>
9 #include <rpc/protocol.h>
10 #include <rpc/server.h>
11 #include <util/strencodings.h>
12 #include <util/string.h>
13 #include <util/system.h>
14 #include <walletinitinterface.h>
15 
16 #include <algorithm>
17 #include <iterator>
18 #include <map>
19 #include <memory>
20 #include <set>
21 #include <string>
22 #include <vector>
23 
25 static const char* WWW_AUTH_HEADER_DATA = "Basic realm=\"jsonrpc\"";
26 
30 class HTTPRPCTimer : public RPCTimerBase
31 {
32 public:
33  HTTPRPCTimer(struct event_base* eventBase, std::function<void()>& func, int64_t millis) :
34  ev(eventBase, false, func)
35  {
36  struct timeval tv;
37  tv.tv_sec = millis/1000;
38  tv.tv_usec = (millis%1000)*1000;
39  ev.trigger(&tv);
40  }
41 private:
43 };
44 
46 {
47 public:
48  explicit HTTPRPCTimerInterface(struct event_base* _base) : base(_base)
49  {
50  }
51  const char* Name() override
52  {
53  return "HTTP";
54  }
55  RPCTimerBase* NewTimer(std::function<void()>& func, int64_t millis) override
56  {
57  return new HTTPRPCTimer(base, func, millis);
58  }
59 private:
60  struct event_base* base;
61 };
62 
63 
64 /* Pre-base64-encoded authentication token */
65 static std::string strRPCUserColonPass;
66 /* Stored RPC timer interface (for unregistration) */
67 static std::unique_ptr<HTTPRPCTimerInterface> httpRPCTimerInterface;
68 /* List of -rpcauth values */
69 static std::vector<std::vector<std::string>> g_rpcauth;
70 /* RPC Auth Whitelist */
71 static std::map<std::string, std::set<std::string>> g_rpc_whitelist;
72 static bool g_rpc_whitelist_default = false;
73 
74 static void JSONErrorReply(HTTPRequest* req, const UniValue& objError, const UniValue& id)
75 {
76  // Send error reply from json-rpc error object
77  int nStatus = HTTP_INTERNAL_SERVER_ERROR;
78  int code = find_value(objError, "code").getInt<int>();
79 
80  if (code == RPC_INVALID_REQUEST)
81  nStatus = HTTP_BAD_REQUEST;
82  else if (code == RPC_METHOD_NOT_FOUND)
83  nStatus = HTTP_NOT_FOUND;
84 
85  std::string strReply = JSONRPCReply(NullUniValue, objError, id);
86 
87  req->WriteHeader("Content-Type", "application/json");
88  req->WriteReply(nStatus, strReply);
89 }
90 
91 //This function checks username and password against -rpcauth
92 //entries from config file.
93 static bool multiUserAuthorized(std::string strUserPass)
94 {
95  if (strUserPass.find(':') == std::string::npos) {
96  return false;
97  }
98  std::string strUser = strUserPass.substr(0, strUserPass.find(':'));
99  std::string strPass = strUserPass.substr(strUserPass.find(':') + 1);
100 
101  for (const auto& vFields : g_rpcauth) {
102  std::string strName = vFields[0];
103  if (!TimingResistantEqual(strName, strUser)) {
104  continue;
105  }
106 
107  std::string strSalt = vFields[1];
108  std::string strHash = vFields[2];
109 
110  static const unsigned int KEY_SIZE = 32;
111  unsigned char out[KEY_SIZE];
112 
113  CHMAC_SHA256(reinterpret_cast<const unsigned char*>(strSalt.data()), strSalt.size()).Write(reinterpret_cast<const unsigned char*>(strPass.data()), strPass.size()).Finalize(out);
114  std::vector<unsigned char> hexvec(out, out+KEY_SIZE);
115  std::string strHashFromPass = HexStr(hexvec);
116 
117  if (TimingResistantEqual(strHashFromPass, strHash)) {
118  return true;
119  }
120  }
121  return false;
122 }
123 
124 static bool RPCAuthorized(const std::string& strAuth, std::string& strAuthUsernameOut)
125 {
126  if (strRPCUserColonPass.empty()) // Belt-and-suspenders measure if InitRPCAuthentication was not called
127  return false;
128  if (strAuth.substr(0, 6) != "Basic ")
129  return false;
130  std::string_view strUserPass64 = TrimStringView(std::string_view{strAuth}.substr(6));
131  auto userpass_data = DecodeBase64(strUserPass64);
132  std::string strUserPass;
133  if (!userpass_data) return false;
134  strUserPass.assign(userpass_data->begin(), userpass_data->end());
135 
136  if (strUserPass.find(':') != std::string::npos)
137  strAuthUsernameOut = strUserPass.substr(0, strUserPass.find(':'));
138 
139  //Check if authorized under single-user field
140  if (TimingResistantEqual(strUserPass, strRPCUserColonPass)) {
141  return true;
142  }
143  return multiUserAuthorized(strUserPass);
144 }
145 
146 static bool HTTPReq_JSONRPC(const std::any& context, HTTPRequest* req)
147 {
148  // JSONRPC handles only POST
149  if (req->GetRequestMethod() != HTTPRequest::POST) {
150  req->WriteReply(HTTP_BAD_METHOD, "JSONRPC server handles only POST requests");
151  return false;
152  }
153  // Check authorization
154  std::pair<bool, std::string> authHeader = req->GetHeader("authorization");
155  if (!authHeader.first) {
156  req->WriteHeader("WWW-Authenticate", WWW_AUTH_HEADER_DATA);
158  return false;
159  }
160 
161  JSONRPCRequest jreq;
162  jreq.context = context;
163  jreq.peerAddr = req->GetPeer().ToString();
164  if (!RPCAuthorized(authHeader.second, jreq.authUser)) {
165  LogPrintf("ThreadRPCServer incorrect password attempt from %s\n", jreq.peerAddr);
166 
167  /* Deter brute-forcing
168  If this results in a DoS the user really
169  shouldn't have their RPC port exposed. */
170  UninterruptibleSleep(std::chrono::milliseconds{250});
171 
172  req->WriteHeader("WWW-Authenticate", WWW_AUTH_HEADER_DATA);
174  return false;
175  }
176 
177  try {
178  // Parse request
179  UniValue valRequest;
180  if (!valRequest.read(req->ReadBody()))
181  throw JSONRPCError(RPC_PARSE_ERROR, "Parse error");
182 
183  // Set the URI
184  jreq.URI = req->GetURI();
185 
186  std::string strReply;
187  bool user_has_whitelist = g_rpc_whitelist.count(jreq.authUser);
188  if (!user_has_whitelist && g_rpc_whitelist_default) {
189  LogPrintf("RPC User %s not allowed to call any methods\n", jreq.authUser);
191  return false;
192 
193  // singleton request
194  } else if (valRequest.isObject()) {
195  jreq.parse(valRequest);
196  if (user_has_whitelist && !g_rpc_whitelist[jreq.authUser].count(jreq.strMethod)) {
197  LogPrintf("RPC User %s not allowed to call method %s\n", jreq.authUser, jreq.strMethod);
199  return false;
200  }
201  UniValue result = tableRPC.execute(jreq);
202 
203  // Send reply
204  strReply = JSONRPCReply(result, NullUniValue, jreq.id);
205 
206  // array of requests
207  } else if (valRequest.isArray()) {
208  if (user_has_whitelist) {
209  for (unsigned int reqIdx = 0; reqIdx < valRequest.size(); reqIdx++) {
210  if (!valRequest[reqIdx].isObject()) {
211  throw JSONRPCError(RPC_INVALID_REQUEST, "Invalid Request object");
212  } else {
213  const UniValue& request = valRequest[reqIdx].get_obj();
214  // Parse method
215  std::string strMethod = find_value(request, "method").get_str();
216  if (!g_rpc_whitelist[jreq.authUser].count(strMethod)) {
217  LogPrintf("RPC User %s not allowed to call method %s\n", jreq.authUser, strMethod);
219  return false;
220  }
221  }
222  }
223  }
224  strReply = JSONRPCExecBatch(jreq, valRequest.get_array());
225  }
226  else
227  throw JSONRPCError(RPC_PARSE_ERROR, "Top-level object parse error");
228 
229  req->WriteHeader("Content-Type", "application/json");
230  req->WriteReply(HTTP_OK, strReply);
231  } catch (const UniValue& objError) {
232  JSONErrorReply(req, objError, jreq.id);
233  return false;
234  } catch (const std::exception& e) {
235  JSONErrorReply(req, JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
236  return false;
237  }
238  return true;
239 }
240 
242 {
243  if (gArgs.GetArg("-rpcpassword", "") == "")
244  {
245  LogPrintf("Using random cookie authentication.\n");
247  return false;
248  }
249  } else {
250  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");
251  strRPCUserColonPass = gArgs.GetArg("-rpcuser", "") + ":" + gArgs.GetArg("-rpcpassword", "");
252  }
253  if (gArgs.GetArg("-rpcauth", "") != "") {
254  LogPrintf("Using rpcauth authentication.\n");
255  for (const std::string& rpcauth : gArgs.GetArgs("-rpcauth")) {
256  std::vector<std::string> fields{SplitString(rpcauth, ':')};
257  const std::vector<std::string> salt_hmac{SplitString(fields.back(), '$')};
258  if (fields.size() == 2 && salt_hmac.size() == 2) {
259  fields.pop_back();
260  fields.insert(fields.end(), salt_hmac.begin(), salt_hmac.end());
261  g_rpcauth.push_back(fields);
262  } else {
263  LogPrintf("Invalid -rpcauth argument.\n");
264  return false;
265  }
266  }
267  }
268 
269  g_rpc_whitelist_default = gArgs.GetBoolArg("-rpcwhitelistdefault", gArgs.IsArgSet("-rpcwhitelist"));
270  for (const std::string& strRPCWhitelist : gArgs.GetArgs("-rpcwhitelist")) {
271  auto pos = strRPCWhitelist.find(':');
272  std::string strUser = strRPCWhitelist.substr(0, pos);
273  bool intersect = g_rpc_whitelist.count(strUser);
274  std::set<std::string>& whitelist = g_rpc_whitelist[strUser];
275  if (pos != std::string::npos) {
276  std::string strWhitelist = strRPCWhitelist.substr(pos + 1);
277  std::vector<std::string> whitelist_split = SplitString(strWhitelist, ", ");
278  std::set<std::string> new_whitelist{
279  std::make_move_iterator(whitelist_split.begin()),
280  std::make_move_iterator(whitelist_split.end())};
281  if (intersect) {
282  std::set<std::string> tmp_whitelist;
283  std::set_intersection(new_whitelist.begin(), new_whitelist.end(),
284  whitelist.begin(), whitelist.end(), std::inserter(tmp_whitelist, tmp_whitelist.end()));
285  new_whitelist = std::move(tmp_whitelist);
286  }
287  whitelist = std::move(new_whitelist);
288  }
289  }
290 
291  return true;
292 }
293 
294 bool StartHTTPRPC(const std::any& context)
295 {
296  LogPrint(BCLog::RPC, "Starting HTTP RPC server\n");
297  if (!InitRPCAuthentication())
298  return false;
299 
300  auto handle_rpc = [context](HTTPRequest* req, const std::string&) { return HTTPReq_JSONRPC(context, req); };
301  RegisterHTTPHandler("/", true, handle_rpc);
303  RegisterHTTPHandler("/wallet/", false, handle_rpc);
304  }
305  struct event_base* eventBase = EventBase();
306  assert(eventBase);
307  httpRPCTimerInterface = std::make_unique<HTTPRPCTimerInterface>(eventBase);
309  return true;
310 }
311 
313 {
314  LogPrint(BCLog::RPC, "Interrupting HTTP RPC server\n");
315 }
316 
318 {
319  LogPrint(BCLog::RPC, "Stopping HTTP RPC server\n");
320  UnregisterHTTPHandler("/", true);
322  UnregisterHTTPHandler("/wallet/", false);
323  }
324  if (httpRPCTimerInterface) {
326  httpRPCTimerInterface.reset();
327  }
328 }
std::vector< std::string > GetArgs(const std::string &strArg) const
Return a vector of strings of the given argument.
Definition: system.cpp:478
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition: system.cpp:487
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: system.cpp:591
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: system.cpp:641
A hasher class for HMAC-SHA-256.
Definition: hmac_sha256.h:15
void Finalize(unsigned char hash[OUTPUT_SIZE])
Definition: hmac_sha256.cpp:29
CHMAC_SHA256 & Write(const unsigned char *data, size_t len)
Definition: hmac_sha256.h:24
UniValue execute(const JSONRPCRequest &request) const
Execute a method.
Definition: server.cpp:476
std::string ToString() const
Definition: netaddress.cpp:933
Event class.
Definition: httpserver.h:155
void trigger(struct timeval *tv)
Trigger the event.
Definition: httpserver.cpp:501
Simple one-shot callback timer to be used by the RPC mechanism to e.g.
Definition: httprpc.cpp:31
HTTPRPCTimer(struct event_base *eventBase, std::function< void()> &func, int64_t millis)
Definition: httprpc.cpp:33
HTTPEvent ev
Definition: httprpc.cpp:42
const char * Name() override
Implementation name.
Definition: httprpc.cpp:51
RPCTimerBase * NewTimer(std::function< void()> &func, int64_t millis) override
Factory function for timers.
Definition: httprpc.cpp:55
struct event_base * base
Definition: httprpc.cpp:60
HTTPRPCTimerInterface(struct event_base *_base)
Definition: httprpc.cpp:48
In-flight HTTP request.
Definition: httpserver.h:57
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:522
std::string GetURI() const
Get requested URI.
Definition: httpserver.cpp:615
void WriteReply(int nStatus, const std::string &strReply="")
Write HTTP reply.
Definition: httpserver.cpp:565
void WriteHeader(const std::string &hdr, const std::string &value)
Write output header.
Definition: httpserver.cpp:553
RequestMethod GetRequestMethod() const
Get request method.
Definition: httpserver.cpp:620
std::string ReadBody()
Read request body.
Definition: httpserver.cpp:533
CService GetPeer() const
Get CService (address:ip) for the origin of the http request.
Definition: httpserver.cpp:595
std::string strMethod
Definition: request.h:32
std::string peerAddr
Definition: request.h:37
UniValue id
Definition: request.h:31
void parse(const UniValue &valRequest)
Definition: request.cpp:158
std::string URI
Definition: request.h:35
std::string authUser
Definition: request.h:36
std::any context
Definition: request.h:38
Opaque base class for timers returned by NewTimerFunc.
Definition: server.h:51
RPC timer "driver".
Definition: server.h:60
const std::string & get_str() const
bool isArray() const
Definition: univalue.h:81
const UniValue & get_obj() const
size_t size() const
Definition: univalue.h:67
Int getInt() const
Definition: univalue.h:138
const UniValue & get_array() const
bool read(const char *raw, size_t len)
bool isObject() const
Definition: univalue.h:82
virtual bool HasWalletSupport() const =0
Is the wallet component enabled.
const WalletInitInterface & g_wallet_init_interface
Definition: dummywallet.cpp:58
static const char * WWW_AUTH_HEADER_DATA
WWW-Authenticate to present with 401 Unauthorized response.
Definition: httprpc.cpp:25
void InterruptHTTPRPC()
Interrupt HTTP RPC subsystem.
Definition: httprpc.cpp:312
void StopHTTPRPC()
Stop HTTP RPC subsystem.
Definition: httprpc.cpp:317
static std::unique_ptr< HTTPRPCTimerInterface > httpRPCTimerInterface
Definition: httprpc.cpp:67
static bool multiUserAuthorized(std::string strUserPass)
Definition: httprpc.cpp:93
bool StartHTTPRPC(const std::any &context)
Start HTTP RPC subsystem.
Definition: httprpc.cpp:294
static bool g_rpc_whitelist_default
Definition: httprpc.cpp:72
static bool RPCAuthorized(const std::string &strAuth, std::string &strAuthUsernameOut)
Definition: httprpc.cpp:124
static std::vector< std::vector< std::string > > g_rpcauth
Definition: httprpc.cpp:69
static bool HTTPReq_JSONRPC(const std::any &context, HTTPRequest *req)
Definition: httprpc.cpp:146
static std::string strRPCUserColonPass
Definition: httprpc.cpp:65
static bool InitRPCAuthentication()
Definition: httprpc.cpp:241
static std::map< std::string, std::set< std::string > > g_rpc_whitelist
Definition: httprpc.cpp:71
static void JSONErrorReply(HTTPRequest *req, const UniValue &objError, const UniValue &id)
Definition: httprpc.cpp:74
void UnregisterHTTPHandler(const std::string &prefix, bool exactMatch)
Unregister handler for prefix.
Definition: httpserver.cpp:674
void RegisterHTTPHandler(const std::string &prefix, bool exactMatch, const HTTPRequestHandler &handler)
Register handler for prefix.
Definition: httpserver.cpp:667
struct event_base * EventBase()
Return evhttp event base.
Definition: httpserver.cpp:477
static struct event_base * eventBase
HTTP module state.
Definition: httpserver.cpp:137
#define LogPrint(category,...)
Definition: logging.h:245
#define LogPrintf(...)
Definition: logging.h:236
@ RPC
Definition: logging.h:47
WalletContext context
std::string JSONRPCReply(const UniValue &result, const UniValue &error, const UniValue &id)
Definition: request.cpp:50
UniValue JSONRPCError(int code, const std::string &message)
Definition: request.cpp:56
bool GenerateAuthCookie(std::string *cookie_out)
Generate a new RPC authentication cookie and write it to disk.
Definition: request.cpp:81
@ HTTP_BAD_REQUEST
Definition: protocol.h:13
@ HTTP_BAD_METHOD
Definition: protocol.h:17
@ HTTP_OK
Definition: protocol.h:12
@ HTTP_UNAUTHORIZED
Definition: protocol.h:14
@ HTTP_NOT_FOUND
Definition: protocol.h:16
@ HTTP_FORBIDDEN
Definition: protocol.h:15
@ HTTP_INTERNAL_SERVER_ERROR
Definition: protocol.h:18
@ RPC_PARSE_ERROR
Definition: protocol.h:36
@ RPC_METHOD_NOT_FOUND
Definition: protocol.h:31
@ RPC_INVALID_REQUEST
Standard JSON-RPC 2.0 errors.
Definition: protocol.h:28
void RPCUnsetTimerInterface(RPCTimerInterface *iface)
Unset factory function for timers.
Definition: server.cpp:548
std::string JSONRPCExecBatch(const JSONRPCRequest &jreq, const UniValue &vReq)
Definition: server.cpp:379
CRPCTable tableRPC
Definition: server.cpp:572
void RPCSetTimerInterface(RPCTimerInterface *iface)
Set the factory function for timers.
Definition: server.cpp:543
bool TimingResistantEqual(const T &a, const T &b)
Timing-attack-resistant comparison.
Definition: strencodings.h:247
std::vector< std::string > SplitString(std::string_view str, char sep)
Definition: string.h:21
std::string_view TrimStringView(std::string_view str, std::string_view pattern=" \f\n\r\t\v")
Definition: string.h:31
void UninterruptibleSleep(const std::chrono::microseconds &n)
Definition: time.cpp:23
const UniValue & find_value(const UniValue &obj, const std::string &name)
Definition: univalue.cpp:233
const UniValue NullUniValue
Definition: univalue.cpp:16
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
std::optional< std::vector< unsigned char > > DecodeBase64(std::string_view str)
ArgsManager gArgs
Definition: system.cpp:73
assert(!tx.IsCoinBase())