25 #include <boost/algorithm/string.hpp>
37 ev(eventBase, false, func)
40 tv.tv_sec = millis/1000;
41 tv.tv_usec = (millis%1000)*1000;
54 const char*
Name()
override
88 req->
WriteHeader(
"Content-Type",
"application/json");
96 if (strUserPass.find(
':') == std::string::npos) {
99 std::string strUser = strUserPass.substr(0, strUserPass.find(
':'));
100 std::string strPass = strUserPass.substr(strUserPass.find(
':') + 1);
102 for (
const std::string& strRPCAuth :
gArgs.
GetArgs(
"-rpcauth")) {
104 std::vector<std::string> vFields;
105 boost::split(vFields, strRPCAuth, boost::is_any_of(
":$"));
106 if (vFields.size() != 3) {
111 std::string strName = vFields[0];
116 std::string strSalt = vFields[1];
117 std::string strHash = vFields[2];
119 static const unsigned int KEY_SIZE = 32;
120 unsigned char out[KEY_SIZE];
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);
133 static bool RPCAuthorized(
const std::string& strAuth, std::string& strAuthUsernameOut)
135 if (strRPCUserColonPass.empty())
137 if (strAuth.substr(0, 6) !=
"Basic ")
139 std::string strUserPass64 = strAuth.substr(6);
140 boost::trim(strUserPass64);
143 if (strUserPass.find(
':') != std::string::npos)
144 strAuthUsernameOut = strUserPass.substr(0, strUserPass.find(
':'));
161 std::pair<bool, std::string> authHeader = req->
GetHeader(
"authorization");
162 if (!authHeader.first) {
171 LogPrintf(
"ThreadRPCServer incorrect password attempt from %s\n", jreq.
peerAddr);
192 std::string strReply;
193 bool user_has_whitelist = g_rpc_whitelist.count(jreq.
authUser);
194 if (!user_has_whitelist && g_rpc_whitelist_default) {
201 jreq.
parse(valRequest);
202 if (user_has_whitelist && !g_rpc_whitelist[jreq.
authUser].count(jreq.
strMethod)) {
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()) {
222 if (!g_rpc_whitelist[jreq.
authUser].count(strMethod)) {
223 LogPrintf(
"RPC User %s not allowed to call method %s\n", jreq.
authUser, strMethod);
235 req->
WriteHeader(
"Content-Type",
"application/json");
237 }
catch (
const UniValue& objError) {
240 }
catch (
const std::exception& e) {
251 LogPrintf(
"Using random cookie authentication.\n");
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");
261 LogPrintf(
"Using rpcauth authentication.\n");
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(
", "));
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);
280 whitelist = std::move(new_whitelist);
300 httpRPCTimerInterface = MakeUnique<HTTPRPCTimerInterface>(
eventBase);
317 if (httpRPCTimerInterface) {
319 httpRPCTimerInterface.reset();
UniValue execute(const JSONRPCRequest &request) const
Execute a method.
const std::string & get_str() const
bool TimingResistantEqual(const T &a, const T &b)
Timing-attack-resistant comparison.
#define LogPrint(category,...)
HTTPRPCTimerInterface(struct event_base *_base)
const char * Name() override
Implementation name.
static const char * WWW_AUTH_HEADER_DATA
WWW-Authenticate to present with 401 Unauthorized response.
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
bool read(const char *raw, size_t len)
static std::string strRPCUserColonPass
static void LogPrintf(const char *fmt, const Args &...args)
RequestMethod GetRequestMethod() const
Get request method.
static bool InitRPCAuthentication()
std::pair< bool, std::string > GetHeader(const std::string &hdr) const
Get the request header specified by hdr, or an empty string.
static void JSONErrorReply(HTTPRequest *req, const UniValue &objError, const UniValue &id)
A hasher class for HMAC-SHA-256.
RPCTimerBase * NewTimer(std::function< void()> &func, int64_t millis) override
Factory function for timers.
std::vector< unsigned char > DecodeBase64(const char *p, bool *pf_invalid)
std::string GetURI() const
Get requested URI.
void InterruptHTTPRPC()
Interrupt HTTP RPC subsystem.
void RPCUnsetTimerInterface(RPCTimerInterface *iface)
Unset factory function for timers.
const UniValue & find_value(const UniValue &obj, const std::string &name)
void RegisterHTTPHandler(const std::string &prefix, bool exactMatch, const HTTPRequestHandler &handler)
Register handler for prefix.
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.
static std::unique_ptr< HTTPRPCTimerInterface > httpRPCTimerInterface
static bool RPCAuthorized(const std::string &strAuth, std::string &strAuthUsernameOut)
static bool multiUserAuthorized(std::string strUserPass)
UniValue JSONRPCError(int code, const std::string &message)
static bool HTTPReq_JSONRPC(const util::Ref &context, HTTPRequest *req)
void WriteReply(int nStatus, const std::string &strReply="")
Write HTTP reply.
Simple one-shot callback timer to be used by the RPC mechanism to e.g.
std::string JSONRPCExecBatch(const JSONRPCRequest &jreq, const UniValue &vReq)
void UnregisterHTTPHandler(const std::string &prefix, bool exactMatch)
Unregister handler for prefix.
std::string ToString() const
struct event_base * EventBase()
Return evhttp event base.
Type-safe dynamic reference.
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
std::string JSONRPCReply(const UniValue &result, const UniValue &error, const UniValue &id)
void StopHTTPRPC()
Stop HTTP RPC subsystem.
const WalletInitInterface & g_wallet_init_interface
void parse(const UniValue &valRequest)
bool StartHTTPRPC(const util::Ref &context)
Start HTTP RPC subsystem.
static bool g_rpc_whitelist_default
HTTPRPCTimer(struct event_base *eventBase, std::function< void()> &func, int64_t millis)
const UniValue & get_array() const
void UninterruptibleSleep(const std::chrono::microseconds &n)
void WriteHeader(const std::string &hdr, const std::string &value)
Write output header.
void trigger(struct timeval *tv)
Trigger the event.
virtual bool HasWalletSupport() const =0
Is the wallet component enabled.
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
void RPCSetTimerInterface(RPCTimerInterface *iface)
Set the factory function for timers.
Opaque base class for timers returned by NewTimerFunc.
bool GenerateAuthCookie(std::string *cookie_out)
Generate a new RPC authentication cookie and write it to disk.
const UniValue NullUniValue
std::string ReadBody()
Read request body.
Standard JSON-RPC 2.0 errors.
static std::map< std::string, std::set< std::string > > g_rpc_whitelist
const UniValue & get_obj() const
CService GetPeer() const
Get CService (address:ip) for the origin of the http request.
static struct event_base * eventBase
HTTP module state.