16 #include <boost/algorithm/string.hpp>
43 tv.tv_sec = millis / 1000;
44 tv.tv_usec = (millis % 1000) * 1000;
56 const char *
Name()
override {
return "HTTP"; }
59 int64_t millis)
override {
91 req->
WriteHeader(
"Content-Type",
"application/json");
100 if (strUserPass.find(
':') == std::string::npos) {
103 std::string strUser = strUserPass.substr(0, strUserPass.find(
':'));
104 std::string strPass = strUserPass.substr(strUserPass.find(
':') + 1);
106 for (
const std::string &strRPCAuth :
gArgs.
GetArgs(
"-rpcauth")) {
108 std::vector<std::string> vFields;
109 boost::split(vFields, strRPCAuth, boost::is_any_of(
":$"));
110 if (vFields.size() != 3) {
115 std::string strName = vFields[0];
120 std::string strSalt = vFields[1];
121 std::string strHash = vFields[2];
123 static const unsigned int KEY_SIZE = 32;
124 uint8_t out[KEY_SIZE];
126 CHMAC_SHA256(
reinterpret_cast<const uint8_t *
>(strSalt.data()),
128 .
Write(
reinterpret_cast<const uint8_t *
>(strPass.data()),
131 std::vector<uint8_t> hexvec(out, out + KEY_SIZE);
132 std::string strHashFromPass =
HexStr(hexvec);
142 std::string &strAuthUsernameOut) {
148 if (strAuth.substr(0, 6) !=
"Basic ") {
152 std::string strUserPass64 = strAuth.substr(6);
153 boost::trim(strUserPass64);
156 if (strUserPass.find(
':') != std::string::npos) {
157 strAuthUsernameOut = strUserPass.substr(0, strUserPass.find(
':'));
172 std::pair<bool, std::string> origin = req->
GetHeader(
"origin");
200 std::pair<bool, std::string> method =
201 req->
GetHeader(
"access-control-request-method");
213 std::pair<bool, std::string> header_field_names =
214 req->
GetHeader(
"access-control-request-headers");
221 if (method.second !=
"POST") {
230 const std::string &list_of_headers =
"authorization,content-type";
237 req->
WriteHeader(
"Access-Control-Allow-Origin", origin.second);
238 req->
WriteHeader(
"Access-Control-Allow-Credentials",
"true");
252 req->
WriteHeader(
"Access-Control-Allow-Methods", method.second);
259 header_field_names.first ? header_field_names.second
277 req->
WriteHeader(
"Access-Control-Allow-Origin", origin.second);
278 req->
WriteHeader(
"Access-Control-Allow-Credentials",
"true");
283 req->
WriteHeader(
"Access-Control-Expose-Headers",
"WWW-Authenticate");
297 "JSONRPC server handles only POST requests");
301 std::pair<bool, std::string> authHeader = req->
GetHeader(
"authorization");
302 if (!authHeader.first) {
312 LogPrintf(
"ThreadRPCServer incorrect password attempt from %s\n",
338 std::string strReply;
341 LogPrintf(
"RPC User %s not allowed to call any methods\n",
348 jreq.
parse(valRequest);
349 if (user_has_whitelist &&
351 LogPrintf(
"RPC User %s not allowed to call method %s\n",
362 }
else if (valRequest.
isArray()) {
363 if (user_has_whitelist) {
364 for (
unsigned int reqIdx = 0; reqIdx < valRequest.
size();
366 if (!valRequest[reqIdx].isObject()) {
368 "Invalid Request object");
372 std::string strMethod =
376 "RPC User %s not allowed to call method %s\n",
390 req->
WriteHeader(
"Content-Type",
"application/json");
392 }
catch (
const UniValue &objError) {
395 }
catch (
const std::exception &e) {
404 LogPrintf(
"Using random cookie authentication.\n");
409 LogPrintf(
"Config options rpcuser and rpcpassword will soon be "
410 "deprecated. Locally-run instances may remove rpcuser to use "
411 "cookie-based auth, or may be replaced with rpcauth. Please "
412 "see share/rpcauth for rpcauth auth generation.\n");
420 LogPrintf(
"Using rpcauth authentication.\n");
425 for (
const std::string &strRPCWhitelist :
gArgs.
GetArgs(
"-rpcwhitelist")) {
426 auto pos = strRPCWhitelist.find(
':');
427 std::string strUser = strRPCWhitelist.substr(0, pos);
430 if (pos != std::string::npos) {
431 std::string strWhitelist = strRPCWhitelist.substr(pos + 1);
432 std::set<std::string> new_whitelist;
433 boost::split(new_whitelist, strWhitelist, boost::is_any_of(
", "));
435 std::set<std::string> tmp_whitelist;
436 std::set_intersection(
437 new_whitelist.begin(), new_whitelist.end(),
438 whitelist.begin(), whitelist.end(),
439 std::inserter(tmp_whitelist, tmp_whitelist.end()));
440 new_whitelist = std::move(tmp_whitelist);
442 whitelist = std::move(new_whitelist);
458 &httpRPCRequestProcessor, std::placeholders::_2);
std::vector< std::string > GetArgs(const std::string &strArg) const
Return a vector of strings of the given argument.
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
A hasher class for HMAC-SHA-256.
CHMAC_SHA256 & Write(const uint8_t *data, size_t len)
void Finalize(uint8_t hash[OUTPUT_SIZE])
std::string ToString() const
void trigger(struct timeval *tv)
Trigger the event.
bool ProcessHTTPRequest(HTTPRequest *request)
static bool DelegateHTTPRequest(HTTPRPCRequestProcessor *requestProcessor, HTTPRequest *request)
Simple one-shot callback timer to be used by the RPC mechanism to e.g.
HTTPRPCTimer(struct event_base *eventBase, std::function< void()> &func, int64_t millis)
const char * Name() override
Implementation name.
RPCTimerBase * NewTimer(std::function< void()> &func, int64_t millis) override
Factory function for timers.
HTTPRPCTimerInterface(struct event_base *_base)
std::pair< bool, std::string > GetHeader(const std::string &hdr) const
Get the request header specified by hdr, or an empty string.
std::string GetURI() const
Get requested URI.
void WriteReply(int nStatus, const std::string &strReply="")
Write HTTP reply.
void WriteHeader(const std::string &hdr, const std::string &value)
Write output header.
RequestMethod GetRequestMethod() const
Get request method.
std::string ReadBody()
Read request body.
CService GetPeer() const
Get CService (address:ip) for the origin of the http request.
void parse(const UniValue &valRequest)
UniValue ExecuteCommand(const Config &config, const JSONRPCRequest &request) const
Attempts to execute an RPC command from the given request.
Opaque base class for timers returned by NewTimerFunc.
const std::string & get_str() const
const UniValue & find_value(std::string_view key) const
const UniValue & get_obj() const
const UniValue & get_array() const
bool read(const char *raw, size_t len)
virtual bool HasWalletSupport() const =0
Is the wallet component enabled.
const WalletInitInterface & g_wallet_init_interface
static bool checkCORS(HTTPRequest *req)
static const char * WWW_AUTH_HEADER_DATA
WWW-Authenticate to present with 401 Unauthorized response.
void InterruptHTTPRPC()
Interrupt HTTP RPC subsystem.
void StopHTTPRPC()
Stop HTTP RPC subsystem.
static std::unique_ptr< HTTPRPCTimerInterface > httpRPCTimerInterface
static std::string strRPCCORSDomain
static bool multiUserAuthorized(std::string strUserPass)
static bool g_rpc_whitelist_default
static bool RPCAuthorized(const std::string &strAuth, std::string &strAuthUsernameOut)
static std::string strRPCUserColonPass
static bool InitRPCAuthentication()
static std::map< std::string, std::set< std::string > > g_rpc_whitelist
bool StartHTTPRPC(HTTPRPCRequestProcessor &httpRPCRequestProcessor)
Start HTTP RPC subsystem.
static const int64_t RPC_AUTH_BRUTE_FORCE_DELAY
RPC auth failure delay to make brute-forcing expensive.
static void JSONErrorReply(HTTPRequest *req, const UniValue &objError, const UniValue &id)
void UnregisterHTTPHandler(const std::string &prefix, bool exactMatch)
Unregister handler for prefix.
void RegisterHTTPHandler(const std::string &prefix, bool exactMatch, const HTTPRequestHandler &handler)
Register handler for prefix.
struct event_base * EventBase()
Return evhttp event base.
static struct event_base * eventBase
HTTP module state.
#define LogPrint(category,...)
std::string JSONRPCReply(const UniValue &result, const UniValue &error, const UniValue &id)
UniValue JSONRPCError(int code, const std::string &message)
bool GenerateAuthCookie(std::string *cookie_out)
Generate a new RPC authentication cookie and write it to disk.
@ HTTP_INTERNAL_SERVER_ERROR
@ RPC_INVALID_REQUEST
Standard JSON-RPC 2.0 errors.
void RPCUnsetTimerInterface(RPCTimerInterface *iface)
Unset factory function for timers.
std::string JSONRPCExecBatch(const Config &config, RPCServer &rpcServer, const JSONRPCRequest &jreq, const UniValue &vReq)
void RPCSetTimerInterface(RPCTimerInterface *iface)
Set the factory function for timers.
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
std::vector< uint8_t > DecodeBase64(const char *p, bool *pf_invalid)
bool TimingResistantEqual(const T &a, const T &b)
Timing-attack-resistant comparison.
void UninterruptibleSleep(const std::chrono::microseconds &n)
const UniValue NullUniValue