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