LCOV - code coverage report
Current view: top level - src - httprpc.cpp (source / functions) Hit Total Coverage
Test: total_coverage.info Lines: 192 215 89.3 %
Date: 2026-06-25 07:23:43 Functions: 29 29 100.0 %

          Line data    Source code
       1             : // Copyright (c) 2015-2021 The Bitcoin Core developers
       2             : // Distributed under the MIT software license, see the accompanying
       3             : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
       4             : 
       5             : #include <httprpc.h>
       6             : 
       7             : #include <crypto/hmac_sha256.h>
       8             : #include <httpserver.h>
       9             : #include <netaddress.h>
      10             : #include <rpc/protocol.h>
      11             : #include <rpc/server.h>
      12             : #include <util/strencodings.h>
      13             : #include <util/string.h>
      14             : #include <util/system.h>
      15             : #include <walletinitinterface.h>
      16             : 
      17             : #include <algorithm>
      18             : #include <iterator>
      19             : #include <map>
      20             : #include <memory>
      21             : #include <set>
      22             : #include <string>
      23             : #include <vector>
      24             : 
      25             : /** WWW-Authenticate to present with 401 Unauthorized response */
      26             : static const char* WWW_AUTH_HEADER_DATA = "Basic realm=\"jsonrpc\"";
      27             : 
      28             : /** Simple one-shot callback timer to be used by the RPC mechanism to e.g.
      29             :  * re-lock the wallet.
      30             :  */
      31             : class HTTPRPCTimer : public RPCTimerBase
      32             : {
      33             : public:
      34         280 :     HTTPRPCTimer(struct event_base* eventBase, std::function<void()>& func, int64_t millis) :
      35         140 :         ev(eventBase, false, func)
      36         280 :     {
      37             :         struct timeval tv;
      38         140 :         tv.tv_sec = millis/1000;
      39         140 :         tv.tv_usec = (millis%1000)*1000;
      40         140 :         ev.trigger(&tv);
      41         280 :     }
      42             : private:
      43             :     HTTPEvent ev;
      44             : };
      45             : 
      46             : class HTTPRPCTimerInterface : public RPCTimerInterface
      47             : {
      48             : public:
      49        9021 :     explicit HTTPRPCTimerInterface(struct event_base* _base) : base(_base)
      50        6014 :     {
      51        6014 :     }
      52         140 :     const char* Name() override
      53             :     {
      54         140 :         return "HTTP";
      55             :     }
      56         140 :     RPCTimerBase* NewTimer(std::function<void()>& func, int64_t millis) override
      57             :     {
      58         140 :         return new HTTPRPCTimer(base, func, millis);
      59           0 :     }
      60             : private:
      61             :     struct event_base* base;
      62             : };
      63             : 
      64             : 
      65             : /* Pre-base64-encoded authentication token */
      66             : static std::string strRPCUserColonPass;
      67             : /* Stored RPC timer interface (for unregistration) */
      68             : static std::unique_ptr<HTTPRPCTimerInterface> httpRPCTimerInterface;
      69             : /* List of -rpcauth values */
      70             : static std::vector<std::vector<std::string>> g_rpcauth;
      71             : /* RPC Auth Whitelist */
      72        3308 : static std::map<std::string, std::set<std::string>> g_rpc_whitelist;
      73             : static bool g_rpc_whitelist_default = false;
      74             : 
      75             : extern std::vector<std::string> g_external_usernames;
      76             : class RpcHttpRequest
      77             : {
      78             : public:
      79             :     HTTPRequest* m_req;
      80             :     int64_t m_startTime;
      81      500097 :     int m_status{0};
      82             :     std::string user;
      83             :     std::string command;
      84             : 
      85     1500291 :     RpcHttpRequest(HTTPRequest* req) :
      86      500097 :         m_req{req},
      87      500097 :         m_startTime{GetTimeMicros()}
      88     1000194 :     {}
      89             : 
      90     1000194 :     ~RpcHttpRequest()
      91      500097 :     {
      92      500097 :         const bool is_external = find(g_external_usernames.begin(), g_external_usernames.end(), user) != g_external_usernames.end();
      93      500097 :         LogPrint(BCLog::BENCHMARK, "HTTP RPC request handled: user=%s command=%s external=%s status=%d elapsed_time_ms=%d\n", user, command, is_external, m_status, (GetTimeMicros() - m_startTime) / 1000);
      94     1000194 :     }
      95             : 
      96      500097 :     bool send_reply(int status, const std::string& response = "")
      97             :     {
      98      500097 :         m_status = status;
      99      500097 :         m_req->WriteReply(status, response);
     100      500097 :         return m_status == HTTP_OK;
     101             :     }
     102             : };
     103             : 
     104          36 : static bool whitelisted(JSONRPCRequest jreq)
     105             : {
     106          36 :     if (g_rpc_whitelist[jreq.authUser].count(jreq.strMethod)) return true;
     107             : 
     108             :     // check for composite command after
     109          24 :     if (!jreq.params.isArray() || jreq.params.empty()) return false;
     110           2 :     if (!jreq.params[0].isStr()) return false;
     111             : 
     112           2 :     return g_rpc_whitelist[jreq.authUser].count(jreq.strMethod + jreq.params[0].get_str());
     113          36 : }
     114             : 
     115        9590 : static bool JSONErrorReply(RpcHttpRequest& rpcRequest, const UniValue& objError, const UniValue& id)
     116             : {
     117             :     // Send error reply from json-rpc error object
     118        9590 :     int nStatus = HTTP_INTERNAL_SERVER_ERROR;
     119        9590 :     int code = objError.find_value("code").getInt<int>();
     120             : 
     121        9590 :     if (code == RPC_INVALID_REQUEST)
     122           8 :         nStatus = HTTP_BAD_REQUEST;
     123        9582 :     else if (code == RPC_METHOD_NOT_FOUND)
     124           6 :         nStatus = HTTP_NOT_FOUND;
     125             : 
     126        9590 :     std::string strReply = JSONRPCReply(NullUniValue, objError, id);
     127             : 
     128        9590 :     rpcRequest.m_req->WriteHeader("Content-Type", "application/json");
     129        9590 :     return rpcRequest.send_reply(nStatus, strReply);
     130        9590 : }
     131             : 
     132             : //This function checks username and password against -rpcauth
     133             : //entries from config file.
     134          94 : static bool multiUserAuthorized(std::string strUserPass)
     135             : {
     136          94 :     if (strUserPass.find(':') == std::string::npos) {
     137           0 :         return false;
     138             :     }
     139          94 :     std::string strUser = strUserPass.substr(0, strUserPass.find(':'));
     140          94 :     std::string strPass = strUserPass.substr(strUserPass.find(':') + 1);
     141             : 
     142         266 :     for (const auto& vFields : g_rpcauth) {
     143         226 :         std::string strName = vFields[0];
     144         226 :         if (!TimingResistantEqual(strName, strUser)) {
     145         164 :             continue;
     146             :         }
     147             : 
     148          62 :         std::string strSalt = vFields[1];
     149          62 :         std::string strHash = vFields[2];
     150             : 
     151             :         static const unsigned int KEY_SIZE = 32;
     152             :         unsigned char out[KEY_SIZE];
     153             : 
     154          62 :         CHMAC_SHA256(reinterpret_cast<const unsigned char*>(strSalt.data()), strSalt.size()).Write(reinterpret_cast<const unsigned char*>(strPass.data()), strPass.size()).Finalize(out);
     155          62 :         std::vector<unsigned char> hexvec(out, out+KEY_SIZE);
     156          62 :         std::string strHashFromPass = HexStr(hexvec);
     157             : 
     158          62 :         if (TimingResistantEqual(strHashFromPass, strHash)) {
     159          54 :             return true;
     160             :         }
     161         226 :     }
     162          40 :     return false;
     163          94 : }
     164             : 
     165      500097 : static bool RPCAuthorized(const std::string& strAuth, std::string& strAuthUsernameOut)
     166             : {
     167      500097 :     if (strRPCUserColonPass.empty()) // Belt-and-suspenders measure if InitRPCAuthentication was not called
     168           0 :         return false;
     169      500097 :     if (strAuth.substr(0, 6) != "Basic ")
     170           4 :         return false;
     171      500093 :     std::string_view strUserPass64 = TrimStringView(std::string_view{strAuth}.substr(6));
     172      500093 :     auto userpass_data = DecodeBase64(strUserPass64);
     173      500093 :     std::string strUserPass;
     174      500093 :     if (!userpass_data) return false;
     175      500093 :     strUserPass.assign(userpass_data->begin(), userpass_data->end());
     176             : 
     177      500093 :     if (strUserPass.find(':') != std::string::npos)
     178      500093 :         strAuthUsernameOut = strUserPass.substr(0, strUserPass.find(':'));
     179             : 
     180             :     //Check if authorized under single-user field
     181      500093 :     if (TimingResistantEqual(strUserPass, strRPCUserColonPass)) {
     182      499999 :         return true;
     183             :     }
     184          94 :     return multiUserAuthorized(strUserPass);
     185      500097 : }
     186             : 
     187      500097 : static bool HTTPReq_JSONRPC(const CoreContext& context, HTTPRequest* req)
     188             : {
     189      500097 :     RpcHttpRequest rpcRequest(req);
     190             : 
     191             :     // JSONRPC handles only POST
     192      500097 :     if (req->GetRequestMethod() != HTTPRequest::POST) {
     193           0 :         return rpcRequest.send_reply(HTTP_BAD_METHOD, "JSONRPC server handles only POST requests");
     194             :     }
     195             :     // Check authorization
     196      500097 :     std::pair<bool, std::string> authHeader = req->GetHeader("authorization");
     197      500097 :     if (!authHeader.first) {
     198           0 :         req->WriteHeader("WWW-Authenticate", WWW_AUTH_HEADER_DATA);
     199           0 :         return rpcRequest.send_reply(HTTP_UNAUTHORIZED);
     200             :     }
     201             : 
     202      500097 :     JSONRPCRequest jreq;
     203      500097 :     jreq.context = context;
     204      500097 :     jreq.peerAddr = req->GetPeer().ToStringAddrPort();
     205      500097 :     if (!RPCAuthorized(authHeader.second, rpcRequest.user)) {
     206          44 :         LogPrintf("ThreadRPCServer incorrect password attempt from %s\n", jreq.peerAddr);
     207             : 
     208             :         /* Deter brute-forcing
     209             :            If this results in a DoS the user really
     210             :            shouldn't have their RPC port exposed. */
     211          44 :         UninterruptibleSleep(std::chrono::milliseconds{250});
     212             : 
     213          44 :         req->WriteHeader("WWW-Authenticate", WWW_AUTH_HEADER_DATA);
     214          44 :         return rpcRequest.send_reply(HTTP_UNAUTHORIZED);
     215             :     }
     216      500053 :     jreq.authUser = rpcRequest.user;
     217             : 
     218             :     try {
     219             :         // Parse request
     220      500053 :         UniValue valRequest;
     221      500053 :         if (!valRequest.read(req->ReadBody()))
     222           0 :             throw JSONRPCError(RPC_PARSE_ERROR, "Parse error");
     223             : 
     224             :         // Set the URI
     225      500053 :         jreq.URI = req->GetURI();
     226             : 
     227      500053 :         std::string strReply;
     228      500053 :         bool user_has_whitelist = g_rpc_whitelist.count(jreq.authUser);
     229      500053 :         if (!user_has_whitelist && g_rpc_whitelist_default) {
     230           0 :             LogPrintf("RPC User %s not allowed to call any methods\n", jreq.authUser);
     231           0 :             return rpcRequest.send_reply(HTTP_FORBIDDEN);
     232             : 
     233             :         // singleton request
     234      500053 :         } else if (valRequest.isObject()) {
     235      499989 :             jreq.parse(valRequest);
     236      499989 :             rpcRequest.command = jreq.strMethod;
     237             : 
     238      499989 :             if (user_has_whitelist && !whitelisted(jreq)) {
     239          22 :                 LogPrintf("RPC User %s not allowed to call method %s\n", jreq.authUser, jreq.strMethod);
     240          22 :                 return rpcRequest.send_reply(HTTP_FORBIDDEN);
     241             :             }
     242      499967 :             UniValue result = tableRPC.execute(jreq);
     243             : 
     244             :             // Send reply
     245      490377 :             strReply = JSONRPCReply(result, NullUniValue, jreq.id);
     246             : 
     247             :         // array of requests
     248      490441 :         } else if (valRequest.isArray()) {
     249          64 :             if (user_has_whitelist) {
     250           0 :                 for (unsigned int reqIdx = 0; reqIdx < valRequest.size(); reqIdx++) {
     251           0 :                     if (!valRequest[reqIdx].isObject()) {
     252           0 :                         throw JSONRPCError(RPC_INVALID_REQUEST, "Invalid Request object");
     253             :                     } else {
     254           0 :                         const UniValue& request = valRequest[reqIdx].get_obj();
     255             :                         // Parse method
     256           0 :                         std::string strMethod = request.find_value("method").get_str();
     257           0 :                         if (!whitelisted(jreq)) {
     258           0 :                             LogPrintf("RPC User %s not allowed to call method %s\n", jreq.authUser, strMethod);
     259           0 :                             return rpcRequest.send_reply(HTTP_FORBIDDEN);
     260             :                         }
     261           0 :                     }
     262           0 :                 }
     263           0 :             }
     264          64 :             strReply = JSONRPCExecBatch(jreq, valRequest.get_array());
     265          64 :         }
     266             :         else
     267           0 :             throw JSONRPCError(RPC_PARSE_ERROR, "Top-level object parse error");
     268             : 
     269      490441 :         req->WriteHeader("Content-Type", "application/json");
     270      490441 :         return rpcRequest.send_reply(HTTP_OK, strReply);
     271      500053 :     } catch (const UniValue& objError) {
     272        9590 :         return JSONErrorReply(rpcRequest, objError, jreq.id);
     273        9590 :     } catch (const std::exception& e) {
     274           0 :         return JSONErrorReply(rpcRequest, JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
     275        9590 :     }
     276           0 :     assert(false);
     277      509687 : }
     278             : 
     279        3019 : static bool InitRPCAuthentication()
     280             : {
     281        3019 :     if (gArgs.GetArg("-rpcpassword", "") == "")
     282             :     {
     283        3017 :         LogPrintf("Using random cookie authentication.\n");
     284        3017 :         if (!GenerateAuthCookie(&strRPCUserColonPass)) {
     285           2 :             return false;
     286             :         }
     287        3015 :     } else {
     288           2 :         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");
     289           2 :         strRPCUserColonPass = gArgs.GetArg("-rpcuser", "") + ":" + gArgs.GetArg("-rpcpassword", "");
     290             :     }
     291        3017 :     if (gArgs.GetArg("-rpcauth", "") != "") {
     292          22 :         LogPrintf("Using rpcauth authentication.\n");
     293          70 :         for (const std::string& rpcauth : gArgs.GetArgs("-rpcauth")) {
     294          48 :             std::vector<std::string> fields{SplitString(rpcauth, ':')};
     295          48 :             const std::vector<std::string> salt_hmac{SplitString(fields.back(), '$')};
     296          48 :             if (fields.size() == 2 && salt_hmac.size() == 2) {
     297          38 :                 fields.pop_back();
     298          38 :                 fields.insert(fields.end(), salt_hmac.begin(), salt_hmac.end());
     299          38 :                 g_rpcauth.push_back(fields);
     300          38 :             } else {
     301          10 :                 LogPrintf("Invalid -rpcauth argument.\n");
     302          10 :                 return false;
     303             :             }
     304          48 :         }
     305          12 :     }
     306             : 
     307        3007 :     g_rpc_whitelist_default = gArgs.GetBoolArg("-rpcwhitelistdefault", gArgs.IsArgSet("-rpcwhitelist"));
     308        3025 :     for (const std::string& strRPCWhitelist : gArgs.GetArgs("-rpcwhitelist")) {
     309          18 :         auto pos = strRPCWhitelist.find(':');
     310          18 :         std::string strUser = strRPCWhitelist.substr(0, pos);
     311          18 :         bool intersect = g_rpc_whitelist.count(strUser);
     312          18 :         std::set<std::string>& whitelist = g_rpc_whitelist[strUser];
     313          18 :         if (pos != std::string::npos) {
     314          16 :             std::string strWhitelist = strRPCWhitelist.substr(pos + 1);
     315          16 :             std::vector<std::string> whitelist_split = SplitString(strWhitelist, ", ");
     316          16 :             std::set<std::string> new_whitelist{
     317          16 :                 std::make_move_iterator(whitelist_split.begin()),
     318          16 :                 std::make_move_iterator(whitelist_split.end())};
     319          16 :             if (intersect) {
     320           2 :                 std::set<std::string> tmp_whitelist;
     321           2 :                 std::set_intersection(new_whitelist.begin(), new_whitelist.end(),
     322           2 :                        whitelist.begin(), whitelist.end(), std::inserter(tmp_whitelist, tmp_whitelist.end()));
     323           2 :                 new_whitelist = std::move(tmp_whitelist);
     324           2 :             }
     325          16 :             whitelist = std::move(new_whitelist);
     326          16 :         }
     327          18 :     }
     328             : 
     329        3007 :     return true;
     330        3019 : }
     331             : 
     332        3019 : bool StartHTTPRPC(const CoreContext& context)
     333             : {
     334        3019 :     LogPrint(BCLog::RPC, "Starting HTTP RPC server\n");
     335        3019 :     if (!InitRPCAuthentication())
     336          12 :         return false;
     337             : 
     338      503104 :     auto handle_rpc = [context](HTTPRequest* req, const std::string&) { return HTTPReq_JSONRPC(context, req); };
     339        3007 :     RegisterHTTPHandler("/", true, handle_rpc);
     340        3007 :     if (g_wallet_init_interface.HasWalletSupport()) {
     341        3007 :         RegisterHTTPHandler("/wallet/", false, handle_rpc);
     342        3007 :     }
     343        3007 :     struct event_base* eventBase = EventBase();
     344        3007 :     assert(eventBase);
     345        3007 :     httpRPCTimerInterface = std::make_unique<HTTPRPCTimerInterface>(eventBase);
     346        3007 :     RPCSetTimerInterface(httpRPCTimerInterface.get());
     347        3007 :     return true;
     348        3019 : }
     349             : 
     350        3030 : void InterruptHTTPRPC()
     351             : {
     352        3030 :     LogPrint(BCLog::RPC, "Interrupting HTTP RPC server\n");
     353        3030 : }
     354             : 
     355        3030 : void StopHTTPRPC()
     356             : {
     357        3030 :     LogPrint(BCLog::RPC, "Stopping HTTP RPC server\n");
     358        3030 :     UnregisterHTTPHandler("/", true);
     359        3030 :     if (g_wallet_init_interface.HasWalletSupport()) {
     360        3030 :         UnregisterHTTPHandler("/wallet/", false);
     361        3030 :     }
     362        3030 :     if (httpRPCTimerInterface) {
     363        3007 :         RPCUnsetTimerInterface(httpRPCTimerInterface.get());
     364        3007 :         httpRPCTimerInterface.reset();
     365        3007 :     }
     366        3030 : }

Generated by: LCOV version 1.16