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