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