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