LCOV - code coverage report
Current view: top level - src - httprpc.cpp (source / functions) Coverage Total Hit
Test: total_coverage.info Lines: 90.3 % 196 177
Test Date: 2025-07-10 05:20:26 Functions: 100.0 % 8 8
Branches: 51.3 % 394 202

             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/fs.h>
      15                 :             : #include <util/fs_helpers.h>
      16                 :             : #include <util/strencodings.h>
      17                 :             : #include <util/string.h>
      18                 :             : #include <walletinitinterface.h>
      19                 :             : 
      20                 :             : #include <algorithm>
      21                 :             : #include <iterator>
      22                 :             : #include <map>
      23                 :             : #include <memory>
      24                 :             : #include <optional>
      25                 :             : #include <set>
      26                 :             : #include <string>
      27                 :             : #include <vector>
      28                 :             : 
      29                 :             : using util::SplitString;
      30                 :             : using util::TrimStringView;
      31                 :             : 
      32                 :             : /** WWW-Authenticate to present with 401 Unauthorized response */
      33                 :             : static const char* WWW_AUTH_HEADER_DATA = "Basic realm=\"jsonrpc\"";
      34                 :             : 
      35                 :             : /* List of -rpcauth values */
      36                 :             : static std::vector<std::vector<std::string>> g_rpcauth;
      37                 :             : /* RPC Auth Whitelist */
      38                 :             : static std::map<std::string, std::set<std::string>> g_rpc_whitelist;
      39                 :             : static bool g_rpc_whitelist_default = false;
      40                 :             : 
      41                 :           6 : static void JSONErrorReply(HTTPRequest* req, UniValue objError, const JSONRPCRequest& jreq)
      42                 :             : {
      43                 :             :     // Sending HTTP errors is a legacy JSON-RPC behavior.
      44                 :           6 :     Assume(jreq.m_json_version != JSONRPCVersion::V2);
      45                 :             : 
      46                 :             :     // Send error reply from json-rpc error object
      47                 :           6 :     int nStatus = HTTP_INTERNAL_SERVER_ERROR;
      48                 :           6 :     int code = objError.find_value("code").getInt<int>();
      49                 :             : 
      50         [ +  + ]:           6 :     if (code == RPC_INVALID_REQUEST)
      51                 :             :         nStatus = HTTP_BAD_REQUEST;
      52         [ +  + ]:           4 :     else if (code == RPC_METHOD_NOT_FOUND)
      53                 :           1 :         nStatus = HTTP_NOT_FOUND;
      54                 :             : 
      55   [ +  -  +  -  :          12 :     std::string strReply = JSONRPCReplyObj(NullUniValue, std::move(objError), jreq.id, jreq.m_json_version).write() + "\n";
                   +  - ]
      56                 :             : 
      57   [ +  -  +  -  :          12 :     req->WriteHeader("Content-Type", "application/json");
                   +  - ]
      58         [ +  - ]:           6 :     req->WriteReply(nStatus, strReply);
      59                 :           6 : }
      60                 :             : 
      61                 :             : //This function checks username and password against -rpcauth
      62                 :             : //entries from config file.
      63                 :      187405 : static bool CheckUserAuthorized(std::string_view user, std::string_view pass)
      64                 :             : {
      65         [ +  + ]:      187568 :     for (const auto& fields : g_rpcauth) {
      66         [ +  + ]:      187549 :         if (!TimingResistantEqual(std::string_view(fields[0]), user)) {
      67                 :         156 :             continue;
      68                 :             :         }
      69                 :             : 
      70                 :      187393 :         const std::string& salt = fields[1];
      71                 :      187393 :         const std::string& hash = fields[2];
      72                 :             : 
      73                 :      187393 :         std::array<unsigned char, CHMAC_SHA256::OUTPUT_SIZE> out;
      74                 :      187393 :         CHMAC_SHA256(UCharCast(salt.data()), salt.size()).Write(UCharCast(pass.data()), pass.size()).Finalize(out.data());
      75                 :      187393 :         std::string hash_from_pass = HexStr(out);
      76                 :             : 
      77         [ +  + ]:      187393 :         if (TimingResistantEqual(hash_from_pass, hash)) {
      78                 :      187386 :             return true;
      79                 :             :         }
      80                 :      187393 :     }
      81                 :             :     return false;
      82                 :             : }
      83                 :             : 
      84                 :      187406 : static bool RPCAuthorized(const std::string& strAuth, std::string& strAuthUsernameOut)
      85                 :             : {
      86         [ +  + ]:      187406 :     if (!strAuth.starts_with("Basic "))
      87                 :             :         return false;
      88                 :      187405 :     std::string_view strUserPass64 = TrimStringView(std::string_view{strAuth}.substr(6));
      89                 :      187405 :     auto userpass_data = DecodeBase64(strUserPass64);
      90         [ +  - ]:      187405 :     std::string strUserPass;
      91         [ +  - ]:      187405 :     if (!userpass_data) return false;
      92         [ +  - ]:      187405 :     strUserPass.assign(userpass_data->begin(), userpass_data->end());
      93                 :             : 
      94                 :      187405 :     size_t colon_pos = strUserPass.find(':');
      95         [ +  - ]:      187405 :     if (colon_pos == std::string::npos) {
      96                 :             :         return false; // Invalid basic auth.
      97                 :             :     }
      98         [ +  - ]:      187405 :     std::string user = strUserPass.substr(0, colon_pos);
      99         [ +  - ]:      187405 :     std::string pass = strUserPass.substr(colon_pos + 1);
     100         [ +  - ]:      187405 :     strAuthUsernameOut = user;
     101         [ +  - ]:      187405 :     return CheckUserAuthorized(user, pass);
     102                 :      374810 : }
     103                 :             : 
     104                 :      187407 : static bool HTTPReq_JSONRPC(const std::any& context, HTTPRequest* req)
     105                 :             : {
     106                 :             :     // JSONRPC handles only POST
     107         [ +  + ]:      187407 :     if (req->GetRequestMethod() != HTTPRequest::POST) {
     108                 :           1 :         req->WriteReply(HTTP_BAD_METHOD, "JSONRPC server handles only POST requests");
     109                 :           1 :         return false;
     110                 :             :     }
     111                 :             :     // Check authorization
     112         [ +  - ]:      187406 :     std::pair<bool, std::string> authHeader = req->GetHeader("authorization");
     113         [ -  + ]:      187406 :     if (!authHeader.first) {
     114   [ #  #  #  #  :           0 :         req->WriteHeader("WWW-Authenticate", WWW_AUTH_HEADER_DATA);
                   #  # ]
     115         [ #  # ]:           0 :         req->WriteReply(HTTP_UNAUTHORIZED);
     116                 :             :         return false;
     117                 :             :     }
     118                 :             : 
     119                 :      187406 :     JSONRPCRequest jreq;
     120         [ +  - ]:      187406 :     jreq.context = context;
     121   [ +  -  +  - ]:      187406 :     jreq.peerAddr = req->GetPeer().ToStringAddrPort();
     122   [ +  -  +  + ]:      187406 :     if (!RPCAuthorized(authHeader.second, jreq.authUser)) {
     123         [ +  - ]:          20 :         LogPrintf("ThreadRPCServer incorrect password attempt from %s\n", jreq.peerAddr);
     124                 :             : 
     125                 :             :         /* Deter brute-forcing
     126                 :             :            If this results in a DoS the user really
     127                 :             :            shouldn't have their RPC port exposed. */
     128         [ +  - ]:          20 :         UninterruptibleSleep(std::chrono::milliseconds{250});
     129                 :             : 
     130   [ +  -  +  -  :          40 :         req->WriteHeader("WWW-Authenticate", WWW_AUTH_HEADER_DATA);
                   +  - ]
     131         [ +  - ]:          20 :         req->WriteReply(HTTP_UNAUTHORIZED);
     132                 :             :         return false;
     133                 :             :     }
     134                 :             : 
     135                 :      187386 :     try {
     136                 :             :         // Parse request
     137         [ +  - ]:      187386 :         UniValue valRequest;
     138   [ +  -  +  -  :      187386 :         if (!valRequest.read(req->ReadBody()))
                   +  + ]
     139   [ +  -  +  - ]:           4 :             throw JSONRPCError(RPC_PARSE_ERROR, "Parse error");
     140                 :             : 
     141                 :             :         // Set the URI
     142         [ +  - ]:      187384 :         jreq.URI = req->GetURI();
     143                 :             : 
     144                 :      187384 :         UniValue reply;
     145                 :      187384 :         bool user_has_whitelist = g_rpc_whitelist.count(jreq.authUser);
     146   [ +  +  +  + ]:      187384 :         if (!user_has_whitelist && g_rpc_whitelist_default) {
     147         [ +  - ]:           4 :             LogPrintf("RPC User %s not allowed to call any methods\n", jreq.authUser);
     148         [ +  - ]:           4 :             req->WriteReply(HTTP_FORBIDDEN);
     149                 :             :             return false;
     150                 :             : 
     151                 :             :         // singleton request
     152         [ +  + ]:      187380 :         } else if (valRequest.isObject()) {
     153         [ +  + ]:      187213 :             jreq.parse(valRequest);
     154   [ +  +  +  -  :      187211 :             if (user_has_whitelist && !g_rpc_whitelist[jreq.authUser].count(jreq.strMethod)) {
                   +  + ]
     155         [ +  - ]:          11 :                 LogPrintf("RPC User %s not allowed to call method %s\n", jreq.authUser, jreq.strMethod);
     156         [ +  - ]:          11 :                 req->WriteReply(HTTP_FORBIDDEN);
     157                 :             :                 return false;
     158                 :             :             }
     159                 :             : 
     160                 :             :             // Legacy 1.0/1.1 behavior is for failed requests to throw
     161                 :             :             // exceptions which return HTTP errors and RPC errors to the client.
     162                 :             :             // 2.0 behavior is to catch exceptions and return HTTP success with
     163                 :             :             // RPC errors, as long as there is not an actual HTTP server error.
     164                 :      187200 :             const bool catch_errors{jreq.m_json_version == JSONRPCVersion::V2};
     165         [ +  + ]:      187200 :             reply = JSONRPCExec(jreq, catch_errors);
     166                 :             : 
     167         [ +  + ]:      187198 :             if (jreq.IsNotification()) {
     168                 :             :                 // Even though we do execute notifications, we do not respond to them
     169         [ +  - ]:           2 :                 req->WriteReply(HTTP_NO_CONTENT);
     170                 :             :                 return true;
     171                 :             :             }
     172                 :             : 
     173                 :             :         // array of requests
     174         [ +  - ]:         167 :         } else if (valRequest.isArray()) {
     175                 :             :             // Check authorization for each request's method
     176         [ -  + ]:         167 :             if (user_has_whitelist) {
     177         [ #  # ]:           0 :                 for (unsigned int reqIdx = 0; reqIdx < valRequest.size(); reqIdx++) {
     178   [ #  #  #  # ]:           0 :                     if (!valRequest[reqIdx].isObject()) {
     179   [ #  #  #  # ]:           0 :                         throw JSONRPCError(RPC_INVALID_REQUEST, "Invalid Request object");
     180                 :             :                     } else {
     181   [ #  #  #  # ]:           0 :                         const UniValue& request = valRequest[reqIdx].get_obj();
     182                 :             :                         // Parse method
     183   [ #  #  #  #  :           0 :                         std::string strMethod = request.find_value("method").get_str();
                   #  # ]
     184   [ #  #  #  # ]:           0 :                         if (!g_rpc_whitelist[jreq.authUser].count(strMethod)) {
     185         [ #  # ]:           0 :                             LogPrintf("RPC User %s not allowed to call method %s\n", jreq.authUser, strMethod);
     186         [ #  # ]:           0 :                             req->WriteReply(HTTP_FORBIDDEN);
     187                 :           0 :                             return false;
     188                 :             :                         }
     189                 :           0 :                     }
     190                 :             :                 }
     191                 :             :             }
     192                 :             : 
     193                 :             :             // Execute each request
     194                 :         167 :             reply = UniValue::VARR;
     195         [ +  + ]:       13621 :             for (size_t i{0}; i < valRequest.size(); ++i) {
     196                 :             :                 // Batches never throw HTTP errors, they are always just included
     197                 :             :                 // in "HTTP OK" responses. Notifications never get any response.
     198         [ +  - ]:       13454 :                 UniValue response;
     199                 :       13454 :                 try {
     200   [ +  -  +  + ]:       13454 :                     jreq.parse(valRequest[i]);
     201         [ +  - ]:       13442 :                     response = JSONRPCExec(jreq, /*catch_errors=*/true);
     202      [ -  +  - ]:          12 :                 } catch (UniValue& e) {
     203   [ +  -  +  -  :          12 :                     response = JSONRPCReplyObj(NullUniValue, std::move(e), jreq.id, jreq.m_json_version);
                   +  - ]
     204                 :          12 :                 } catch (const std::exception& e) {
     205   [ -  -  -  -  :           0 :                     response = JSONRPCReplyObj(NullUniValue, JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id, jreq.m_json_version);
          -  -  -  -  -  
                      - ]
     206                 :           0 :                 }
     207         [ +  + ]:       13454 :                 if (!jreq.IsNotification()) {
     208         [ +  - ]:       13449 :                     reply.push_back(std::move(response));
     209                 :             :                 }
     210                 :       13454 :             }
     211                 :             :             // Return no response for an all-notification batch, but only if the
     212                 :             :             // batch request is non-empty. Technically according to the JSON-RPC
     213                 :             :             // 2.0 spec, an empty batch request should also return no response,
     214                 :             :             // However, if the batch request is empty, it means the request did
     215                 :             :             // not contain any JSON-RPC version numbers, so returning an empty
     216                 :             :             // response could break backwards compatibility with old RPC clients
     217                 :             :             // relying on previous behavior. Return an empty array instead of an
     218                 :             :             // empty response in this case to favor being backwards compatible
     219                 :             :             // over complying with the JSON-RPC 2.0 spec in this case.
     220   [ +  +  +  + ]:         167 :             if (reply.size() == 0 && valRequest.size() > 0) {
     221         [ +  - ]:           1 :                 req->WriteReply(HTTP_NO_CONTENT);
     222                 :             :                 return true;
     223                 :             :             }
     224                 :             :         }
     225                 :             :         else
     226   [ #  #  #  # ]:           0 :             throw JSONRPCError(RPC_PARSE_ERROR, "Top-level object parse error");
     227                 :             : 
     228   [ +  -  +  -  :      374724 :         req->WriteHeader("Content-Type", "application/json");
                   +  - ]
     229   [ +  -  +  - ]:      562086 :         req->WriteReply(HTTP_OK, reply.write() + "\n");
     230      [ -  +  - ]:      187396 :     } catch (UniValue& e) {
     231         [ +  - ]:           6 :         JSONErrorReply(req, std::move(e), jreq);
     232                 :           6 :         return false;
     233                 :           6 :     } catch (const std::exception& e) {
     234   [ -  -  -  -  :           0 :         JSONErrorReply(req, JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq);
                   -  - ]
     235                 :           0 :         return false;
     236                 :           0 :     }
     237                 :      187362 :     return true;
     238                 :      374812 : }
     239                 :             : 
     240                 :        1034 : static bool InitRPCAuthentication()
     241                 :             : {
     242         [ +  - ]:        1034 :     std::string user;
     243                 :        1034 :     std::string pass;
     244                 :             : 
     245   [ +  -  +  -  :        1034 :     if (gArgs.GetArg("-rpcpassword", "") == "")
             +  -  +  + ]
     246                 :             :     {
     247                 :        1033 :         std::optional<fs::perms> cookie_perms{std::nullopt};
     248   [ +  -  +  - ]:        1033 :         auto cookie_perms_arg{gArgs.GetArg("-rpccookieperms")};
     249         [ +  + ]:        1033 :         if (cookie_perms_arg) {
     250         [ +  - ]:           3 :             auto perm_opt = InterpretPermString(*cookie_perms_arg);
     251         [ -  + ]:           3 :             if (!perm_opt) {
     252         [ #  # ]:           0 :                 LogError("Invalid -rpccookieperms=%s; must be one of 'owner', 'group', or 'all'.", *cookie_perms_arg);
     253                 :             :                 return false;
     254                 :             :             }
     255                 :           3 :             cookie_perms = *perm_opt;
     256                 :             :         }
     257                 :             : 
     258   [ +  -  +  +  :        1033 :         switch (GenerateAuthCookie(cookie_perms, user, pass)) {
                   -  + ]
     259                 :             :         case GenerateAuthCookieResult::ERR:
     260                 :             :             return false;
     261                 :           1 :         case GenerateAuthCookieResult::DISABLED:
     262         [ +  - ]:           1 :             LogInfo("RPC authentication cookie file generation is disabled.");
     263                 :             :             break;
     264                 :        1031 :         case GenerateAuthCookieResult::OK:
     265         [ +  - ]:        1031 :             LogInfo("Using random cookie authentication.");
     266                 :             :             break;
     267                 :             :         }
     268                 :        1033 :     } else {
     269         [ +  - ]:           1 :         LogInfo("Using rpcuser/rpcpassword authentication.");
     270         [ +  - ]:           1 :         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.");
     271   [ +  -  +  -  :           1 :         user = gArgs.GetArg("-rpcuser", "");
                   +  - ]
     272   [ +  -  +  -  :           1 :         pass = gArgs.GetArg("-rpcpassword", "");
                   +  - ]
     273                 :             :     }
     274                 :             : 
     275                 :             :     // If there is a plaintext credential, hash it with a random salt before storage.
     276   [ +  +  -  + ]:        1033 :     if (!user.empty() || !pass.empty()) {
     277                 :             :         // Generate a random 16 byte hex salt.
     278                 :        1032 :         std::array<unsigned char, 16> raw_salt;
     279                 :        1032 :         GetStrongRandBytes(raw_salt);
     280         [ +  - ]:        1032 :         std::string salt = HexStr(raw_salt);
     281                 :             : 
     282                 :             :         // Compute HMAC.
     283                 :        1032 :         std::array<unsigned char, CHMAC_SHA256::OUTPUT_SIZE> out;
     284   [ +  -  +  -  :        1032 :         CHMAC_SHA256(UCharCast(salt.data()), salt.size()).Write(UCharCast(pass.data()), pass.size()).Finalize(out.data());
                   +  - ]
     285         [ +  - ]:        1032 :         std::string hash = HexStr(out);
     286                 :             : 
     287   [ +  -  +  +  :        5160 :         g_rpcauth.push_back({user, salt, hash});
                   -  - ]
     288                 :        1032 :     }
     289                 :             : 
     290   [ +  -  +  -  :        1033 :     if (!gArgs.GetArgs("-rpcauth").empty()) {
                   +  + ]
     291         [ +  - ]:          18 :         LogInfo("Using rpcauth authentication.\n");
     292   [ +  -  +  -  :          58 :         for (const std::string& rpcauth : gArgs.GetArgs("-rpcauth")) {
                   +  + ]
     293         [ +  - ]:          51 :             std::vector<std::string> fields{SplitString(rpcauth, ':')};
     294         [ +  - ]:          51 :             const std::vector<std::string> salt_hmac{SplitString(fields.back(), '$')};
     295   [ +  +  +  + ]:          51 :             if (fields.size() == 2 && salt_hmac.size() == 2) {
     296                 :          40 :                 fields.pop_back();
     297         [ +  - ]:          40 :                 fields.insert(fields.end(), salt_hmac.begin(), salt_hmac.end());
     298         [ +  - ]:          40 :                 g_rpcauth.push_back(fields);
     299                 :             :             } else {
     300         [ +  - ]:          11 :                 LogPrintf("Invalid -rpcauth argument.\n");
     301                 :          11 :                 return false;
     302                 :             :             }
     303                 :          58 :         }
     304                 :             :     }
     305                 :             : 
     306   [ +  -  +  -  :        1022 :     g_rpc_whitelist_default = gArgs.GetBoolArg("-rpcwhitelistdefault", !gArgs.GetArgs("-rpcwhitelist").empty());
             +  -  +  - ]
     307   [ +  -  +  -  :        1048 :     for (const std::string& strRPCWhitelist : gArgs.GetArgs("-rpcwhitelist")) {
                   +  + ]
     308                 :          26 :         auto pos = strRPCWhitelist.find(':');
     309         [ +  - ]:          26 :         std::string strUser = strRPCWhitelist.substr(0, pos);
     310                 :          26 :         bool intersect = g_rpc_whitelist.count(strUser);
     311         [ +  - ]:          26 :         std::set<std::string>& whitelist = g_rpc_whitelist[strUser];
     312         [ +  + ]:          26 :         if (pos != std::string::npos) {
     313         [ +  - ]:          23 :             std::string strWhitelist = strRPCWhitelist.substr(pos + 1);
     314         [ +  - ]:          23 :             std::vector<std::string> whitelist_split = SplitString(strWhitelist, ", ");
     315         [ +  - ]:          23 :             std::set<std::string> new_whitelist{
     316         [ +  - ]:          23 :                 std::make_move_iterator(whitelist_split.begin()),
     317         [ +  - ]:          23 :                 std::make_move_iterator(whitelist_split.end())};
     318         [ +  + ]:          23 :             if (intersect) {
     319         [ +  - ]:           3 :                 std::set<std::string> tmp_whitelist;
     320         [ +  - ]:           3 :                 std::set_intersection(new_whitelist.begin(), new_whitelist.end(),
     321                 :             :                        whitelist.begin(), whitelist.end(), std::inserter(tmp_whitelist, tmp_whitelist.end()));
     322                 :           3 :                 new_whitelist = std::move(tmp_whitelist);
     323                 :           3 :             }
     324                 :          23 :             whitelist = std::move(new_whitelist);
     325                 :          23 :         }
     326                 :          26 :     }
     327                 :             : 
     328                 :        1022 :     return true;
     329   [ +  -  +  -  :        2066 : }
             +  -  -  - ]
     330                 :             : 
     331                 :        1034 : bool StartHTTPRPC(const std::any& context)
     332                 :             : {
     333         [ +  - ]:        1034 :     LogDebug(BCLog::RPC, "Starting HTTP RPC server\n");
     334         [ +  + ]:        1034 :     if (!InitRPCAuthentication())
     335                 :             :         return false;
     336                 :             : 
     337   [ +  -  +  - ]:      575509 :     auto handle_rpc = [context](HTTPRequest* req, const std::string&) { return HTTPReq_JSONRPC(context, req); };
     338   [ +  -  +  -  :        2044 :     RegisterHTTPHandler("/", true, handle_rpc);
                   +  - ]
     339   [ +  -  +  - ]:        1022 :     if (g_wallet_init_interface.HasWalletSupport()) {
     340   [ +  -  +  -  :        2044 :         RegisterHTTPHandler("/wallet/", false, handle_rpc);
                   +  - ]
     341                 :             :     }
     342         [ +  - ]:        1022 :     struct event_base* eventBase = EventBase();
     343         [ -  + ]:        1022 :     assert(eventBase);
     344                 :        1022 :     return true;
     345                 :        1022 : }
     346                 :             : 
     347                 :        1074 : void InterruptHTTPRPC()
     348                 :             : {
     349         [ +  + ]:        1074 :     LogDebug(BCLog::RPC, "Interrupting HTTP RPC server\n");
     350                 :        1074 : }
     351                 :             : 
     352                 :        1074 : void StopHTTPRPC()
     353                 :             : {
     354         [ +  + ]:        1074 :     LogDebug(BCLog::RPC, "Stopping HTTP RPC server\n");
     355         [ +  - ]:        1074 :     UnregisterHTTPHandler("/", true);
     356         [ +  - ]:        1074 :     if (g_wallet_init_interface.HasWalletSupport()) {
     357         [ +  - ]:        2148 :         UnregisterHTTPHandler("/wallet/", false);
     358                 :             :     }
     359                 :        1074 : }
        

Generated by: LCOV version 2.0-1