Bitcoin Core  0.19.99
P2P Digital Currency
httprpc.cpp
Go to the documentation of this file.
1 // Copyright (c) 2015-2019 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 <ui_interface.h>
13 #include <util/strencodings.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> // boost::trim
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 /* RPC Auth Whitelist */
73 static std::map<std::string, std::set<std::string>> g_rpc_whitelist;
74 static bool g_rpc_whitelist_default = false;
75 
76 static void JSONErrorReply(HTTPRequest* req, const UniValue& objError, const UniValue& id)
77 {
78  // Send error reply from json-rpc error object
79  int nStatus = HTTP_INTERNAL_SERVER_ERROR;
80  int code = find_value(objError, "code").get_int();
81 
82  if (code == RPC_INVALID_REQUEST)
83  nStatus = HTTP_BAD_REQUEST;
84  else if (code == RPC_METHOD_NOT_FOUND)
85  nStatus = HTTP_NOT_FOUND;
86 
87  std::string strReply = JSONRPCReply(NullUniValue, objError, id);
88 
89  req->WriteHeader("Content-Type", "application/json");
90  req->WriteReply(nStatus, strReply);
91 }
92 
93 //This function checks username and password against -rpcauth
94 //entries from config file.
95 static bool multiUserAuthorized(std::string strUserPass)
96 {
97  if (strUserPass.find(':') == std::string::npos) {
98  return false;
99  }
100  std::string strUser = strUserPass.substr(0, strUserPass.find(':'));
101  std::string strPass = strUserPass.substr(strUserPass.find(':') + 1);
102 
103  for (const std::string& strRPCAuth : gArgs.GetArgs("-rpcauth")) {
104  //Search for multi-user login/pass "rpcauth" from config
105  std::vector<std::string> vFields;
106  boost::split(vFields, strRPCAuth, boost::is_any_of(":$"));
107  if (vFields.size() != 3) {
108  //Incorrect formatting in config file
109  continue;
110  }
111 
112  std::string strName = vFields[0];
113  if (!TimingResistantEqual(strName, strUser)) {
114  continue;
115  }
116 
117  std::string strSalt = vFields[1];
118  std::string strHash = vFields[2];
119 
120  static const unsigned int KEY_SIZE = 32;
121  unsigned char out[KEY_SIZE];
122 
123  CHMAC_SHA256(reinterpret_cast<const unsigned char*>(strSalt.data()), strSalt.size()).Write(reinterpret_cast<const unsigned char*>(strPass.data()), strPass.size()).Finalize(out);
124  std::vector<unsigned char> hexvec(out, out+KEY_SIZE);
125  std::string strHashFromPass = HexStr(hexvec);
126 
127  if (TimingResistantEqual(strHashFromPass, strHash)) {
128  return true;
129  }
130  }
131  return false;
132 }
133 
134 static bool RPCAuthorized(const std::string& strAuth, std::string& strAuthUsernameOut)
135 {
136  if (strRPCUserColonPass.empty()) // Belt-and-suspenders measure if InitRPCAuthentication was not called
137  return false;
138  if (strAuth.substr(0, 6) != "Basic ")
139  return false;
140  std::string strUserPass64 = strAuth.substr(6);
141  boost::trim(strUserPass64);
142  std::string strUserPass = DecodeBase64(strUserPass64);
143 
144  if (strUserPass.find(':') != std::string::npos)
145  strAuthUsernameOut = strUserPass.substr(0, strUserPass.find(':'));
146 
147  //Check if authorized under single-user field
148  if (TimingResistantEqual(strUserPass, strRPCUserColonPass)) {
149  return true;
150  }
151  return multiUserAuthorized(strUserPass);
152 }
153 
154 static bool HTTPReq_JSONRPC(HTTPRequest* req, const std::string &)
155 {
156  // JSONRPC handles only POST
157  if (req->GetRequestMethod() != HTTPRequest::POST) {
158  req->WriteReply(HTTP_BAD_METHOD, "JSONRPC server handles only POST requests");
159  return false;
160  }
161  // Check authorization
162  std::pair<bool, std::string> authHeader = req->GetHeader("authorization");
163  if (!authHeader.first) {
164  req->WriteHeader("WWW-Authenticate", WWW_AUTH_HEADER_DATA);
166  return false;
167  }
168 
169  JSONRPCRequest jreq;
170  jreq.peerAddr = req->GetPeer().ToString();
171  if (!RPCAuthorized(authHeader.second, jreq.authUser)) {
172  LogPrintf("ThreadRPCServer incorrect password attempt from %s\n", jreq.peerAddr);
173 
174  /* Deter brute-forcing
175  If this results in a DoS the user really
176  shouldn't have their RPC port exposed. */
177  MilliSleep(250);
178 
179  req->WriteHeader("WWW-Authenticate", WWW_AUTH_HEADER_DATA);
181  return false;
182  }
183 
184  try {
185  // Parse request
186  UniValue valRequest;
187  if (!valRequest.read(req->ReadBody()))
188  throw JSONRPCError(RPC_PARSE_ERROR, "Parse error");
189 
190  // Set the URI
191  jreq.URI = req->GetURI();
192 
193  std::string strReply;
194  bool user_has_whitelist = g_rpc_whitelist.count(jreq.authUser);
195  if (!user_has_whitelist && g_rpc_whitelist_default) {
196  LogPrintf("RPC User %s not allowed to call any methods\n", jreq.authUser);
198  return false;
199 
200  // singleton request
201  } else if (valRequest.isObject()) {
202  jreq.parse(valRequest);
203  if (user_has_whitelist && !g_rpc_whitelist[jreq.authUser].count(jreq.strMethod)) {
204  LogPrintf("RPC User %s not allowed to call method %s\n", jreq.authUser, jreq.strMethod);
206  return false;
207  }
208  UniValue result = tableRPC.execute(jreq);
209 
210  // Send reply
211  strReply = JSONRPCReply(result, NullUniValue, jreq.id);
212 
213  // array of requests
214  } else if (valRequest.isArray()) {
215  if (user_has_whitelist) {
216  for (unsigned int reqIdx = 0; reqIdx < valRequest.size(); reqIdx++) {
217  if (!valRequest[reqIdx].isObject()) {
218  throw JSONRPCError(RPC_INVALID_REQUEST, "Invalid Request object");
219  } else {
220  const UniValue& request = valRequest[reqIdx].get_obj();
221  // Parse method
222  std::string strMethod = find_value(request, "method").get_str();
223  if (!g_rpc_whitelist[jreq.authUser].count(strMethod)) {
224  LogPrintf("RPC User %s not allowed to call method %s\n", jreq.authUser, strMethod);
226  return false;
227  }
228  }
229  }
230  }
231  strReply = JSONRPCExecBatch(jreq, valRequest.get_array());
232  }
233  else
234  throw JSONRPCError(RPC_PARSE_ERROR, "Top-level object parse error");
235 
236  req->WriteHeader("Content-Type", "application/json");
237  req->WriteReply(HTTP_OK, strReply);
238  } catch (const UniValue& objError) {
239  JSONErrorReply(req, objError, jreq.id);
240  return false;
241  } catch (const std::exception& e) {
242  JSONErrorReply(req, JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
243  return false;
244  }
245  return true;
246 }
247 
249 {
250  if (gArgs.GetArg("-rpcpassword", "") == "")
251  {
252  LogPrintf("No rpcpassword set - using random cookie authentication.\n");
253  if (!GenerateAuthCookie(&strRPCUserColonPass)) {
254  uiInterface.ThreadSafeMessageBox(
255  _("Error: A fatal internal error occurred, see debug.log for details").translated, // Same message as AbortNode
257  return false;
258  }
259  } else {
260  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");
261  strRPCUserColonPass = gArgs.GetArg("-rpcuser", "") + ":" + gArgs.GetArg("-rpcpassword", "");
262  }
263  if (gArgs.GetArg("-rpcauth","") != "")
264  {
265  LogPrintf("Using rpcauth authentication.\n");
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 
292 {
293  LogPrint(BCLog::RPC, "Starting HTTP RPC server\n");
294  if (!InitRPCAuthentication())
295  return false;
296 
299  RegisterHTTPHandler("/wallet/", false, HTTPReq_JSONRPC);
300  }
301  struct event_base* eventBase = EventBase();
302  assert(eventBase);
303  httpRPCTimerInterface = MakeUnique<HTTPRPCTimerInterface>(eventBase);
304  RPCSetTimerInterface(httpRPCTimerInterface.get());
305  return true;
306 }
307 
309 {
310  LogPrint(BCLog::RPC, "Interrupting HTTP RPC server\n");
311 }
312 
314 {
315  LogPrint(BCLog::RPC, "Stopping HTTP RPC server\n");
316  UnregisterHTTPHandler("/", true);
318  UnregisterHTTPHandler("/wallet/", false);
319  }
320  if (httpRPCTimerInterface) {
321  RPCUnsetTimerInterface(httpRPCTimerInterface.get());
322  httpRPCTimerInterface.reset();
323  }
324 }
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:362
bool TimingResistantEqual(const T &a, const T &b)
Timing-attack-resistant comparison.
Definition: strencodings.h:158
RPC timer "driver".
Definition: server.h:56
#define LogPrint(category,...)
Definition: logging.h:179
HTTPRPCTimerInterface(struct event_base *_base)
Definition: httprpc.cpp:52
const char * Name() override
Implementation name.
Definition: httprpc.cpp:55
static const char * WWW_AUTH_HEADER_DATA
WWW-Authenticate to present with 401 Unauthorized response.
Definition: httprpc.cpp:29
bool read(const char *raw, size_t len)
static std::string strRPCUserColonPass
Definition: httprpc.cpp:69
HTTPEvent ev
Definition: httprpc.cpp:46
Event class.
Definition: httpserver.h:129
static bool InitRPCAuthentication()
Definition: httprpc.cpp:248
bool StartHTTPRPC()
Start HTTP RPC subsystem.
Definition: httprpc.cpp:291
struct event_base * base
Definition: httprpc.cpp:64
static void JSONErrorReply(HTTPRequest *req, const UniValue &objError, const UniValue &id)
Definition: httprpc.cpp:76
void MilliSleep(int64_t n)
Definition: time.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:59
static void LogPrintf(const char *fmt, const Args &... args)
Definition: logging.h:163
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:384
void InterruptHTTPRPC()
Interrupt HTTP RPC subsystem.
Definition: httprpc.cpp:308
static bool HTTPReq_JSONRPC(HTTPRequest *req, const std::string &)
Definition: httprpc.cpp:154
void RPCUnsetTimerInterface(RPCTimerInterface *iface)
Unset factory function for timers.
Definition: server.cpp:476
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:640
UniValue execute(const JSONRPCRequest &request) const
Execute a method.
Definition: server.cpp:418
std::string strMethod
Definition: request.h:31
static std::unique_ptr< HTTPRPCTimerInterface > httpRPCTimerInterface
Definition: httprpc.cpp:71
static bool RPCAuthorized(const std::string &strAuth, std::string &strAuthUsernameOut)
Definition: httprpc.cpp:134
CRPCTable tableRPC
Definition: server.cpp:499
std::string peerAddr
Definition: request.h:36
static bool multiUserAuthorized(std::string strUserPass)
Definition: httprpc.cpp:95
UniValue JSONRPCError(int code, const std::string &message)
Definition: request.cpp:51
void WriteReply(int nStatus, const std::string &strReply="")
Write HTTP reply.
Definition: httpserver.cpp:570
Simple one-shot callback timer to be used by the RPC mechanism to e.g.
Definition: httprpc.cpp:34
RequestMethod GetRequestMethod() const
Get request method.
Definition: httpserver.cpp:619
bilingual_str _(const char *psz)
Translation function.
Definition: translation.h:36
std::string JSONRPCExecBatch(const JSONRPCRequest &jreq, const UniValue &vReq)
Definition: server.cpp:359
UniValue id
Definition: request.h:30
void UnregisterHTTPHandler(const std::string &prefix, bool exactMatch)
Unregister handler for prefix.
Definition: httpserver.cpp:646
int get_int() const
struct event_base * EventBase()
Return evhttp event base.
Definition: httpserver.cpp:482
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:313
const WalletInitInterface & g_wallet_init_interface
Definition: dummywallet.cpp:58
void parse(const UniValue &valRequest)
Definition: request.cpp:153
static bool g_rpc_whitelist_default
Definition: httprpc.cpp:74
HTTPRPCTimer(struct event_base *eventBase, std::function< void()> &func, int64_t millis)
Definition: httprpc.cpp:37
void WriteHeader(const std::string &hdr, const std::string &value)
Write output header.
Definition: httpserver.cpp:558
void trigger(struct timeval *tv)
Trigger the event.
Definition: httpserver.cpp:506
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:372
std::string URI
Definition: request.h:34
std::string authUser
Definition: request.h:35
void RPCSetTimerInterface(RPCTimerInterface *iface)
Set the factory function for timers.
Definition: server.cpp:471
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:527
Opaque base class for timers returned by NewTimerFunc.
Definition: server.h:47
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:125
ArgsManager gArgs
Definition: system.cpp:76
const UniValue NullUniValue
Definition: univalue.cpp:13
CService GetPeer() const
Get CService (address:ip) for the origin of the http request.
Definition: httpserver.cpp:600
std::string ReadBody()
Read request body.
Definition: httpserver.cpp:538
Standard JSON-RPC 2.0 errors.
Definition: protocol.h:28
std::string ToString() const
Definition: netaddress.cpp:745
In-flight HTTP request.
Definition: httpserver.h:56
size_t size() const
Definition: univalue.h:68
CClientUIInterface uiInterface
static std::map< std::string, std::set< std::string > > g_rpc_whitelist
Definition: httprpc.cpp:73
std::vector< std::string > GetArgs(const std::string &strArg) const
Return a vector of strings of the given argument.
Definition: system.cpp:353
bool isArray() const
Definition: univalue.h:83
std::string GetURI() const
Get requested URI.
Definition: httpserver.cpp:614
static struct event_base * eventBase
HTTP module state.
Definition: httpserver.cpp:140