Raven Core  3.0.0
P2P Digital Currency
httprpc.cpp
Go to the documentation of this file.
1 // Copyright (c) 2015-2016 The Bitcoin Core developers
2 // Copyright (c) 2017-2019 The Raven Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 
6 #include "httprpc.h"
7 
8 #include "base58.h"
9 #include "chainparams.h"
10 #include "httpserver.h"
11 #include "rpc/protocol.h"
12 #include "rpc/server.h"
13 #include "random.h"
14 #include "sync.h"
15 #include "util.h"
16 #include "utilstrencodings.h"
17 #include "ui_interface.h"
18 #include "crypto/hmac_sha256.h"
19 #include <stdio.h>
20 
21 #include <boost/algorithm/string.hpp> // boost::trim
22 
24 static const char* WWW_AUTH_HEADER_DATA = "Basic realm=\"jsonrpc\"";
25 
29 class HTTPRPCTimer : public RPCTimerBase
30 {
31 public:
32  HTTPRPCTimer(struct event_base* eventBase, std::function<void(void)>& func, int64_t millis) :
33  ev(eventBase, false, func)
34  {
35  struct timeval tv;
36  tv.tv_sec = millis/1000;
37  tv.tv_usec = (millis%1000)*1000;
38  ev.trigger(&tv);
39  }
40 private:
42 };
43 
45 {
46 public:
47  explicit HTTPRPCTimerInterface(struct event_base* _base) : base(_base)
48  {
49  }
50  const char* Name() override
51  {
52  return "HTTP";
53  }
54  RPCTimerBase* NewTimer(std::function<void(void)>& func, int64_t millis) override
55  {
56  return new HTTPRPCTimer(base, func, millis);
57  }
58 private:
59  struct event_base* base;
60 };
61 
62 
63 /* Pre-base64-encoded authentication token */
64 static std::string strRPCUserColonPass;
65 /* Stored RPC timer interface (for unregistration) */
66 static HTTPRPCTimerInterface* httpRPCTimerInterface = nullptr;
67 
68 static void JSONErrorReply(HTTPRequest* req, const UniValue& objError, const UniValue& id)
69 {
70  // Send error reply from json-rpc error object
71  int nStatus = HTTP_INTERNAL_SERVER_ERROR;
72  int code = find_value(objError, "code").get_int();
73 
74  if (code == RPC_INVALID_REQUEST)
75  nStatus = HTTP_BAD_REQUEST;
76  else if (code == RPC_METHOD_NOT_FOUND)
77  nStatus = HTTP_NOT_FOUND;
78 
79  std::string strReply = JSONRPCReply(NullUniValue, objError, id);
80 
81  req->WriteHeader("Content-Type", "application/json");
82  req->WriteReply(nStatus, strReply);
83 }
84 
85 //This function checks username and password against -rpcauth
86 //entries from config file.
87 static bool multiUserAuthorized(std::string strUserPass)
88 {
89  if (strUserPass.find(":") == std::string::npos) {
90  return false;
91  }
92  std::string strUser = strUserPass.substr(0, strUserPass.find(":"));
93  std::string strPass = strUserPass.substr(strUserPass.find(":") + 1);
94 
95  for (const std::string& strRPCAuth : gArgs.GetArgs("-rpcauth")) {
96  //Search for multi-user login/pass "rpcauth" from config
97  std::vector<std::string> vFields;
98  boost::split(vFields, strRPCAuth, boost::is_any_of(":$"));
99  if (vFields.size() != 3) {
100  //Incorrect formatting in config file
101  continue;
102  }
103 
104  std::string strName = vFields[0];
105  if (!TimingResistantEqual(strName, strUser)) {
106  continue;
107  }
108 
109  std::string strSalt = vFields[1];
110  std::string strHash = vFields[2];
111 
112  static const unsigned int KEY_SIZE = 32;
113  unsigned char out[KEY_SIZE];
114 
115  CHMAC_SHA256(reinterpret_cast<const unsigned char*>(strSalt.c_str()), strSalt.size()).Write(reinterpret_cast<const unsigned char*>(strPass.c_str()), strPass.size()).Finalize(out);
116  std::vector<unsigned char> hexvec(out, out+KEY_SIZE);
117  std::string strHashFromPass = HexStr(hexvec);
118 
119  if (TimingResistantEqual(strHashFromPass, strHash)) {
120  return true;
121  }
122  }
123  return false;
124 }
125 
126 static bool RPCAuthorized(const std::string& strAuth, std::string& strAuthUsernameOut)
127 {
128  if (strRPCUserColonPass.empty()) // Belt-and-suspenders measure if InitRPCAuthentication was not called
129  return false;
130  if (strAuth.substr(0, 6) != "Basic ")
131  return false;
132  std::string strUserPass64 = strAuth.substr(6);
133  boost::trim(strUserPass64);
134  std::string strUserPass = DecodeBase64(strUserPass64);
135 
136  if (strUserPass.find(":") != std::string::npos)
137  strAuthUsernameOut = strUserPass.substr(0, strUserPass.find(":"));
138 
139  //Check if authorized under single-user field
140  if (TimingResistantEqual(strUserPass, strRPCUserColonPass)) {
141  return true;
142  }
143  return multiUserAuthorized(strUserPass);
144 }
145 
146 static bool HTTPReq_JSONRPC(HTTPRequest* req, const std::string &)
147 {
148  // JSONRPC handles only POST
149  if (req->GetRequestMethod() != HTTPRequest::POST) {
150  req->WriteReply(HTTP_BAD_METHOD, "JSONRPC server handles only POST requests");
151  return false;
152  }
153  // Check authorization
154  std::pair<bool, std::string> authHeader = req->GetHeader("authorization");
155  if (!authHeader.first) {
156  req->WriteHeader("WWW-Authenticate", WWW_AUTH_HEADER_DATA);
158  return false;
159  }
160 
161  JSONRPCRequest jreq;
162  if (!RPCAuthorized(authHeader.second, jreq.authUser)) {
163  LogPrintf("ThreadRPCServer incorrect password attempt from %s\n", req->GetPeer().ToString());
164 
165  /* Deter brute-forcing
166  If this results in a DoS the user really
167  shouldn't have their RPC port exposed. */
168  MilliSleep(250);
169 
170  req->WriteHeader("WWW-Authenticate", WWW_AUTH_HEADER_DATA);
172  return false;
173  }
174 
175  try {
176  // Parse request
177  UniValue valRequest;
178  if (!valRequest.read(req->ReadBody()))
179  throw JSONRPCError(RPC_PARSE_ERROR, "Parse error");
180 
181  // Set the URI
182  jreq.URI = req->GetURI();
183 
184  std::string strReply;
185  // singleton request
186  if (valRequest.isObject()) {
187  jreq.parse(valRequest);
188 
189  UniValue result = tableRPC.execute(jreq);
190 
191  // Send reply
192  strReply = JSONRPCReply(result, NullUniValue, jreq.id);
193 
194  // array of requests
195  } else if (valRequest.isArray())
196  strReply = JSONRPCExecBatch(jreq, valRequest.get_array());
197  else
198  throw JSONRPCError(RPC_PARSE_ERROR, "Top-level object parse error");
199 
200  req->WriteHeader("Content-Type", "application/json");
201  req->WriteReply(HTTP_OK, strReply);
202  } catch (const UniValue& objError) {
203  JSONErrorReply(req, objError, jreq.id);
204  return false;
205  } catch (const std::exception& e) {
206  JSONErrorReply(req, JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
207  return false;
208  }
209  return true;
210 }
211 
212 static bool InitRPCAuthentication()
213 {
214  if (gArgs.GetArg("-rpcpassword", "") == "")
215  {
216  LogPrintf("No rpcpassword set - using random cookie authentication\n");
217  if (!GenerateAuthCookie(&strRPCUserColonPass)) {
219  _("Error: A fatal internal error occurred, see debug.log for details"), // Same message as AbortNode
221  return false;
222  }
223  } else {
224  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/rpcuser for rpcauth auth generation.\n");
225  strRPCUserColonPass = gArgs.GetArg("-rpcuser", "") + ":" + gArgs.GetArg("-rpcpassword", "");
226  }
227  return true;
228 }
229 
231 {
232  LogPrint(BCLog::RPC, "Starting HTTP RPC server\n");
233  if (!InitRPCAuthentication())
234  return false;
235 
236  RegisterHTTPHandler("/", true, HTTPReq_JSONRPC);
237 #ifdef ENABLE_WALLET
238  // ifdef can be removed once we switch to better endpoint support and API versioning
239  RegisterHTTPHandler("/wallet/", false, HTTPReq_JSONRPC);
240 #endif
241  assert(EventBase());
242  httpRPCTimerInterface = new HTTPRPCTimerInterface(EventBase());
243  RPCSetTimerInterface(httpRPCTimerInterface);
244  return true;
245 }
246 
248 {
249  LogPrint(BCLog::RPC, "Interrupting HTTP RPC server\n");
250 }
251 
253 {
254  LogPrint(BCLog::RPC, "Stopping HTTP RPC server\n");
255  UnregisterHTTPHandler("/", true);
256  if (httpRPCTimerInterface) {
257  RPCUnsetTimerInterface(httpRPCTimerInterface);
258  delete httpRPCTimerInterface;
259  httpRPCTimerInterface = nullptr;
260  }
261 }
bool isObject() const
Definition: univalue.h:86
RPC timer "driver".
Definition: server.h:101
HTTPRPCTimer(struct event_base *eventBase, std::function< void(void)> &func, int64_t millis)
Definition: httprpc.cpp:32
std::vector< unsigned char > DecodeBase64(const char *p, bool *pfInvalid)
HTTPRPCTimerInterface(struct event_base *_base)
Definition: httprpc.cpp:47
void MilliSleep(int64_t n)
Definition: utiltime.cpp:61
const char * Name() override
Implementation name.
Definition: httprpc.cpp:50
bool read(const char *raw, size_t len)
HTTPEvent ev
Definition: httprpc.cpp:41
std::pair< bool, std::string > GetHeader(const std::string &hdr)
Get the request header specified by hdr, or an empty string.
Definition: httpserver.cpp:555
Event class.
Definition: httpserver.h:131
bool StartHTTPRPC()
Start HTTP RPC subsystem.
Definition: httprpc.cpp:230
std::string GetURI()
Get requested URI.
Definition: httpserver.cpp:626
std::string HexStr(const T itbegin, const T itend, bool fSpaces=false)
struct event_base * base
Definition: httprpc.cpp:59
A hasher class for HMAC-SHA-256.
Definition: hmac_sha256.h:15
const UniValue & get_array() const
void InterruptHTTPRPC()
Interrupt HTTP RPC subsystem.
Definition: httprpc.cpp:247
std::string JSONRPCReply(const UniValue &result, const UniValue &error, const UniValue &id)
Definition: protocol.cpp:49
RequestMethod GetRequestMethod()
Get request method.
Definition: httpserver.cpp:631
void RPCUnsetTimerInterface(RPCTimerInterface *iface)
Unset factory function for timers.
Definition: server.cpp:544
const UniValue & find_value(const UniValue &obj, const std::string &name)
Definition: univalue.cpp:236
void RegisterHTTPHandler(const std::string &prefix, bool exactMatch, const HTTPRequestHandler &handler)
Register handler for prefix.
Definition: httpserver.cpp:652
UniValue execute(const JSONRPCRequest &request) const
Execute a method.
Definition: server.cpp:480
bool TimingResistantEqual(const T &a, const T &b)
Timing-attack-resistant comparison.
CRPCTable tableRPC
Definition: server.cpp:567
#define LogPrintf(...)
Definition: util.h:149
void WriteReply(int nStatus, const std::string &strReply="")
Write HTTP reply.
Definition: httpserver.cpp:598
Simple one-shot callback timer to be used by the RPC mechanism to e.g.
Definition: httprpc.cpp:29
std::string JSONRPCExecBatch(const JSONRPCRequest &jreq, const UniValue &vReq)
Definition: server.cpp:421
UniValue id
Definition: server.h:43
void UnregisterHTTPHandler(const std::string &prefix, bool exactMatch)
Unregister handler for prefix.
Definition: httpserver.cpp:658
int get_int() const
CService GetPeer()
Get CService (address:ip) for the origin of the http request.
Definition: httpserver.cpp:612
struct event_base * EventBase()
Return evhttp event base.
Definition: httpserver.cpp:510
void StopHTTPRPC()
Stop HTTP RPC subsystem.
Definition: httprpc.cpp:252
#define LogPrint(category,...)
Definition: util.h:160
void parse(const UniValue &valRequest)
Definition: server.cpp:362
ArgsManager gArgs
Definition: util.cpp:94
bool GenerateAuthCookie(std::string *cookie_out)
Generate a new RPC authentication cookie and write it to disk.
Definition: protocol.cpp:82
void WriteHeader(const std::string &hdr, const std::string &value)
Write output header.
Definition: httpserver.cpp:586
void trigger(struct timeval *tv)
Trigger the event.
Definition: httpserver.cpp:534
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: util.cpp:454
std::string URI
Definition: server.h:47
std::string authUser
Definition: server.h:48
void RPCSetTimerInterface(RPCTimerInterface *iface)
Set the factory function for timers.
Definition: server.cpp:539
Opaque base class for timers returned by NewTimerFunc.
Definition: server.h:92
const UniValue NullUniValue
Definition: univalue.cpp:15
boost::signals2::signal< bool(const std::string &message, const std::string &caption, unsigned int style), boost::signals2::last_value< bool > > ThreadSafeMessageBox
Show message box.
Definition: ui_interface.h:76
std::string ReadBody()
Read request body.
Definition: httpserver.cpp:566
Standard JSON-RPC 2.0 errors.
Definition: protocol.h:38
std::string ToString() const
Definition: netaddress.cpp:597
UniValue JSONRPCError(int code, const std::string &message)
Definition: protocol.cpp:55
In-flight HTTP request.
Definition: httpserver.h:58
CClientUIInterface uiInterface
Definition: ui_interface.cpp:9
std::vector< std::string > GetArgs(const std::string &strArg) const
Return a vector of strings of the given argument.
Definition: util.cpp:440
bool isArray() const
Definition: univalue.h:85
RPCTimerBase * NewTimer(std::function< void(void)> &func, int64_t millis) override
Factory function for timers.
Definition: httprpc.cpp:54
std::string _(const char *psz)
Translation function: Call Translate signal on UI interface, which returns a boost::optional result...
Definition: util.h:66