Bitcoin Core  21.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/system.h>
14 #include <util/translation.h>
15 #include <walletinitinterface.h>
16 
17 #include <algorithm>
18 #include <iterator>
19 #include <map>
20 #include <memory>
21 #include <stdio.h>
22 #include <set>
23 #include <string>
24 
25 #include <boost/algorithm/string.hpp> // boost::trim
26 
28 static const char* WWW_AUTH_HEADER_DATA = "Basic realm=\"jsonrpc\"";
29 
33 class HTTPRPCTimer : public RPCTimerBase
34 {
35 public:
36  HTTPRPCTimer(struct event_base* eventBase, std::function<void()>& func, int64_t millis) :
37  ev(eventBase, false, func)
38  {
39  struct timeval tv;
40  tv.tv_sec = millis/1000;
41  tv.tv_usec = (millis%1000)*1000;
42  ev.trigger(&tv);
43  }
44 private:
46 };
47 
49 {
50 public:
51  explicit HTTPRPCTimerInterface(struct event_base* _base) : base(_base)
52  {
53  }
54  const char* Name() override
55  {
56  return "HTTP";
57  }
58  RPCTimerBase* NewTimer(std::function<void()>& func, int64_t millis) override
59  {
60  return new HTTPRPCTimer(base, func, millis);
61  }
62 private:
63  struct event_base* base;
64 };
65 
66 
67 /* Pre-base64-encoded authentication token */
68 static std::string strRPCUserColonPass;
69 /* Stored RPC timer interface (for unregistration) */
70 static std::unique_ptr<HTTPRPCTimerInterface> httpRPCTimerInterface;
71 /* List of -rpcauth values */
72 static std::vector<std::vector<std::string>> g_rpcauth;
73 /* RPC Auth Whitelist */
74 static std::map<std::string, std::set<std::string>> g_rpc_whitelist;
75 static bool g_rpc_whitelist_default = false;
76 
77 static void JSONErrorReply(HTTPRequest* req, const UniValue& objError, const UniValue& id)
78 {
79  // Send error reply from json-rpc error object
80  int nStatus = HTTP_INTERNAL_SERVER_ERROR;
81  int code = find_value(objError, "code").get_int();
82 
83  if (code == RPC_INVALID_REQUEST)
84  nStatus = HTTP_BAD_REQUEST;
85  else if (code == RPC_METHOD_NOT_FOUND)
86  nStatus = HTTP_NOT_FOUND;
87 
88  std::string strReply = JSONRPCReply(NullUniValue, objError, id);
89 
90  req->WriteHeader("Content-Type", "application/json");
91  req->WriteReply(nStatus, strReply);
92 }
93 
94 //This function checks username and password against -rpcauth
95 //entries from config file.
96 static bool multiUserAuthorized(std::string strUserPass)
97 {
98  if (strUserPass.find(':') == std::string::npos) {
99  return false;
100  }
101  std::string strUser = strUserPass.substr(0, strUserPass.find(':'));
102  std::string strPass = strUserPass.substr(strUserPass.find(':') + 1);
103 
104  for (const auto& vFields : g_rpcauth) {
105  std::string strName = vFields[0];
106  if (!TimingResistantEqual(strName, strUser)) {
107  continue;
108  }
109 
110  std::string strSalt = vFields[1];
111  std::string strHash = vFields[2];
112 
113  static const unsigned int KEY_SIZE = 32;
114  unsigned char out[KEY_SIZE];
115 
116  CHMAC_SHA256(reinterpret_cast<const unsigned char*>(strSalt.data()), strSalt.size()).Write(reinterpret_cast<const unsigned char*>(strPass.data()), strPass.size()).Finalize(out);
117  std::vector<unsigned char> hexvec(out, out+KEY_SIZE);
118  std::string strHashFromPass = HexStr(hexvec);
119 
120  if (TimingResistantEqual(strHashFromPass, strHash)) {
121  return true;
122  }
123  }
124  return false;
125 }
126 
127 static bool RPCAuthorized(const std::string& strAuth, std::string& strAuthUsernameOut)
128 {
129  if (strRPCUserColonPass.empty()) // Belt-and-suspenders measure if InitRPCAuthentication was not called
130  return false;
131  if (strAuth.substr(0, 6) != "Basic ")
132  return false;
133  std::string strUserPass64 = strAuth.substr(6);
134  boost::trim(strUserPass64);
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 util::Ref& 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(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");
246  if (!GenerateAuthCookie(&strRPCUserColonPass)) {
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  {
255  LogPrintf("Using rpcauth authentication.\n");
256  for (const std::string& rpcauth : gArgs.GetArgs("-rpcauth")) {
257  std::vector<std::string> fields;
258  boost::split(fields, rpcauth, boost::is_any_of(":$"));
259  if (fields.size() == 3) {
260  g_rpcauth.push_back(fields);
261  } else {
262  LogPrintf("Invalid -rpcauth argument.\n");
263  return false;
264  }
265  }
266  }
267 
268  g_rpc_whitelist_default = gArgs.GetBoolArg("-rpcwhitelistdefault", gArgs.IsArgSet("-rpcwhitelist"));
269  for (const std::string& strRPCWhitelist : gArgs.GetArgs("-rpcwhitelist")) {
270  auto pos = strRPCWhitelist.find(':');
271  std::string strUser = strRPCWhitelist.substr(0, pos);
272  bool intersect = g_rpc_whitelist.count(strUser);
273  std::set<std::string>& whitelist = g_rpc_whitelist[strUser];
274  if (pos != std::string::npos) {
275  std::string strWhitelist = strRPCWhitelist.substr(pos + 1);
276  std::set<std::string> new_whitelist;
277  boost::split(new_whitelist, strWhitelist, boost::is_any_of(", "));
278  if (intersect) {
279  std::set<std::string> tmp_whitelist;
280  std::set_intersection(new_whitelist.begin(), new_whitelist.end(),
281  whitelist.begin(), whitelist.end(), std::inserter(tmp_whitelist, tmp_whitelist.end()));
282  new_whitelist = std::move(tmp_whitelist);
283  }
284  whitelist = std::move(new_whitelist);
285  }
286  }
287 
288  return true;
289 }
290 
291 bool StartHTTPRPC(const util::Ref& context)
292 {
293  LogPrint(BCLog::RPC, "Starting HTTP RPC server\n");
294  if (!InitRPCAuthentication())
295  return false;
296 
297  auto handle_rpc = [&context](HTTPRequest* req, const std::string&) { return HTTPReq_JSONRPC(context, req); };
298  RegisterHTTPHandler("/", true, handle_rpc);
300  RegisterHTTPHandler("/wallet/", false, handle_rpc);
301  }
302  struct event_base* eventBase = EventBase();
303  assert(eventBase);
304  httpRPCTimerInterface = MakeUnique<HTTPRPCTimerInterface>(eventBase);
305  RPCSetTimerInterface(httpRPCTimerInterface.get());
306  return true;
307 }
308 
310 {
311  LogPrint(BCLog::RPC, "Interrupting HTTP RPC server\n");
312 }
313 
315 {
316  LogPrint(BCLog::RPC, "Stopping HTTP RPC server\n");
317  UnregisterHTTPHandler("/", true);
319  UnregisterHTTPHandler("/wallet/", false);
320  }
321  if (httpRPCTimerInterface) {
322  RPCUnsetTimerInterface(httpRPCTimerInterface.get());
323  httpRPCTimerInterface.reset();
324  }
325 }
bool isObject() const
Definition: univalue.h:84
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition: system.cpp:371
bool TimingResistantEqual(const T &a, const T &b)
Timing-attack-resistant comparison.
Definition: strencodings.h:159
RPC timer "driver".
Definition: server.h:60
#define LogPrint(category,...)
Definition: logging.h:182
HTTPRPCTimerInterface(struct event_base *_base)
Definition: httprpc.cpp:51
assert(!tx.IsCoinBase())
const char * Name() override
Implementation name.
Definition: httprpc.cpp:54
static const char * WWW_AUTH_HEADER_DATA
WWW-Authenticate to present with 401 Unauthorized response.
Definition: httprpc.cpp:28
bool read(const char *raw, size_t len)
static std::string strRPCUserColonPass
Definition: httprpc.cpp:68
HTTPEvent ev
Definition: httprpc.cpp:45
Event class.
Definition: httpserver.h:129
static std::vector< std::vector< std::string > > g_rpcauth
Definition: httprpc.cpp:72
static bool InitRPCAuthentication()
Definition: httprpc.cpp:241
struct event_base * base
Definition: httprpc.cpp:63
static void JSONErrorReply(HTTPRequest *req, const UniValue &objError, const UniValue &id)
Definition: httprpc.cpp:77
A hasher class for HMAC-SHA-256.
Definition: hmac_sha256.h:14
RPCTimerBase * NewTimer(std::function< void()> &func, int64_t millis) override
Factory function for timers.
Definition: httprpc.cpp:58
static void LogPrintf(const char *fmt, const Args &... args)
Definition: logging.h:166
const std::string & get_str() const
std::vector< unsigned char > DecodeBase64(const char *p, bool *pf_invalid)
const UniValue & get_array() const
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: system.cpp:479
void InterruptHTTPRPC()
Interrupt HTTP RPC subsystem.
Definition: httprpc.cpp:309
void RPCUnsetTimerInterface(RPCTimerInterface *iface)
Unset factory function for timers.
Definition: server.cpp:493
const UniValue & find_value(const UniValue &obj, const std::string &name)
Definition: univalue.cpp:234
void RegisterHTTPHandler(const std::string &prefix, bool exactMatch, const HTTPRequestHandler &handler)
Register handler for prefix.
Definition: httpserver.cpp:634
UniValue execute(const JSONRPCRequest &request) const
Execute a method.
Definition: server.cpp:435
std::string strMethod
Definition: request.h:35
static std::unique_ptr< HTTPRPCTimerInterface > httpRPCTimerInterface
Definition: httprpc.cpp:70
static bool RPCAuthorized(const std::string &strAuth, std::string &strAuthUsernameOut)
Definition: httprpc.cpp:127
CRPCTable tableRPC
Definition: server.cpp:517
std::string peerAddr
Definition: request.h:40
static bool multiUserAuthorized(std::string strUserPass)
Definition: httprpc.cpp:96
UniValue JSONRPCError(int code, const std::string &message)
Definition: request.cpp:51
static bool HTTPReq_JSONRPC(const util::Ref &context, HTTPRequest *req)
Definition: httprpc.cpp:147
void WriteReply(int nStatus, const std::string &strReply="")
Write HTTP reply.
Definition: httpserver.cpp:564
Simple one-shot callback timer to be used by the RPC mechanism to e.g.
Definition: httprpc.cpp:33
RequestMethod GetRequestMethod() const
Get request method.
Definition: httpserver.cpp:613
std::string JSONRPCExecBatch(const JSONRPCRequest &jreq, const UniValue &vReq)
Definition: server.cpp:376
UniValue id
Definition: request.h:34
void UnregisterHTTPHandler(const std::string &prefix, bool exactMatch)
Unregister handler for prefix.
Definition: httpserver.cpp:640
int get_int() const
struct event_base * EventBase()
Return evhttp event base.
Definition: httpserver.cpp:476
Type-safe dynamic reference.
Definition: ref.h:21
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
std::string JSONRPCReply(const UniValue &result, const UniValue &error, const UniValue &id)
Definition: request.cpp:45
void StopHTTPRPC()
Stop HTTP RPC subsystem.
Definition: httprpc.cpp:314
const WalletInitInterface & g_wallet_init_interface
Definition: dummywallet.cpp:55
void parse(const UniValue &valRequest)
Definition: request.cpp:153
bool StartHTTPRPC(const util::Ref &context)
Start HTTP RPC subsystem.
Definition: httprpc.cpp:291
static bool g_rpc_whitelist_default
Definition: httprpc.cpp:75
HTTPRPCTimer(struct event_base *eventBase, std::function< void()> &func, int64_t millis)
Definition: httprpc.cpp:36
void UninterruptibleSleep(const std::chrono::microseconds &n)
Definition: time.cpp:19
void WriteHeader(const std::string &hdr, const std::string &value)
Write output header.
Definition: httpserver.cpp:552
void trigger(struct timeval *tv)
Trigger the event.
Definition: httpserver.cpp:500
virtual bool HasWalletSupport() const =0
Is the wallet component enabled.
const UniValue & get_obj() const
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: system.cpp:467
std::string URI
Definition: request.h:38
std::string authUser
Definition: request.h:39
void RPCSetTimerInterface(RPCTimerInterface *iface)
Set the factory function for timers.
Definition: server.cpp:488
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:521
Opaque base class for timers returned by NewTimerFunc.
Definition: server.h:51
bool GenerateAuthCookie(std::string *cookie_out)
Generate a new RPC authentication cookie and write it to disk.
Definition: request.cpp:76
ArgsManager gArgs
Definition: system.cpp:77
const UniValue NullUniValue
Definition: univalue.cpp:13
CService GetPeer() const
Get CService (address:ip) for the origin of the http request.
Definition: httpserver.cpp:594
std::string ReadBody()
Read request body.
Definition: httpserver.cpp:532
Standard JSON-RPC 2.0 errors.
Definition: protocol.h:28
std::string ToString() const
Definition: netaddress.cpp:986
In-flight HTTP request.
Definition: httpserver.h:56
size_t size() const
Definition: univalue.h:68
static std::map< std::string, std::set< std::string > > g_rpc_whitelist
Definition: httprpc.cpp:74
std::vector< std::string > GetArgs(const std::string &strArg) const
Return a vector of strings of the given argument.
Definition: system.cpp:362
bool isArray() const
Definition: univalue.h:83
std::string GetURI() const
Get requested URI.
Definition: httpserver.cpp:608
static struct event_base * eventBase
HTTP module state.
Definition: httpserver.cpp:134