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