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