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