LCOV - code coverage report
Current view: top level - src - httprpc.cpp (source / functions) Hit Total Coverage
Test: fuzz_coverage.info Lines: 7 206 3.4 %
Date: 2023-10-05 12:38:51 Functions: 7 27 25.9 %
Branches: 2 472 0.4 %

           Branch data     Line data    Source code
       1                 :            : // Copyright (c) 2015-2022 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 <common/args.h>
       8                 :            : #include <crypto/hmac_sha256.h>
       9                 :            : #include <httpserver.h>
      10                 :            : #include <logging.h>
      11                 :            : #include <rpc/protocol.h>
      12                 :            : #include <rpc/server.h>
      13                 :            : #include <util/strencodings.h>
      14                 :            : #include <util/string.h>
      15                 :            : #include <walletinitinterface.h>
      16                 :            : 
      17         [ +  - ]:          2 : #include <algorithm>
      18         [ +  - ]:          2 : #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                 :          2 : 
      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                 :          0 :     HTTPRPCTimer(struct event_base* eventBase, std::function<void()>& func, int64_t millis) :
      35         [ #  # ]:          0 :         ev(eventBase, false, func)
      36                 :          0 :     {
      37                 :            :         struct timeval tv;
      38                 :          0 :         tv.tv_sec = millis/1000;
      39                 :          0 :         tv.tv_usec = (millis%1000)*1000;
      40         [ #  # ]:          0 :         ev.trigger(&tv);
      41                 :          0 :     }
      42                 :            : private:
      43                 :            :     HTTPEvent ev;
      44                 :            : };
      45                 :            : 
      46                 :            : class HTTPRPCTimerInterface : public RPCTimerInterface
      47                 :            : {
      48                 :            : public:
      49                 :          0 :     explicit HTTPRPCTimerInterface(struct event_base* _base) : base(_base)
      50                 :          0 :     {
      51                 :          0 :     }
      52                 :          0 :     const char* Name() override
      53                 :            :     {
      54                 :          0 :         return "HTTP";
      55                 :            :     }
      56                 :          0 :     RPCTimerBase* NewTimer(std::function<void()>& func, int64_t millis) override
      57                 :            :     {
      58         [ #  # ]:          0 :         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                 :          2 : static std::string strRPCUserColonPass;
      67                 :            : /* Stored RPC timer interface (for unregistration) */
      68                 :            : static std::unique_ptr<HTTPRPCTimerInterface> httpRPCTimerInterface;
      69                 :            : /* List of -rpcauth values */
      70                 :          2 : static std::vector<std::vector<std::string>> g_rpcauth;
      71                 :            : /* RPC Auth Whitelist */
      72                 :          2 : static std::map<std::string, std::set<std::string>> g_rpc_whitelist;
      73                 :            : static bool g_rpc_whitelist_default = false;
      74                 :          2 : 
      75                 :          0 : static void JSONErrorReply(HTTPRequest* req, const UniValue& objError, const UniValue& id)
      76                 :            : {
      77                 :            :     // Send error reply from json-rpc error object
      78                 :          0 :     int nStatus = HTTP_INTERNAL_SERVER_ERROR;
      79                 :          0 :     int code = objError.find_value("code").getInt<int>();
      80                 :            : 
      81         [ #  # ]:          0 :     if (code == RPC_INVALID_REQUEST)
      82                 :          0 :         nStatus = HTTP_BAD_REQUEST;
      83         [ #  # ]:          0 :     else if (code == RPC_METHOD_NOT_FOUND)
      84                 :          0 :         nStatus = HTTP_NOT_FOUND;
      85                 :            : 
      86                 :          0 :     std::string strReply = JSONRPCReply(NullUniValue, objError, id);
      87                 :            : 
      88   [ #  #  #  #  :          0 :     req->WriteHeader("Content-Type", "application/json");
                   #  # ]
      89         [ #  # ]:          0 :     req->WriteReply(nStatus, strReply);
      90                 :          0 : }
      91                 :            : 
      92                 :            : //This function checks username and password against -rpcauth
      93                 :            : //entries from config file.
      94                 :          0 : static bool multiUserAuthorized(std::string strUserPass)
      95                 :            : {
      96         [ #  # ]:          0 :     if (strUserPass.find(':') == std::string::npos) {
      97                 :          0 :         return false;
      98                 :            :     }
      99                 :          0 :     std::string strUser = strUserPass.substr(0, strUserPass.find(':'));
     100         [ #  # ]:          0 :     std::string strPass = strUserPass.substr(strUserPass.find(':') + 1);
     101                 :            : 
     102         [ #  # ]:          0 :     for (const auto& vFields : g_rpcauth) {
     103         [ #  # ]:          0 :         std::string strName = vFields[0];
     104         [ #  # ]:          0 :         if (!TimingResistantEqual(strName, strUser)) {
     105                 :          0 :             continue;
     106                 :            :         }
     107                 :            : 
     108         [ #  # ]:          0 :         std::string strSalt = vFields[1];
     109         [ #  # ]:          0 :         std::string strHash = vFields[2];
     110                 :            : 
     111                 :            :         static const unsigned int KEY_SIZE = 32;
     112                 :            :         unsigned char out[KEY_SIZE];
     113                 :            : 
     114   [ #  #  #  #  :          0 :         CHMAC_SHA256(reinterpret_cast<const unsigned char*>(strSalt.data()), strSalt.size()).Write(reinterpret_cast<const unsigned char*>(strPass.data()), strPass.size()).Finalize(out);
                   #  # ]
     115         [ #  # ]:          0 :         std::vector<unsigned char> hexvec(out, out+KEY_SIZE);
     116   [ #  #  #  # ]:          0 :         std::string strHashFromPass = HexStr(hexvec);
     117                 :            : 
     118         [ #  # ]:          0 :         if (TimingResistantEqual(strHashFromPass, strHash)) {
     119                 :          0 :             return true;
     120                 :            :         }
     121      [ #  #  # ]:          0 :     }
     122                 :          0 :     return false;
     123                 :          0 : }
     124                 :            : 
     125                 :          0 : static bool RPCAuthorized(const std::string& strAuth, std::string& strAuthUsernameOut)
     126                 :            : {
     127         [ #  # ]:          0 :     if (strRPCUserColonPass.empty()) // Belt-and-suspenders measure if InitRPCAuthentication was not called
     128                 :          0 :         return false;
     129         [ #  # ]:          0 :     if (strAuth.substr(0, 6) != "Basic ")
     130                 :          0 :         return false;
     131                 :          0 :     std::string_view strUserPass64 = TrimStringView(std::string_view{strAuth}.substr(6));
     132                 :          0 :     auto userpass_data = DecodeBase64(strUserPass64);
     133                 :          0 :     std::string strUserPass;
     134         [ #  # ]:          0 :     if (!userpass_data) return false;
     135   [ #  #  #  #  :          0 :     strUserPass.assign(userpass_data->begin(), userpass_data->end());
                   #  # ]
     136                 :            : 
     137         [ #  # ]:          0 :     if (strUserPass.find(':') != std::string::npos)
     138         [ #  # ]:          0 :         strAuthUsernameOut = strUserPass.substr(0, strUserPass.find(':'));
     139                 :            : 
     140                 :            :     //Check if authorized under single-user field
     141   [ #  #  #  # ]:          0 :     if (TimingResistantEqual(strUserPass, strRPCUserColonPass)) {
     142                 :          0 :         return true;
     143                 :            :     }
     144   [ #  #  #  # ]:          0 :     return multiUserAuthorized(strUserPass);
     145                 :          0 : }
     146                 :            : 
     147                 :          0 : static bool HTTPReq_JSONRPC(const std::any& context, HTTPRequest* req)
     148                 :            : {
     149                 :            :     // JSONRPC handles only POST
     150         [ #  # ]:          0 :     if (req->GetRequestMethod() != HTTPRequest::POST) {
     151   [ #  #  #  # ]:          0 :         req->WriteReply(HTTP_BAD_METHOD, "JSONRPC server handles only POST requests");
     152                 :          0 :         return false;
     153                 :            :     }
     154                 :            :     // Check authorization
     155   [ #  #  #  # ]:          0 :     std::pair<bool, std::string> authHeader = req->GetHeader("authorization");
     156         [ #  # ]:          0 :     if (!authHeader.first) {
     157   [ #  #  #  #  :          0 :         req->WriteHeader("WWW-Authenticate", WWW_AUTH_HEADER_DATA);
                   #  # ]
     158   [ #  #  #  # ]:          0 :         req->WriteReply(HTTP_UNAUTHORIZED);
     159                 :          0 :         return false;
     160                 :            :     }
     161                 :            : 
     162         [ #  # ]:          0 :     JSONRPCRequest jreq;
     163         [ #  # ]:          0 :     jreq.context = context;
     164   [ #  #  #  # ]:          0 :     jreq.peerAddr = req->GetPeer().ToStringAddrPort();
     165   [ #  #  #  # ]:          0 :     if (!RPCAuthorized(authHeader.second, jreq.authUser)) {
     166   [ #  #  #  #  :          0 :         LogPrintf("ThreadRPCServer incorrect password attempt from %s\n", jreq.peerAddr);
                   #  # ]
     167                 :            : 
     168                 :            :         /* Deter brute-forcing
     169                 :            :            If this results in a DoS the user really
     170                 :            :            shouldn't have their RPC port exposed. */
     171   [ #  #  #  #  :          0 :         UninterruptibleSleep(std::chrono::milliseconds{250});
                   #  # ]
     172                 :            : 
     173   [ #  #  #  #  :          0 :         req->WriteHeader("WWW-Authenticate", WWW_AUTH_HEADER_DATA);
                   #  # ]
     174   [ #  #  #  # ]:          0 :         req->WriteReply(HTTP_UNAUTHORIZED);
     175                 :          0 :         return false;
     176                 :            :     }
     177                 :            : 
     178                 :            :     try {
     179                 :            :         // Parse request
     180         [ #  # ]:          0 :         UniValue valRequest;
     181   [ #  #  #  #  :          0 :         if (!valRequest.read(req->ReadBody()))
                   #  # ]
     182   [ #  #  #  #  :          0 :             throw JSONRPCError(RPC_PARSE_ERROR, "Parse error");
                   #  # ]
     183                 :            : 
     184                 :            :         // Set the URI
     185         [ #  # ]:          0 :         jreq.URI = req->GetURI();
     186                 :            : 
     187                 :          0 :         std::string strReply;
     188         [ #  # ]:          0 :         bool user_has_whitelist = g_rpc_whitelist.count(jreq.authUser);
     189   [ #  #  #  # ]:          0 :         if (!user_has_whitelist && g_rpc_whitelist_default) {
     190   [ #  #  #  #  :          0 :             LogPrintf("RPC User %s not allowed to call any methods\n", jreq.authUser);
                   #  # ]
     191   [ #  #  #  # ]:          0 :             req->WriteReply(HTTP_FORBIDDEN);
     192                 :          0 :             return false;
     193                 :            : 
     194                 :            :         // singleton request
     195   [ #  #  #  # ]:          0 :         } else if (valRequest.isObject()) {
     196         [ #  # ]:          0 :             jreq.parse(valRequest);
     197   [ #  #  #  #  :          0 :             if (user_has_whitelist && !g_rpc_whitelist[jreq.authUser].count(jreq.strMethod)) {
             #  #  #  # ]
     198   [ #  #  #  #  :          0 :                 LogPrintf("RPC User %s not allowed to call method %s\n", jreq.authUser, jreq.strMethod);
                   #  # ]
     199   [ #  #  #  # ]:          0 :                 req->WriteReply(HTTP_FORBIDDEN);
     200                 :          0 :                 return false;
     201                 :            :             }
     202         [ #  # ]:          0 :             UniValue result = tableRPC.execute(jreq);
     203                 :            : 
     204                 :            :             // Send reply
     205         [ #  # ]:          0 :             strReply = JSONRPCReply(result, NullUniValue, jreq.id);
     206                 :            : 
     207                 :            :         // array of requests
     208   [ #  #  #  # ]:          0 :         } else if (valRequest.isArray()) {
     209         [ #  # ]:          0 :             if (user_has_whitelist) {
     210   [ #  #  #  # ]:          0 :                 for (unsigned int reqIdx = 0; reqIdx < valRequest.size(); reqIdx++) {
     211   [ #  #  #  #  :          0 :                     if (!valRequest[reqIdx].isObject()) {
                   #  # ]
     212   [ #  #  #  #  :          0 :                         throw JSONRPCError(RPC_INVALID_REQUEST, "Invalid Request object");
                   #  # ]
     213                 :            :                     } else {
     214   [ #  #  #  # ]:          0 :                         const UniValue& request = valRequest[reqIdx].get_obj();
     215                 :            :                         // Parse method
     216   [ #  #  #  #  :          0 :                         std::string strMethod = request.find_value("method").get_str();
                   #  # ]
     217   [ #  #  #  #  :          0 :                         if (!g_rpc_whitelist[jreq.authUser].count(strMethod)) {
                   #  # ]
     218   [ #  #  #  #  :          0 :                             LogPrintf("RPC User %s not allowed to call method %s\n", jreq.authUser, strMethod);
                   #  # ]
     219   [ #  #  #  # ]:          0 :                             req->WriteReply(HTTP_FORBIDDEN);
     220                 :          0 :                             return false;
     221                 :            :                         }
     222         [ #  # ]:          0 :                     }
     223                 :          0 :                 }
     224                 :          0 :             }
     225   [ #  #  #  # ]:          0 :             strReply = JSONRPCExecBatch(jreq, valRequest.get_array());
     226                 :          0 :         }
     227                 :            :         else
     228   [ #  #  #  #  :          0 :             throw JSONRPCError(RPC_PARSE_ERROR, "Top-level object parse error");
                   #  # ]
     229                 :            : 
     230   [ #  #  #  #  :          0 :         req->WriteHeader("Content-Type", "application/json");
                   #  # ]
     231         [ #  # ]:          0 :         req->WriteReply(HTTP_OK, strReply);
     232   [ #  #  #  #  :          0 :     } catch (const UniValue& objError) {
                   #  # ]
     233         [ #  # ]:          0 :         JSONErrorReply(req, objError, jreq.id);
     234                 :          0 :         return false;
     235   [ #  #  #  # ]:          0 :     } catch (const std::exception& e) {
     236   [ #  #  #  #  :          0 :         JSONErrorReply(req, JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
                   #  # ]
     237                 :          0 :         return false;
     238   [ #  #  #  # ]:          0 :     }
     239                 :          0 :     return true;
     240                 :          0 : }
     241                 :            : 
     242                 :          0 : static bool InitRPCAuthentication()
     243                 :            : {
     244   [ #  #  #  #  :          0 :     if (gArgs.GetArg("-rpcpassword", "") == "")
          #  #  #  #  #  
                      # ]
     245                 :            :     {
     246   [ #  #  #  #  :          0 :         LogPrintf("Using random cookie authentication.\n");
                   #  # ]
     247         [ #  # ]:          0 :         if (!GenerateAuthCookie(&strRPCUserColonPass)) {
     248                 :          0 :             return false;
     249                 :            :         }
     250                 :          0 :     } else {
     251   [ #  #  #  #  :          0 :         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");
                   #  # ]
     252   [ #  #  #  #  :          0 :         strRPCUserColonPass = gArgs.GetArg("-rpcuser", "") + ":" + gArgs.GetArg("-rpcpassword", "");
          #  #  #  #  #  
          #  #  #  #  #  
                   #  # ]
     253                 :            :     }
     254   [ #  #  #  #  :          0 :     if (gArgs.GetArg("-rpcauth", "") != "") {
          #  #  #  #  #  
                      # ]
     255   [ #  #  #  #  :          0 :         LogPrintf("Using rpcauth authentication.\n");
                   #  # ]
     256   [ #  #  #  #  :          0 :         for (const std::string& rpcauth : gArgs.GetArgs("-rpcauth")) {
             #  #  #  #  
                      # ]
     257         [ #  # ]:          0 :             std::vector<std::string> fields{SplitString(rpcauth, ':')};
     258         [ #  # ]:          0 :             const std::vector<std::string> salt_hmac{SplitString(fields.back(), '$')};
     259   [ #  #  #  # ]:          0 :             if (fields.size() == 2 && salt_hmac.size() == 2) {
     260                 :          0 :                 fields.pop_back();
     261         [ #  # ]:          0 :                 fields.insert(fields.end(), salt_hmac.begin(), salt_hmac.end());
     262         [ #  # ]:          0 :                 g_rpcauth.push_back(fields);
     263                 :          0 :             } else {
     264   [ #  #  #  #  :          0 :                 LogPrintf("Invalid -rpcauth argument.\n");
                   #  # ]
     265                 :          0 :                 return false;
     266                 :            :             }
     267         [ #  # ]:          0 :         }
     268                 :          0 :     }
     269                 :            : 
     270   [ #  #  #  #  :          0 :     g_rpc_whitelist_default = gArgs.GetBoolArg("-rpcwhitelistdefault", gArgs.IsArgSet("-rpcwhitelist"));
             #  #  #  # ]
     271   [ #  #  #  #  :          0 :     for (const std::string& strRPCWhitelist : gArgs.GetArgs("-rpcwhitelist")) {
                   #  # ]
     272                 :          0 :         auto pos = strRPCWhitelist.find(':');
     273         [ #  # ]:          0 :         std::string strUser = strRPCWhitelist.substr(0, pos);
     274         [ #  # ]:          0 :         bool intersect = g_rpc_whitelist.count(strUser);
     275         [ #  # ]:          0 :         std::set<std::string>& whitelist = g_rpc_whitelist[strUser];
     276         [ #  # ]:          0 :         if (pos != std::string::npos) {
     277         [ #  # ]:          0 :             std::string strWhitelist = strRPCWhitelist.substr(pos + 1);
     278         [ #  # ]:          0 :             std::vector<std::string> whitelist_split = SplitString(strWhitelist, ", ");
     279         [ #  # ]:          0 :             std::set<std::string> new_whitelist{
     280         [ #  # ]:          0 :                 std::make_move_iterator(whitelist_split.begin()),
     281         [ #  # ]:          0 :                 std::make_move_iterator(whitelist_split.end())};
     282         [ #  # ]:          0 :             if (intersect) {
     283                 :          0 :                 std::set<std::string> tmp_whitelist;
     284         [ #  # ]:          0 :                 std::set_intersection(new_whitelist.begin(), new_whitelist.end(),
     285         [ #  # ]:          0 :                        whitelist.begin(), whitelist.end(), std::inserter(tmp_whitelist, tmp_whitelist.end()));
     286                 :          0 :                 new_whitelist = std::move(tmp_whitelist);
     287                 :          0 :             }
     288                 :          0 :             whitelist = std::move(new_whitelist);
     289                 :          0 :         }
     290                 :          0 :     }
     291                 :            : 
     292                 :          0 :     return true;
     293                 :          0 : }
     294                 :            : 
     295                 :          0 : bool StartHTTPRPC(const std::any& context)
     296                 :            : {
     297   [ #  #  #  #  :          0 :     LogPrint(BCLog::RPC, "Starting HTTP RPC server\n");
             #  #  #  # ]
     298         [ #  # ]:          0 :     if (!InitRPCAuthentication())
     299                 :          0 :         return false;
     300                 :            : 
     301                 :          0 :     auto handle_rpc = [context](HTTPRequest* req, const std::string&) { return HTTPReq_JSONRPC(context, req); };
     302   [ #  #  #  #  :          0 :     RegisterHTTPHandler("/", true, handle_rpc);
             #  #  #  # ]
     303   [ #  #  #  # ]:          0 :     if (g_wallet_init_interface.HasWalletSupport()) {
     304   [ #  #  #  #  :          0 :         RegisterHTTPHandler("/wallet/", false, handle_rpc);
             #  #  #  # ]
     305                 :          0 :     }
     306         [ #  # ]:          0 :     struct event_base* eventBase = EventBase();
     307         [ #  # ]:          0 :     assert(eventBase);
     308         [ #  # ]:          0 :     httpRPCTimerInterface = std::make_unique<HTTPRPCTimerInterface>(eventBase);
     309         [ #  # ]:          0 :     RPCSetTimerInterface(httpRPCTimerInterface.get());
     310                 :          0 :     return true;
     311                 :          0 : }
     312                 :            : 
     313                 :          0 : void InterruptHTTPRPC()
     314                 :            : {
     315   [ #  #  #  #  :          0 :     LogPrint(BCLog::RPC, "Interrupting HTTP RPC server\n");
             #  #  #  # ]
     316                 :          0 : }
     317                 :            : 
     318                 :          0 : void StopHTTPRPC()
     319                 :            : {
     320   [ #  #  #  #  :          0 :     LogPrint(BCLog::RPC, "Stopping HTTP RPC server\n");
             #  #  #  # ]
     321   [ #  #  #  # ]:          0 :     UnregisterHTTPHandler("/", true);
     322         [ #  # ]:          0 :     if (g_wallet_init_interface.HasWalletSupport()) {
     323   [ #  #  #  # ]:          0 :         UnregisterHTTPHandler("/wallet/", false);
     324                 :          0 :     }
     325         [ #  # ]:          0 :     if (httpRPCTimerInterface) {
     326                 :          0 :         RPCUnsetTimerInterface(httpRPCTimerInterface.get());
     327                 :          0 :         httpRPCTimerInterface.reset();
     328                 :          0 :     }
     329                 :          0 : }

Generated by: LCOV version 1.14