45 tv.tv_sec = millis/1000;
46 tv.tv_usec = (millis%1000)*1000;
59 const char*
Name()
override
77static std::vector<std::vector<std::string>>
g_rpcauth;
98 req->
WriteHeader(
"Content-Type",
"application/json");
106 if (strUserPass.find(
':') == std::string::npos) {
109 std::string strUser = strUserPass.substr(0, strUserPass.find(
':'));
110 std::string strPass = strUserPass.substr(strUserPass.find(
':') + 1);
113 std::string strName = vFields[0];
118 std::string strSalt = vFields[1];
119 std::string strHash = vFields[2];
121 static const unsigned int KEY_SIZE = 32;
122 unsigned char out[KEY_SIZE];
124 CHMAC_SHA256(
reinterpret_cast<const unsigned char*
>(strSalt.data()), strSalt.size()).
Write(
reinterpret_cast<const unsigned char*
>(strPass.data()), strPass.size()).
Finalize(
out);
125 std::vector<unsigned char> hexvec(
out,
out+KEY_SIZE);
126 std::string strHashFromPass =
HexStr(hexvec);
135static bool RPCAuthorized(
const std::string& strAuth, std::string& strAuthUsernameOut)
137 if (strAuth.substr(0, 6) !=
"Basic ")
139 std::string_view strUserPass64 =
TrimStringView(std::string_view{strAuth}.substr(6));
141 std::string strUserPass;
142 if (!userpass_data)
return false;
143 strUserPass.assign(userpass_data->begin(), userpass_data->end());
145 if (strUserPass.find(
':') != std::string::npos)
146 strAuthUsernameOut = strUserPass.substr(0, strUserPass.find(
':'));
164 std::pair<bool, std::string> authHeader = req->
GetHeader(
"authorization");
165 if (!authHeader.first) {
175 LogPrintf(
"ThreadRPCServer incorrect password attempt from %s\n", jreq.
peerAddr);
205 jreq.
parse(valRequest);
226 }
else if (valRequest.
isArray()) {
228 if (user_has_whitelist) {
229 for (
unsigned int reqIdx = 0; reqIdx < valRequest.
size(); reqIdx++) {
230 if (!valRequest[reqIdx].isObject()) {
237 LogPrintf(
"RPC User %s not allowed to call method %s\n", jreq.
authUser, strMethod);
247 for (
size_t i{0}; i < valRequest.
size(); ++i) {
252 jreq.
parse(valRequest[i]);
256 }
catch (
const std::exception& e) {
272 if (reply.
size() == 0 && valRequest.
size() > 0) {
280 req->
WriteHeader(
"Content-Type",
"application/json");
285 }
catch (
const std::exception& e) {
296 std::optional<fs::perms> cookie_perms{std::nullopt};
297 auto cookie_perms_arg{
gArgs.
GetArg(
"-rpccookieperms")};
298 if (cookie_perms_arg) {
301 LogError(
"Invalid -rpccookieperms=%s; must be one of 'owner', 'group', or 'all'.", *cookie_perms_arg);
304 cookie_perms = *perm_opt;
312 LogInfo(
"RPC authentication cookie file generation is disabled.");
314 LogInfo(
"Using random cookie authentication.");
317 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");
322 LogInfo(
"Using rpcauth authentication.\n");
323 for (
const std::string& rpcauth :
gArgs.
GetArgs(
"-rpcauth")) {
324 std::vector<std::string> fields{
SplitString(rpcauth,
':')};
325 const std::vector<std::string> salt_hmac{
SplitString(fields.back(),
'$')};
326 if (fields.size() == 2 && salt_hmac.size() == 2) {
328 fields.insert(fields.end(), salt_hmac.begin(), salt_hmac.end());
331 LogPrintf(
"Invalid -rpcauth argument.\n");
338 for (
const std::string& strRPCWhitelist :
gArgs.
GetArgs(
"-rpcwhitelist")) {
339 auto pos = strRPCWhitelist.find(
':');
340 std::string strUser = strRPCWhitelist.substr(0, pos);
343 if (pos != std::string::npos) {
344 std::string strWhitelist = strRPCWhitelist.substr(pos + 1);
345 std::vector<std::string> whitelist_split =
SplitString(strWhitelist,
", ");
346 std::set<std::string> new_whitelist{
347 std::make_move_iterator(whitelist_split.begin()),
348 std::make_move_iterator(whitelist_split.end())};
350 std::set<std::string> tmp_whitelist;
351 std::set_intersection(new_whitelist.begin(), new_whitelist.end(),
352 whitelist.begin(), whitelist.end(), std::inserter(tmp_whitelist, tmp_whitelist.end()));
353 new_whitelist = std::move(tmp_whitelist);
355 whitelist = std::move(new_whitelist);
#define Assume(val)
Assume is the identity function.
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 unsigned char *data, size_t len)
void Finalize(unsigned char hash[OUTPUT_SIZE])
std::string ToStringAddrPort() const
void trigger(struct timeval *tv)
Trigger the event.
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, std::string_view reply="")
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.
JSONRPCVersion m_json_version
bool IsNotification() const
void parse(const UniValue &valRequest)
std::optional< UniValue > id
Opaque base class for timers returned by NewTimerFunc.
void push_back(UniValue val)
const std::string & get_str() const
const UniValue & find_value(std::string_view key) const
std::string write(unsigned int prettyIndent=0, unsigned int indentLevel=0) const
const UniValue & get_obj() const
bool read(std::string_view raw)
virtual bool HasWalletSupport() const =0
Is the wallet component enabled.
const WalletInitInterface & g_wallet_init_interface
std::optional< fs::perms > InterpretPermString(const std::string &s)
Interpret a custom permissions level string as fs::perms.
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
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 bool multiUserAuthorized(std::string strUserPass)
bool StartHTTPRPC(const std::any &context)
Start HTTP RPC subsystem.
static bool g_rpc_whitelist_default
static bool RPCAuthorized(const std::string &strAuth, std::string &strAuthUsernameOut)
static std::vector< std::vector< std::string > > g_rpcauth
static bool HTTPReq_JSONRPC(const std::any &context, HTTPRequest *req)
static std::string strRPCUserColonPass
static bool InitRPCAuthentication()
static std::map< std::string, std::set< std::string > > g_rpc_whitelist
static void JSONErrorReply(HTTPRequest *req, UniValue objError, const JSONRPCRequest &jreq)
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.
static struct event_base * eventBase
HTTP module state.
struct event_base * EventBase()
Return evhttp event base.
#define LogDebug(category,...)
std::vector< std::string > SplitString(std::string_view str, char sep)
std::string_view TrimStringView(std::string_view str, std::string_view pattern=" \f\n\r\t\v")
UniValue JSONRPCError(int code, const std::string &message)
UniValue JSONRPCReplyObj(UniValue result, UniValue error, std::optional< UniValue > id, JSONRPCVersion jsonrpc_version)
bool GenerateAuthCookie(std::string *cookie_out, std::optional< fs::perms > cookie_perms)
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.
UniValue JSONRPCExec(const JSONRPCRequest &jreq, bool catch_errors)
void RPCSetTimerInterface(RPCTimerInterface *iface)
Set the factory function for timers.
bool TimingResistantEqual(const T &a, const T &b)
Timing-attack-resistant comparison.
void UninterruptibleSleep(const std::chrono::microseconds &n)
const UniValue NullUniValue
std::optional< std::vector< unsigned char > > DecodeBase64(std::string_view str)