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