Bitcoin Core  26.1.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 <common/args.h>
8 #include <crypto/hmac_sha256.h>
9 #include <httpserver.h>
10 #include <logging.h>
11 #include <rpc/protocol.h>
12 #include <rpc/server.h>
13 #include <util/strencodings.h>
14 #include <util/string.h>
15 #include <walletinitinterface.h>
16 
17 #include <algorithm>
18 #include <iterator>
19 #include <map>
20 #include <memory>
21 #include <set>
22 #include <string>
23 #include <vector>
24 
26 static const char* WWW_AUTH_HEADER_DATA = "Basic realm=\"jsonrpc\"";
27 
31 class HTTPRPCTimer : public RPCTimerBase
32 {
33 public:
34  HTTPRPCTimer(struct event_base* eventBase, std::function<void()>& func, int64_t millis) :
35  ev(eventBase, false, func)
36  {
37  struct timeval tv;
38  tv.tv_sec = millis/1000;
39  tv.tv_usec = (millis%1000)*1000;
40  ev.trigger(&tv);
41  }
42 private:
44 };
45 
47 {
48 public:
49  explicit HTTPRPCTimerInterface(struct event_base* _base) : base(_base)
50  {
51  }
52  const char* Name() override
53  {
54  return "HTTP";
55  }
56  RPCTimerBase* NewTimer(std::function<void()>& func, int64_t millis) override
57  {
58  return new HTTPRPCTimer(base, func, millis);
59  }
60 private:
61  struct event_base* base;
62 };
63 
64 
65 /* Pre-base64-encoded authentication token */
66 static std::string strRPCUserColonPass;
67 /* Stored RPC timer interface (for unregistration) */
68 static std::unique_ptr<HTTPRPCTimerInterface> httpRPCTimerInterface;
69 /* List of -rpcauth values */
70 static std::vector<std::vector<std::string>> g_rpcauth;
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 = objError.find_value("code").getInt<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 auto& vFields : g_rpcauth) {
103  std::string strName = vFields[0];
104  if (!TimingResistantEqual(strName, strUser)) {
105  continue;
106  }
107 
108  std::string strSalt = vFields[1];
109  std::string strHash = vFields[2];
110 
111  static const unsigned int KEY_SIZE = 32;
112  unsigned char out[KEY_SIZE];
113 
114  CHMAC_SHA256(reinterpret_cast<const unsigned char*>(strSalt.data()), strSalt.size()).Write(reinterpret_cast<const unsigned char*>(strPass.data()), strPass.size()).Finalize(out);
115  std::vector<unsigned char> hexvec(out, out+KEY_SIZE);
116  std::string strHashFromPass = HexStr(hexvec);
117 
118  if (TimingResistantEqual(strHashFromPass, strHash)) {
119  return true;
120  }
121  }
122  return false;
123 }
124 
125 static bool RPCAuthorized(const std::string& strAuth, std::string& strAuthUsernameOut)
126 {
127  if (strRPCUserColonPass.empty()) // Belt-and-suspenders measure if InitRPCAuthentication was not called
128  return false;
129  if (strAuth.substr(0, 6) != "Basic ")
130  return false;
131  std::string_view strUserPass64 = TrimStringView(std::string_view{strAuth}.substr(6));
132  auto userpass_data = DecodeBase64(strUserPass64);
133  std::string strUserPass;
134  if (!userpass_data) return false;
135  strUserPass.assign(userpass_data->begin(), userpass_data->end());
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().ToStringAddrPort();
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 = request.find_value("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  LogPrintf("Using rpcauth authentication.\n");
256  for (const std::string& rpcauth : gArgs.GetArgs("-rpcauth")) {
257  std::vector<std::string> fields{SplitString(rpcauth, ':')};
258  const std::vector<std::string> salt_hmac{SplitString(fields.back(), '$')};
259  if (fields.size() == 2 && salt_hmac.size() == 2) {
260  fields.pop_back();
261  fields.insert(fields.end(), salt_hmac.begin(), salt_hmac.end());
262  g_rpcauth.push_back(fields);
263  } else {
264  LogPrintf("Invalid -rpcauth argument.\n");
265  return false;
266  }
267  }
268  }
269 
270  g_rpc_whitelist_default = gArgs.GetBoolArg("-rpcwhitelistdefault", gArgs.IsArgSet("-rpcwhitelist"));
271  for (const std::string& strRPCWhitelist : gArgs.GetArgs("-rpcwhitelist")) {
272  auto pos = strRPCWhitelist.find(':');
273  std::string strUser = strRPCWhitelist.substr(0, pos);
274  bool intersect = g_rpc_whitelist.count(strUser);
275  std::set<std::string>& whitelist = g_rpc_whitelist[strUser];
276  if (pos != std::string::npos) {
277  std::string strWhitelist = strRPCWhitelist.substr(pos + 1);
278  std::vector<std::string> whitelist_split = SplitString(strWhitelist, ", ");
279  std::set<std::string> new_whitelist{
280  std::make_move_iterator(whitelist_split.begin()),
281  std::make_move_iterator(whitelist_split.end())};
282  if (intersect) {
283  std::set<std::string> tmp_whitelist;
284  std::set_intersection(new_whitelist.begin(), new_whitelist.end(),
285  whitelist.begin(), whitelist.end(), std::inserter(tmp_whitelist, tmp_whitelist.end()));
286  new_whitelist = std::move(tmp_whitelist);
287  }
288  whitelist = std::move(new_whitelist);
289  }
290  }
291 
292  return true;
293 }
294 
295 bool StartHTTPRPC(const std::any& context)
296 {
297  LogPrint(BCLog::RPC, "Starting HTTP RPC server\n");
298  if (!InitRPCAuthentication())
299  return false;
300 
301  auto handle_rpc = [context](HTTPRequest* req, const std::string&) { return HTTPReq_JSONRPC(context, req); };
302  RegisterHTTPHandler("/", true, handle_rpc);
304  RegisterHTTPHandler("/wallet/", false, handle_rpc);
305  }
306  struct event_base* eventBase = EventBase();
307  assert(eventBase);
308  httpRPCTimerInterface = std::make_unique<HTTPRPCTimerInterface>(eventBase);
310  return true;
311 }
312 
314 {
315  LogPrint(BCLog::RPC, "Interrupting HTTP RPC server\n");
316 }
317 
319 {
320  LogPrint(BCLog::RPC, "Stopping HTTP RPC server\n");
321  UnregisterHTTPHandler("/", true);
323  UnregisterHTTPHandler("/wallet/", false);
324  }
325  if (httpRPCTimerInterface) {
327  httpRPCTimerInterface.reset();
328  }
329 }
bool isObject() const
Definition: univalue.h:85
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition: args.cpp:370
bool TimingResistantEqual(const T &a, const T &b)
Timing-attack-resistant comparison.
Definition: strencodings.h:253
RPC timer "driver".
Definition: server.h:59
std::any context
Definition: request.h:38
#define LogPrint(category,...)
Definition: logging.h:246
HTTPRPCTimerInterface(struct event_base *_base)
Definition: httprpc.cpp:49
assert(!tx.IsCoinBase())
const char * Name() override
Implementation name.
Definition: httprpc.cpp:52
static const char * WWW_AUTH_HEADER_DATA
WWW-Authenticate to present with 401 Unauthorized response.
Definition: httprpc.cpp:26
static std::string strRPCUserColonPass
Definition: httprpc.cpp:66
HTTPEvent ev
Definition: httprpc.cpp:43
bool read(std::string_view raw)
Event class.
Definition: httpserver.h:154
static std::vector< std::vector< std::string > > g_rpcauth
Definition: httprpc.cpp:70
static bool InitRPCAuthentication()
Definition: httprpc.cpp:242
struct event_base * base
Definition: httprpc.cpp:61
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:56
std::string_view TrimStringView(std::string_view str, std::string_view pattern=" \\\)
Definition: string.h:31
const std::string & get_str() const
const UniValue & get_array() const
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: args.cpp:506
bool StartHTTPRPC(const std::any &context)
Start HTTP RPC subsystem.
Definition: httprpc.cpp:295
void InterruptHTTPRPC()
Interrupt HTTP RPC subsystem.
Definition: httprpc.cpp:313
Int getInt() const
Definition: univalue.h:137
std::vector< std::string > SplitString(std::string_view str, char sep)
Definition: string.h:21
std::string ToStringAddrPort() const
Definition: netaddress.cpp:889
void RPCUnsetTimerInterface(RPCTimerInterface *iface)
Unset factory function for timers.
Definition: server.cpp:582
void RegisterHTTPHandler(const std::string &prefix, bool exactMatch, const HTTPRequestHandler &handler)
Register handler for prefix.
Definition: httpserver.cpp:745
UniValue execute(const JSONRPCRequest &request) const
Execute a method.
Definition: server.cpp:509
const UniValue & find_value(std::string_view key) const
Definition: univalue.cpp:233
std::string strMethod
Definition: request.h:32
static std::unique_ptr< HTTPRPCTimerInterface > httpRPCTimerInterface
Definition: httprpc.cpp:68
static bool RPCAuthorized(const std::string &strAuth, std::string &strAuthUsernameOut)
Definition: httprpc.cpp:125
CRPCTable tableRPC
Definition: server.cpp:606
std::string peerAddr
Definition: request.h:37
static bool multiUserAuthorized(std::string strUserPass)
Definition: httprpc.cpp:94
UniValue JSONRPCError(int code, const std::string &message)
Definition: request.cpp:58
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
void WriteReply(int nStatus, const std::string &strReply="")
Write HTTP reply.
Definition: httpserver.cpp:640
Simple one-shot callback timer to be used by the RPC mechanism to e.g.
Definition: httprpc.cpp:31
std::optional< std::vector< unsigned char > > DecodeBase64(std::string_view str)
RequestMethod GetRequestMethod() const
Get request method.
Definition: httpserver.cpp:695
std::string JSONRPCExecBatch(const JSONRPCRequest &jreq, const UniValue &vReq)
Definition: server.cpp:382
UniValue id
Definition: request.h:31
void UnregisterHTTPHandler(const std::string &prefix, bool exactMatch)
Unregister handler for prefix.
Definition: httpserver.cpp:752
WalletContext context
struct event_base * EventBase()
Return evhttp event base.
Definition: httpserver.cpp:552
std::string JSONRPCReply(const UniValue &result, const UniValue &error, const UniValue &id)
Definition: request.cpp:52
void StopHTTPRPC()
Stop HTTP RPC subsystem.
Definition: httprpc.cpp:318
ArgsManager gArgs
Definition: args.cpp:42
static bool HTTPReq_JSONRPC(const std::any &context, HTTPRequest *req)
Definition: httprpc.cpp:147
const WalletInitInterface & g_wallet_init_interface
Definition: dummywallet.cpp:59
void parse(const UniValue &valRequest)
Definition: request.cpp:166
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:34
void UninterruptibleSleep(const std::chrono::microseconds &n)
Definition: time.cpp:23
void WriteHeader(const std::string &hdr, const std::string &value)
Write output header.
Definition: httpserver.cpp:628
void trigger(struct timeval *tv)
Trigger the event.
Definition: httpserver.cpp:576
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: args.cpp:456
std::string URI
Definition: request.h:35
std::string authUser
Definition: request.h:36
void RPCSetTimerInterface(RPCTimerInterface *iface)
Set the factory function for timers.
Definition: server.cpp:577
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:597
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:85
const UniValue NullUniValue
Definition: univalue.cpp:16
CService GetPeer() const
Get CService (address:ip) for the origin of the http request.
Definition: httpserver.cpp:670
std::string ReadBody()
Read request body.
Definition: httpserver.cpp:608
Standard JSON-RPC 2.0 errors.
Definition: protocol.h:28
In-flight HTTP request.
Definition: httpserver.h:56
size_t size() const
Definition: univalue.h:70
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: args.cpp:361
#define LogPrintf(...)
Definition: logging.h:237
bool isArray() const
Definition: univalue.h:84
std::string GetURI() const
Get requested URI.
Definition: httpserver.cpp:690
static struct event_base * eventBase
HTTP module state.
Definition: httpserver.cpp:141