Bitcoin Core  0.20.99
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 /* RPC Auth Whitelist */
72 static std::map<std::string, std::set<std::string>> g_rpc_whitelist;
73 static bool g_rpc_whitelist_default = false;
74 
75 static void JSONErrorReply(HTTPRequest* req, const UniValue& objError, const UniValue& id)
76 {
77  // Send error reply from json-rpc error object
78  int nStatus = HTTP_INTERNAL_SERVER_ERROR;
79  int code = find_value(objError, "code").get_int();
80 
81  if (code == RPC_INVALID_REQUEST)
82  nStatus = HTTP_BAD_REQUEST;
83  else if (code == RPC_METHOD_NOT_FOUND)
84  nStatus = HTTP_NOT_FOUND;
85 
86  std::string strReply = JSONRPCReply(NullUniValue, objError, id);
87 
88  req->WriteHeader("Content-Type", "application/json");
89  req->WriteReply(nStatus, strReply);
90 }
91 
92 //This function checks username and password against -rpcauth
93 //entries from config file.
94 static bool multiUserAuthorized(std::string strUserPass)
95 {
96  if (strUserPass.find(':') == std::string::npos) {
97  return false;
98  }
99  std::string strUser = strUserPass.substr(0, strUserPass.find(':'));
100  std::string strPass = strUserPass.substr(strUserPass.find(':') + 1);
101 
102  for (const std::string& strRPCAuth : gArgs.GetArgs("-rpcauth")) {
103  //Search for multi-user login/pass "rpcauth" from config
104  std::vector<std::string> vFields;
105  boost::split(vFields, strRPCAuth, boost::is_any_of(":$"));
106  if (vFields.size() != 3) {
107  //Incorrect formatting in config file
108  continue;
109  }
110 
111  std::string strName = vFields[0];
112  if (!TimingResistantEqual(strName, strUser)) {
113  continue;
114  }
115 
116  std::string strSalt = vFields[1];
117  std::string strHash = vFields[2];
118 
119  static const unsigned int KEY_SIZE = 32;
120  unsigned char out[KEY_SIZE];
121 
122  CHMAC_SHA256(reinterpret_cast<const unsigned char*>(strSalt.data()), strSalt.size()).Write(reinterpret_cast<const unsigned char*>(strPass.data()), strPass.size()).Finalize(out);
123  std::vector<unsigned char> hexvec(out, out+KEY_SIZE);
124  std::string strHashFromPass = HexStr(hexvec);
125 
126  if (TimingResistantEqual(strHashFromPass, strHash)) {
127  return true;
128  }
129  }
130  return false;
131 }
132 
133 static bool RPCAuthorized(const std::string& strAuth, std::string& strAuthUsernameOut)
134 {
135  if (strRPCUserColonPass.empty()) // Belt-and-suspenders measure if InitRPCAuthentication was not called
136  return false;
137  if (strAuth.substr(0, 6) != "Basic ")
138  return false;
139  std::string strUserPass64 = strAuth.substr(6);
140  boost::trim(strUserPass64);
141  std::string strUserPass = DecodeBase64(strUserPass64);
142 
143  if (strUserPass.find(':') != std::string::npos)
144  strAuthUsernameOut = strUserPass.substr(0, strUserPass.find(':'));
145 
146  //Check if authorized under single-user field
147  if (TimingResistantEqual(strUserPass, strRPCUserColonPass)) {
148  return true;
149  }
150  return multiUserAuthorized(strUserPass);
151 }
152 
153 static bool HTTPReq_JSONRPC(const util::Ref& context, HTTPRequest* req)
154 {
155  // JSONRPC handles only POST
156  if (req->GetRequestMethod() != HTTPRequest::POST) {
157  req->WriteReply(HTTP_BAD_METHOD, "JSONRPC server handles only POST requests");
158  return false;
159  }
160  // Check authorization
161  std::pair<bool, std::string> authHeader = req->GetHeader("authorization");
162  if (!authHeader.first) {
163  req->WriteHeader("WWW-Authenticate", WWW_AUTH_HEADER_DATA);
165  return false;
166  }
167 
168  JSONRPCRequest jreq(context);
169  jreq.peerAddr = req->GetPeer().ToString();
170  if (!RPCAuthorized(authHeader.second, jreq.authUser)) {
171  LogPrintf("ThreadRPCServer incorrect password attempt from %s\n", jreq.peerAddr);
172 
173  /* Deter brute-forcing
174  If this results in a DoS the user really
175  shouldn't have their RPC port exposed. */
176  UninterruptibleSleep(std::chrono::milliseconds{250});
177 
178  req->WriteHeader("WWW-Authenticate", WWW_AUTH_HEADER_DATA);
180  return false;
181  }
182 
183  try {
184  // Parse request
185  UniValue valRequest;
186  if (!valRequest.read(req->ReadBody()))
187  throw JSONRPCError(RPC_PARSE_ERROR, "Parse error");
188 
189  // Set the URI
190  jreq.URI = req->GetURI();
191 
192  std::string strReply;
193  bool user_has_whitelist = g_rpc_whitelist.count(jreq.authUser);
194  if (!user_has_whitelist && g_rpc_whitelist_default) {
195  LogPrintf("RPC User %s not allowed to call any methods\n", jreq.authUser);
197  return false;
198 
199  // singleton request
200  } else if (valRequest.isObject()) {
201  jreq.parse(valRequest);
202  if (user_has_whitelist && !g_rpc_whitelist[jreq.authUser].count(jreq.strMethod)) {
203  LogPrintf("RPC User %s not allowed to call method %s\n", jreq.authUser, jreq.strMethod);
205  return false;
206  }
207  UniValue result = tableRPC.execute(jreq);
208 
209  // Send reply
210  strReply = JSONRPCReply(result, NullUniValue, jreq.id);
211 
212  // array of requests
213  } else if (valRequest.isArray()) {
214  if (user_has_whitelist) {
215  for (unsigned int reqIdx = 0; reqIdx < valRequest.size(); reqIdx++) {
216  if (!valRequest[reqIdx].isObject()) {
217  throw JSONRPCError(RPC_INVALID_REQUEST, "Invalid Request object");
218  } else {
219  const UniValue& request = valRequest[reqIdx].get_obj();
220  // Parse method
221  std::string strMethod = find_value(request, "method").get_str();
222  if (!g_rpc_whitelist[jreq.authUser].count(strMethod)) {
223  LogPrintf("RPC User %s not allowed to call method %s\n", jreq.authUser, strMethod);
225  return false;
226  }
227  }
228  }
229  }
230  strReply = JSONRPCExecBatch(jreq, valRequest.get_array());
231  }
232  else
233  throw JSONRPCError(RPC_PARSE_ERROR, "Top-level object parse error");
234 
235  req->WriteHeader("Content-Type", "application/json");
236  req->WriteReply(HTTP_OK, strReply);
237  } catch (const UniValue& objError) {
238  JSONErrorReply(req, objError, jreq.id);
239  return false;
240  } catch (const std::exception& e) {
241  JSONErrorReply(req, JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
242  return false;
243  }
244  return true;
245 }
246 
248 {
249  if (gArgs.GetArg("-rpcpassword", "") == "")
250  {
251  LogPrintf("Using random cookie authentication.\n");
252  if (!GenerateAuthCookie(&strRPCUserColonPass)) {
253  return false;
254  }
255  } else {
256  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");
257  strRPCUserColonPass = gArgs.GetArg("-rpcuser", "") + ":" + gArgs.GetArg("-rpcpassword", "");
258  }
259  if (gArgs.GetArg("-rpcauth","") != "")
260  {
261  LogPrintf("Using rpcauth authentication.\n");
262  }
263 
264  g_rpc_whitelist_default = gArgs.GetBoolArg("-rpcwhitelistdefault", gArgs.IsArgSet("-rpcwhitelist"));
265  for (const std::string& strRPCWhitelist : gArgs.GetArgs("-rpcwhitelist")) {
266  auto pos = strRPCWhitelist.find(':');
267  std::string strUser = strRPCWhitelist.substr(0, pos);
268  bool intersect = g_rpc_whitelist.count(strUser);
269  std::set<std::string>& whitelist = g_rpc_whitelist[strUser];
270  if (pos != std::string::npos) {
271  std::string strWhitelist = strRPCWhitelist.substr(pos + 1);
272  std::set<std::string> new_whitelist;
273  boost::split(new_whitelist, strWhitelist, boost::is_any_of(", "));
274  if (intersect) {
275  std::set<std::string> tmp_whitelist;
276  std::set_intersection(new_whitelist.begin(), new_whitelist.end(),
277  whitelist.begin(), whitelist.end(), std::inserter(tmp_whitelist, tmp_whitelist.end()));
278  new_whitelist = std::move(tmp_whitelist);
279  }
280  whitelist = std::move(new_whitelist);
281  }
282  }
283 
284  return true;
285 }
286 
287 bool StartHTTPRPC(const util::Ref& context)
288 {
289  LogPrint(BCLog::RPC, "Starting HTTP RPC server\n");
290  if (!InitRPCAuthentication())
291  return false;
292 
293  auto handle_rpc = [&context](HTTPRequest* req, const std::string&) { return HTTPReq_JSONRPC(context, req); };
294  RegisterHTTPHandler("/", true, handle_rpc);
296  RegisterHTTPHandler("/wallet/", false, handle_rpc);
297  }
298  struct event_base* eventBase = EventBase();
299  assert(eventBase);
300  httpRPCTimerInterface = MakeUnique<HTTPRPCTimerInterface>(eventBase);
301  RPCSetTimerInterface(httpRPCTimerInterface.get());
302  return true;
303 }
304 
306 {
307  LogPrint(BCLog::RPC, "Interrupting HTTP RPC server\n");
308 }
309 
311 {
312  LogPrint(BCLog::RPC, "Stopping HTTP RPC server\n");
313  UnregisterHTTPHandler("/", true);
315  UnregisterHTTPHandler("/wallet/", false);
316  }
317  if (httpRPCTimerInterface) {
318  RPCUnsetTimerInterface(httpRPCTimerInterface.get());
319  httpRPCTimerInterface.reset();
320  }
321 }
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:370
bool TimingResistantEqual(const T &a, const T &b)
Timing-attack-resistant comparison.
Definition: strencodings.h:156
RPC timer "driver".
Definition: server.h:59
#define LogPrint(category,...)
Definition: logging.h:182
HTTPRPCTimerInterface(struct event_base *_base)
Definition: httprpc.cpp:51
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 bool InitRPCAuthentication()
Definition: httprpc.cpp:247
struct event_base * base
Definition: httprpc.cpp:63
static void JSONErrorReply(HTTPRequest *req, const UniValue &objError, const UniValue &id)
Definition: httprpc.cpp:75
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:392
void InterruptHTTPRPC()
Interrupt HTTP RPC subsystem.
Definition: httprpc.cpp:305
void RPCUnsetTimerInterface(RPCTimerInterface *iface)
Unset factory function for timers.
Definition: server.cpp:496
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:641
UniValue execute(const JSONRPCRequest &request) const
Execute a method.
Definition: server.cpp:438
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:133
CRPCTable tableRPC
Definition: server.cpp:520
std::string peerAddr
Definition: request.h:40
static bool multiUserAuthorized(std::string strUserPass)
Definition: httprpc.cpp:94
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:153
void WriteReply(int nStatus, const std::string &strReply="")
Write HTTP reply.
Definition: httpserver.cpp:571
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:620
std::string JSONRPCExecBatch(const JSONRPCRequest &jreq, const UniValue &vReq)
Definition: server.cpp:379
UniValue id
Definition: request.h:34
void UnregisterHTTPHandler(const std::string &prefix, bool exactMatch)
Unregister handler for prefix.
Definition: httpserver.cpp:647
int get_int() const
struct event_base * EventBase()
Return evhttp event base.
Definition: httpserver.cpp:483
Type-safe dynamic reference.
Definition: ref.h:21
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:310
const WalletInitInterface & g_wallet_init_interface
Definition: dummywallet.cpp:59
void parse(const UniValue &valRequest)
Definition: request.cpp:153
bool StartHTTPRPC(const util::Ref &context)
Start HTTP RPC subsystem.
Definition: httprpc.cpp:287
static bool g_rpc_whitelist_default
Definition: httprpc.cpp:73
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:559
void trigger(struct timeval *tv)
Trigger the event.
Definition: httpserver.cpp:507
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:380
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:491
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:528
Opaque base class for timers returned by NewTimerFunc.
Definition: server.h:50
bool GenerateAuthCookie(std::string *cookie_out)
Generate a new RPC authentication cookie and write it to disk.
Definition: request.cpp:76
std::string HexStr(const T itbegin, const T itend)
Definition: strencodings.h:123
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:601
std::string ReadBody()
Read request body.
Definition: httpserver.cpp:539
Standard JSON-RPC 2.0 errors.
Definition: protocol.h:28
std::string ToString() const
Definition: netaddress.cpp:751
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:72
std::vector< std::string > GetArgs(const std::string &strArg) const
Return a vector of strings of the given argument.
Definition: system.cpp:361
bool isArray() const
Definition: univalue.h:83
std::string GetURI() const
Get requested URI.
Definition: httpserver.cpp:615
static struct event_base * eventBase
HTTP module state.
Definition: httpserver.cpp:141