37static std::vector<std::vector<std::string>>
g_rpcauth;
70 const std::string& salt = fields[1];
71 const std::string& hash = fields[2];
73 std::array<unsigned char, CHMAC_SHA256::OUTPUT_SIZE>
out;
84static bool RPCAuthorized(
const std::string& strAuth, std::string& strAuthUsernameOut)
86 if (!strAuth.starts_with(
"Basic "))
88 std::string_view strUserPass64 =
TrimStringView(std::string_view{strAuth}.substr(6));
90 std::string strUserPass;
91 if (!userpass_data)
return false;
92 strUserPass.assign(userpass_data->begin(), userpass_data->end());
94 size_t colon_pos = strUserPass.find(
':');
95 if (colon_pos == std::string::npos) {
98 std::string user = strUserPass.substr(0, colon_pos);
99 std::string pass = strUserPass.substr(colon_pos + 1);
100 strAuthUsernameOut = user;
116 jreq.
parse(valRequest);
136 }
else if (valRequest.
isArray()) {
138 if (user_has_whitelist) {
139 for (
unsigned int reqIdx = 0; reqIdx < valRequest.
size(); reqIdx++) {
140 if (!valRequest[reqIdx].isObject()) {
157 for (
size_t i{0}; i < valRequest.
size(); ++i) {
162 jreq.
parse(valRequest[i]);
166 }
catch (
const std::exception& e) {
182 if (reply.
size() == 0 && valRequest.
size() > 0) {
192 }
catch (
const std::exception& e) {
205 std::pair<bool, std::string> authHeader = req->
GetHeader(
"authorization");
206 if (!authHeader.first) {
244 req->
WriteHeader(
"Content-Type",
"application/json");
256 std::optional<fs::perms> cookie_perms{std::nullopt};
257 auto cookie_perms_arg{
gArgs.
GetArg(
"-rpccookieperms")};
258 if (cookie_perms_arg) {
261 LogError(
"Invalid -rpccookieperms=%s; must be one of 'owner', 'group', or 'all'.", *cookie_perms_arg);
264 cookie_perms = *perm_opt;
271 LogInfo(
"RPC authentication cookie file generation is disabled.");
274 LogInfo(
"Using random cookie authentication.");
278 LogInfo(
"Using rpcuser/rpcpassword authentication.");
279 LogWarning(
"The use of rpcuser/rpcpassword is less secure, because credentials are configured in plain text. It is recommended that locally-run instances switch to cookie-based auth, or otherwise to use hashed rpcauth credentials. See share/rpcauth in the source directory for more information.");
285 if (!user.empty() || !pass.empty()) {
287 std::array<unsigned char, 16> raw_salt;
289 std::string salt =
HexStr(raw_salt);
292 std::array<unsigned char, CHMAC_SHA256::OUTPUT_SIZE>
out;
300 LogInfo(
"Using rpcauth authentication.\n");
301 for (
const std::string& rpcauth :
gArgs.
GetArgs(
"-rpcauth")) {
302 std::vector<std::string> fields{
SplitString(rpcauth,
':')};
303 const std::vector<std::string> salt_hmac{
SplitString(fields.back(),
'$')};
304 if (fields.size() == 2 && salt_hmac.size() == 2) {
306 fields.insert(fields.end(), salt_hmac.begin(), salt_hmac.end());
316 for (
const std::string& strRPCWhitelist :
gArgs.
GetArgs(
"-rpcwhitelist")) {
317 auto pos = strRPCWhitelist.find(
':');
318 std::string strUser = strRPCWhitelist.substr(0, pos);
321 if (pos != std::string::npos) {
322 std::string strWhitelist = strRPCWhitelist.substr(pos + 1);
323 std::vector<std::string> whitelist_split =
SplitString(strWhitelist,
", ");
324 std::set<std::string> new_whitelist{
325 std::make_move_iterator(whitelist_split.begin()),
326 std::make_move_iterator(whitelist_split.end())};
328 std::set<std::string> tmp_whitelist;
329 std::set_intersection(new_whitelist.begin(), new_whitelist.end(),
330 whitelist.begin(), whitelist.end(), std::inserter(tmp_whitelist, tmp_whitelist.end()));
331 new_whitelist = std::move(tmp_whitelist);
333 whitelist = std::move(new_whitelist);
#define Assume(val)
Assume is the identity function.
std::vector< std::string > GetArgs(const std::string &strArg) const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Return a vector of strings of the given argument.
std::string GetArg(const std::string &strArg, const std::string &strDefault) const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Return string argument or default value.
bool GetBoolArg(const std::string &strArg, bool fDefault) const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
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
JSONRPCVersion m_json_version
bool IsNotification() const
void parse(const UniValue &valRequest)
std::optional< UniValue > id
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.
std::string GetURI() const
std::string ReadBody() const
std::pair< bool, std::string > GetHeader(std::string_view hdr) const
void WriteHeader(std::string &&hdr, std::string &&value)
HTTPRequestMethod GetRequestMethod() const
void WriteReply(HTTPStatusCode status, std::span< const std::byte > reply_body={})
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 std::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.
UniValue ExecuteHTTPRPC(const UniValue &valRequest, JSONRPCRequest &jreq, HTTPStatusCode &status)
Execute a single HTTP request containing one or more JSONRPC requests.
void InterruptHTTPRPC()
Interrupt HTTP RPC subsystem.
void StopHTTPRPC()
Stop HTTP RPC subsystem.
static bool CheckUserAuthorized(std::string_view user, std::string_view pass)
bool StartHTTPRPC(const std::any &context)
Start HTTP RPC subsystem.
static bool g_rpc_whitelist_default
static void HTTPReq_JSONRPC(const std::any &context, HTTPRequest *req)
static bool RPCAuthorized(const std::string &strAuth, std::string &strAuthUsernameOut)
static std::vector< std::vector< std::string > > g_rpcauth
static bool InitRPCAuthentication()
static std::map< std::string, std::set< std::string > > g_rpc_whitelist
static UniValue JSONErrorReply(UniValue objError, const JSONRPCRequest &jreq, HTTPStatusCode &nStatus)
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.
#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")
void GetStrongRandBytes(std::span< unsigned char > bytes) noexcept
Gather entropy from various sources, feed it into the internal PRNG, and generate random data using i...
UniValue JSONRPCError(int code, const std::string &message)
AuthCookieResult GenerateAuthCookie(const std::optional< fs::perms > &cookie_perms, std::string &user, std::string &pass)
Generate a new RPC authentication cookie and write it to disk.
UniValue JSONRPCReplyObj(UniValue result, UniValue error, std::optional< UniValue > id, JSONRPCVersion jsonrpc_version)
HTTPStatusCode
HTTP status codes.
@ HTTP_INTERNAL_SERVER_ERROR
@ RPC_INVALID_REQUEST
Standard JSON-RPC 2.0 errors.
UniValue JSONRPCExec(const JSONRPCRequest &jreq, bool catch_errors)
unsigned char * UCharCast(char *c)
bool TimingResistantEqual(const T &a, const T &b)
Timing-attack-resistant comparison.
const UniValue NullUniValue
std::optional< std::vector< unsigned char > > DecodeBase64(std::string_view str)
void UninterruptibleSleep(const std::chrono::microseconds &n)