LCOV - code coverage report
Current view: top level - src - httprpc.cpp (source / functions) Hit Total Coverage
Test: fuzz_coverage.info Lines: 2 204 1.0 %
Date: 2024-01-03 14:57:27 Functions: 0 21 0.0 %
Branches: 0 462 0.0 %

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

Generated by: LCOV version 1.14