Commit 4272966

Browse files
committed
Merge bitcoin#32423: rpc: Undeprecate rpcuser/rpcpassword, store all credentials hashed in memory
e49a727 rpc: Avoid join-split roundtrip for user:pass for auth credentials (Vasil Dimov) 98ff38a rpc: Perform HTTP user:pass split once in `RPCAuthorized` (laanwj) 879a17b rpc: Store all credentials hashed in memory (laanwj) 4ab9bed rpc: Undeprecate rpcuser/rpcpassword, change message to security warning (laanwj) Pull request description: This PR does two things: ### Undeprecate rpcuser/rpcpassword, change message to security warning Back in 2015, in bitcoin#7044, we added configuration option `rpcauth` for multiple RPC users. At the same time the old settings for single-user configuration `rpcuser` and `rpcpassword` were "soon" to be deprecated. The main reason for this deprecation is that while `rpcpassword` stores the password in plain text, `rpcauth` stores a hash, so it doesn't appear in the configuration in plain text. As the options are still in active use, actually removing them is expected to be a hassle to many, and it's not clear that is worth it. As for the security risk, in many kinds of setups (no wallet, containerized, single-user-single-application, local-only, etc) it is an unlikely point of escalation. In the end, it is good to encourage secure practices, but it is the responsibility of the user. Log a clear warning but remove the deprecation notice (this is also the only place where the options appear as deprecated, they were never marked as such in the -help output). <hr> ### Store all credentials hashed in memory This gets rid of the special-casing of `strRPCUserColonPass` by hashing cookies as well as manually provided `-rpcuser`/`-rpcpassword` with a random salt before storing them. Also take the opportunity to modernize the surrounding code a bit. There should be no end-user visible differences in behavior. <hr> Closesbitcoin#29240. ACKs for top commit: 1440000bytes: utACK bitcoin@e49a727 janb84: reACK bitcoin@e49a727 vasild: ACK e49a727 Tree-SHA512: 7162848ada4545bc07b5843d1ab6fb7e31fb26de8d6385464b7c166491cd122eac2ec5e70887c414fc136600482df8277dc0cc0541d7b7cf62c4f72e25bb6145
2 parents ff1ee10 + e49a727 commit 4272966

3 files changed

Lines changed: 75 additions & 48 deletions

File tree

‎src/httprpc.cpp‎

Lines changed: 44 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -69,8 +69,6 @@ class HTTPRPCTimerInterface : public RPCTimerInterface
6969
};
7070

7171

72-
/* Pre-base64-encoded authentication token */
73-
static std::string strRPCUserColonPass;
7472
/* Stored RPC timer interface (for unregistration) */
7573
static std::unique_ptr<HTTPRPCTimerInterface> httpRPCTimerInterface;
7674
/* List of -rpcauth values */
@@ -101,31 +99,21 @@ static void JSONErrorReply(HTTPRequest* req, UniValue objError, const JSONRPCReq
10199

102100
//This function checks username and password against -rpcauth
103101
//entries from config file.
104-
staticboolmultiUserAuthorized(std::string strUserPass)
102+
staticboolCheckUserAuthorized(std::string_view user, std::string_view pass)
105103
{
106-
if (strUserPass.find(':') == std::string::npos) {
107-
returnfalse;
108-
}
109-
std::string strUser = strUserPass.substr(0, strUserPass.find(':'));
110-
std::string strPass = strUserPass.substr(strUserPass.find(':') + 1);
111-
112-
for (constauto& vFields : g_rpcauth) {
113-
std::string strName = vFields[0];
114-
if (!TimingResistantEqual(strName, strUser)) {
104+
for (constauto& fields : g_rpcauth) {
105+
if (!TimingResistantEqual(std::string_view(fields[0]), user)) {
115106
continue;
116107
}
117108

118-
std::string strSalt = vFields[1];
119-
std::string strHash = vFields[2];
109+
conststd::string& salt = fields[1];
110+
conststd::string& hash = fields[2];
120111

121-
staticconstunsignedintKEY_SIZE = 32;
122-
unsignedchar out[KEY_SIZE];
112+
std::array<unsignedchar, CHMAC_SHA256::OUTPUT_SIZE> out;
113+
CHMAC_SHA256(UCharCast(salt.data()), salt.size()).Write(UCharCast(pass.data()), pass.size()).Finalize(out.data());
114+
std::string hash_from_pass = HexStr(out);
123115

124-
CHMAC_SHA256(reinterpret_cast<constunsignedchar*>(strSalt.data()), strSalt.size()).Write(reinterpret_cast<constunsignedchar*>(strPass.data()), strPass.size()).Finalize(out);
125-
std::vector<unsignedchar> hexvec(out, out+KEY_SIZE);
126-
std::string strHashFromPass = HexStr(hexvec);
127-
128-
if (TimingResistantEqual(strHashFromPass, strHash)) {
116+
if (TimingResistantEqual(hash_from_pass, hash)) {
129117
returntrue;
130118
}
131119
}
@@ -142,15 +130,14 @@ static bool RPCAuthorized(const std::string& strAuth, std::string& strAuthUserna
142130
if (!userpass_data) returnfalse;
143131
strUserPass.assign(userpass_data->begin(), userpass_data->end());
144132

145-
if (strUserPass.find(':') != std::string::npos)
146-
strAuthUsernameOut = strUserPass.substr(0, strUserPass.find(':'));
147-
148-
// Check if authorized under single-user field.
149-
// (strRPCUserColonPass is empty when -norpccookiefile is specified).
150-
if (!strRPCUserColonPass.empty() && TimingResistantEqual(strUserPass, strRPCUserColonPass)) {
151-
returntrue;
133+
size_t colon_pos = strUserPass.find(':');
134+
if (colon_pos == std::string::npos) {
135+
returnfalse; // Invalid basic auth.
152136
}
153-
returnmultiUserAuthorized(strUserPass);
137+
std::string user = strUserPass.substr(0, colon_pos);
138+
std::string pass = strUserPass.substr(colon_pos + 1);
139+
strAuthUsernameOut = user;
140+
returnCheckUserAuthorized(user, pass);
154141
}
155142

156143
staticboolHTTPReq_JSONRPC(const std::any& context, HTTPRequest* req)
@@ -291,6 +278,9 @@ static bool HTTPReq_JSONRPC(const std::any& context, HTTPRequest* req)
291278

292279
staticboolInitRPCAuthentication()
293280
{
281+
std::string user;
282+
std::string pass;
283+
294284
if (gArgs.GetArg("-rpcpassword", "") == "")
295285
{
296286
std::optional<fs::perms> cookie_perms{std::nullopt};
@@ -304,18 +294,36 @@ static bool InitRPCAuthentication()
304294
cookie_perms = *perm_opt;
305295
}
306296

307-
assert(strRPCUserColonPass.empty()); // Only support initializing once
308-
if (!GenerateAuthCookie(&strRPCUserColonPass, cookie_perms)) {
297+
switch (GenerateAuthCookie(cookie_perms, user, pass)) {
298+
case GenerateAuthCookieResult::ERR:
309299
returnfalse;
310-
}
311-
if (strRPCUserColonPass.empty()) {
300+
case GenerateAuthCookieResult::DISABLED:
312301
LogInfo("RPC authentication cookie file generation is disabled.");
313-
} else {
302+
break;
303+
case GenerateAuthCookieResult::OK:
314304
LogInfo("Using random cookie authentication.");
305+
break;
315306
}
316307
} else {
317-
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");
318-
strRPCUserColonPass = gArgs.GetArg("-rpcuser", "") + ":" + gArgs.GetArg("-rpcpassword", "");
308+
LogInfo("Using rpcuser/rpcpassword authentication.");
309+
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+
user = gArgs.GetArg("-rpcuser", "");
311+
pass = gArgs.GetArg("-rpcpassword", "");
312+
}
313+
314+
// If there is a plaintext credential, hash it with a random salt before storage.
315+
if (!user.empty() || !pass.empty()) {
316+
// Generate a random 16 byte hex salt.
317+
std::array<unsignedchar, 16> raw_salt;
318+
GetStrongRandBytes(raw_salt);
319+
std::string salt = HexStr(raw_salt);
320+
321+
// Compute HMAC.
322+
std::array<unsignedchar, CHMAC_SHA256::OUTPUT_SIZE> out;
323+
CHMAC_SHA256(UCharCast(salt.data()), salt.size()).Write(UCharCast(pass.data()), pass.size()).Finalize(out.data());
324+
std::string hash = HexStr(out);
325+
326+
g_rpcauth.push_back({user, salt, hash});
319327
}
320328

321329
if (!gArgs.GetArgs("-rpcauth").empty()) {

‎src/rpc/request.cpp‎

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -97,50 +97,52 @@ static fs::path GetAuthCookieFile(bool temp=false)
9797

9898
staticbool g_generated_cookie = false;
9999

100-
boolGenerateAuthCookie(std::string* cookie_out, std::optional<fs::perms> cookie_perms)
100+
GenerateAuthCookieResult GenerateAuthCookie(const std::optional<fs::perms>& cookie_perms,
101+
std::string& user,
102+
std::string& pass)
101103
{
102104
constsize_tCOOKIE_SIZE = 32;
103105
unsignedchar rand_pwd[COOKIE_SIZE];
104106
GetRandBytes(rand_pwd);
105-
std::string cookie = COOKIEAUTH_USER + ":" + HexStr(rand_pwd);
107+
conststd::string rand_pwd_hex{HexStr(rand_pwd)};
106108

107109
/** the umask determines what permissions are used to create this file -
108110
* these are set to 0077 in common/system.cpp.
109111
*/
110112
std::ofstream file;
111113
fs::path filepath_tmp = GetAuthCookieFile(true);
112114
if (filepath_tmp.empty()) {
113-
returntrue; // -norpccookiefile
115+
returnGenerateAuthCookieResult::DISABLED; // -norpccookiefile
114116
}
115117
file.open(filepath_tmp);
116118
if (!file.is_open()) {
117119
LogWarning("Unable to open cookie authentication file %s for writing", fs::PathToString(filepath_tmp));
118-
returnfalse;
120+
returnGenerateAuthCookieResult::ERR;
119121
}
120-
file << cookie;
122+
file << COOKIEAUTH_USER << ":" << rand_pwd_hex;
121123
file.close();
122124

123125
fs::path filepath = GetAuthCookieFile(false);
124126
if (!RenameOver(filepath_tmp, filepath)) {
125127
LogWarning("Unable to rename cookie authentication file %s to %s", fs::PathToString(filepath_tmp), fs::PathToString(filepath));
126-
returnfalse;
128+
returnGenerateAuthCookieResult::ERR;
127129
}
128130
if (cookie_perms) {
129131
std::error_code code;
130132
fs::permissions(filepath, cookie_perms.value(), fs::perm_options::replace, code);
131133
if (code) {
132134
LogWarning("Unable to set permissions on cookie authentication file %s", fs::PathToString(filepath));
133-
returnfalse;
135+
returnGenerateAuthCookieResult::ERR;
134136
}
135137
}
136138

137139
g_generated_cookie = true;
138140
LogInfo("Generated RPC authentication cookie %s\n", fs::PathToString(filepath));
139141
LogInfo("Permissions used for cookie: %s\n", PermsToSymbolicString(fs::status(filepath).permissions()));
140142

141-
if (cookie_out)
142-
*cookie_out = cookie;
143-
returntrue;
143+
user = COOKIEAUTH_USER;
144+
pass = rand_pwd_hex;
145+
returnGenerateAuthCookieResult::OK;
144146
}
145147

146148
boolGetAuthCookie(std::string *cookie_out)

‎src/rpc/request.h‎

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,25 @@ UniValue JSONRPCRequestObj(const std::string& strMethod, const UniValue& params,
2323
UniValue JSONRPCReplyObj(UniValue result, UniValue error, std::optional<UniValue> id, JSONRPCVersion jsonrpc_version);
2424
UniValue JSONRPCError(int code, const std::string& message);
2525

26-
/** Generate a new RPC authentication cookie and write it to disk */
27-
boolGenerateAuthCookie(std::string* cookie_out, std::optional<fs::perms> cookie_perms=std::nullopt);
26+
enumclassGenerateAuthCookieResult : uint8_t {
27+
DISABLED, // -norpccookiefile
28+
ERR,
29+
OK,
30+
};
31+
32+
/**
33+
* Generate a new RPC authentication cookie and write it to disk
34+
* @param[in] cookie_perms Filesystem permissions to use for the cookie file.
35+
* @param[out] user Generated username, only set if `OK` is returned.
36+
* @param[out] pass Generated password, only set if `OK` is returned.
37+
* @retval GenerateAuthCookieResult::DISABLED Authentication via cookie is disabled.
38+
* @retval GenerateAuthCookieResult::ERROR Error occurred, auth data could not be saved to disk.
39+
* @retval GenerateAuthCookieResult::OK Auth data was generated, saved to disk and in `user` and `pass`.
40+
*/
41+
GenerateAuthCookieResult GenerateAuthCookie(const std::optional<fs::perms>& cookie_perms,
42+
std::string& user,
43+
std::string& pass);
44+
2845
/** Read the RPC authentication cookie from disk */
2946
boolGetAuthCookie(std::string *cookie_out);
3047
/** Delete RPC authentication cookie from disk */

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Commit 4272966

Browse files
committed
Merge bitcoin#32423: rpc: Undeprecate rpcuser/rpcpassword, store all credentials hashed in memory
e49a727 rpc: Avoid join-split roundtrip for user:pass for auth credentials (Vasil Dimov) 98ff38a rpc: Perform HTTP user:pass split once in `RPCAuthorized` (laanwj) 879a17b rpc: Store all credentials hashed in memory (laanwj) 4ab9bed rpc: Undeprecate rpcuser/rpcpassword, change message to security warning (laanwj) Pull request description: This PR does two things: ### Undeprecate rpcuser/rpcpassword, change message to security warning Back in 2015, in bitcoin#7044, we added configuration option `rpcauth` for multiple RPC users. At the same time the old settings for single-user configuration `rpcuser` and `rpcpassword` were "soon" to be deprecated. The main reason for this deprecation is that while `rpcpassword` stores the password in plain text, `rpcauth` stores a hash, so it doesn't appear in the configuration in plain text. As the options are still in active use, actually removing them is expected to be a hassle to many, and it's not clear that is worth it. As for the security risk, in many kinds of setups (no wallet, containerized, single-user-single-application, local-only, etc) it is an unlikely point of escalation. In the end, it is good to encourage secure practices, but it is the responsibility of the user. Log a clear warning but remove the deprecation notice (this is also the only place where the options appear as deprecated, they were never marked as such in the -help output). <hr> ### Store all credentials hashed in memory This gets rid of the special-casing of `strRPCUserColonPass` by hashing cookies as well as manually provided `-rpcuser`/`-rpcpassword` with a random salt before storing them. Also take the opportunity to modernize the surrounding code a bit. There should be no end-user visible differences in behavior. <hr> Closesbitcoin#29240. ACKs for top commit: 1440000bytes: utACK bitcoin@e49a727 janb84: reACK bitcoin@e49a727 vasild: ACK e49a727 Tree-SHA512: 7162848ada4545bc07b5843d1ab6fb7e31fb26de8d6385464b7c166491cd122eac2ec5e70887c414fc136600482df8277dc0cc0541d7b7cf62c4f72e25bb6145
2 parents ff1ee10 + e49a727 commit 4272966

3 files changed

Lines changed: 75 additions & 48 deletions

File tree

‎src/httprpc.cpp‎

Lines changed: 44 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -69,8 +69,6 @@ class HTTPRPCTimerInterface : public RPCTimerInterface
6969
};
7070

7171

72-
/* Pre-base64-encoded authentication token */
73-
static std::string strRPCUserColonPass;
7472
/* Stored RPC timer interface (for unregistration) */
7573
static std::unique_ptr<HTTPRPCTimerInterface> httpRPCTimerInterface;
7674
/* List of -rpcauth values */
@@ -101,31 +99,21 @@ static void JSONErrorReply(HTTPRequest* req, UniValue objError, const JSONRPCReq
10199

102100
//This function checks username and password against -rpcauth
103101
//entries from config file.
104-
staticboolmultiUserAuthorized(std::string strUserPass)
102+
staticboolCheckUserAuthorized(std::string_view user, std::string_view pass)
105103
{
106-
if (strUserPass.find(':') == std::string::npos) {
107-
returnfalse;
108-
}
109-
std::string strUser = strUserPass.substr(0, strUserPass.find(':'));
110-
std::string strPass = strUserPass.substr(strUserPass.find(':') + 1);
111-
112-
for (constauto& vFields : g_rpcauth) {
113-
std::string strName = vFields[0];
114-
if (!TimingResistantEqual(strName, strUser)) {
104+
for (constauto& fields : g_rpcauth) {
105+
if (!TimingResistantEqual(std::string_view(fields[0]), user)) {
115106
continue;
116107
}
117108

118-
std::string strSalt = vFields[1];
119-
std::string strHash = vFields[2];
109+
conststd::string& salt = fields[1];
110+
conststd::string& hash = fields[2];
120111

121-
staticconstunsignedintKEY_SIZE = 32;
122-
unsignedchar out[KEY_SIZE];
112+
std::array<unsignedchar, CHMAC_SHA256::OUTPUT_SIZE> out;
113+
CHMAC_SHA256(UCharCast(salt.data()), salt.size()).Write(UCharCast(pass.data()), pass.size()).Finalize(out.data());
114+
std::string hash_from_pass = HexStr(out);
123115

124-
CHMAC_SHA256(reinterpret_cast<constunsignedchar*>(strSalt.data()), strSalt.size()).Write(reinterpret_cast<constunsignedchar*>(strPass.data()), strPass.size()).Finalize(out);
125-
std::vector<unsignedchar> hexvec(out, out+KEY_SIZE);
126-
std::string strHashFromPass = HexStr(hexvec);
127-
128-
if (TimingResistantEqual(strHashFromPass, strHash)) {
116+
if (TimingResistantEqual(hash_from_pass, hash)) {
129117
returntrue;
130118
}
131119
}
@@ -142,15 +130,14 @@ static bool RPCAuthorized(const std::string& strAuth, std::string& strAuthUserna
142130
if (!userpass_data) returnfalse;
143131
strUserPass.assign(userpass_data->begin(), userpass_data->end());
144132

145-
if (strUserPass.find(':') != std::string::npos)
146-
strAuthUsernameOut = strUserPass.substr(0, strUserPass.find(':'));
147-
148-
// Check if authorized under single-user field.
149-
// (strRPCUserColonPass is empty when -norpccookiefile is specified).
150-
if (!strRPCUserColonPass.empty() && TimingResistantEqual(strUserPass, strRPCUserColonPass)) {
151-
returntrue;
133+
size_t colon_pos = strUserPass.find(':');
134+
if (colon_pos == std::string::npos) {
135+
returnfalse; // Invalid basic auth.
152136
}
153-
returnmultiUserAuthorized(strUserPass);
137+
std::string user = strUserPass.substr(0, colon_pos);
138+
std::string pass = strUserPass.substr(colon_pos + 1);
139+
strAuthUsernameOut = user;
140+
returnCheckUserAuthorized(user, pass);
154141
}
155142

156143
staticboolHTTPReq_JSONRPC(const std::any& context, HTTPRequest* req)
@@ -291,6 +278,9 @@ static bool HTTPReq_JSONRPC(const std::any& context, HTTPRequest* req)
291278

292279
staticboolInitRPCAuthentication()
293280
{
281+
std::string user;
282+
std::string pass;
283+
294284
if (gArgs.GetArg("-rpcpassword", "") == "")
295285
{
296286
std::optional<fs::perms> cookie_perms{std::nullopt};
@@ -304,18 +294,36 @@ static bool InitRPCAuthentication()
304294
cookie_perms = *perm_opt;
305295
}
306296

307-
assert(strRPCUserColonPass.empty()); // Only support initializing once
308-
if (!GenerateAuthCookie(&strRPCUserColonPass, cookie_perms)) {
297+
switch (GenerateAuthCookie(cookie_perms, user, pass)) {
298+
case GenerateAuthCookieResult::ERR:
309299
returnfalse;
310-
}
311-
if (strRPCUserColonPass.empty()) {
300+
case GenerateAuthCookieResult::DISABLED:
312301
LogInfo("RPC authentication cookie file generation is disabled.");
313-
} else {
302+
break;
303+
case GenerateAuthCookieResult::OK:
314304
LogInfo("Using random cookie authentication.");
305+
break;
315306
}
316307
} else {
317-
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");
318-
strRPCUserColonPass = gArgs.GetArg("-rpcuser", "") + ":" + gArgs.GetArg("-rpcpassword", "");
308+
LogInfo("Using rpcuser/rpcpassword authentication.");
309+
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+
user = gArgs.GetArg("-rpcuser", "");
311+
pass = gArgs.GetArg("-rpcpassword", "");
312+
}
313+
314+
// If there is a plaintext credential, hash it with a random salt before storage.
315+
if (!user.empty() || !pass.empty()) {
316+
// Generate a random 16 byte hex salt.
317+
std::array<unsignedchar, 16> raw_salt;
318+
GetStrongRandBytes(raw_salt);
319+
std::string salt = HexStr(raw_salt);
320+
321+
// Compute HMAC.
322+
std::array<unsignedchar, CHMAC_SHA256::OUTPUT_SIZE> out;
323+
CHMAC_SHA256(UCharCast(salt.data()), salt.size()).Write(UCharCast(pass.data()), pass.size()).Finalize(out.data());
324+
std::string hash = HexStr(out);
325+
326+
g_rpcauth.push_back({user, salt, hash});
319327
}
320328

321329
if (!gArgs.GetArgs("-rpcauth").empty()) {

‎src/rpc/request.cpp‎

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -97,50 +97,52 @@ static fs::path GetAuthCookieFile(bool temp=false)
9797

9898
staticbool g_generated_cookie = false;
9999

100-
boolGenerateAuthCookie(std::string* cookie_out, std::optional<fs::perms> cookie_perms)
100+
GenerateAuthCookieResult GenerateAuthCookie(const std::optional<fs::perms>& cookie_perms,
101+
std::string& user,
102+
std::string& pass)
101103
{
102104
constsize_tCOOKIE_SIZE = 32;
103105
unsignedchar rand_pwd[COOKIE_SIZE];
104106
GetRandBytes(rand_pwd);
105-
std::string cookie = COOKIEAUTH_USER + ":" + HexStr(rand_pwd);
107+
conststd::string rand_pwd_hex{HexStr(rand_pwd)};
106108

107109
/** the umask determines what permissions are used to create this file -
108110
* these are set to 0077 in common/system.cpp.
109111
*/
110112
std::ofstream file;
111113
fs::path filepath_tmp = GetAuthCookieFile(true);
112114
if (filepath_tmp.empty()) {
113-
returntrue; // -norpccookiefile
115+
returnGenerateAuthCookieResult::DISABLED; // -norpccookiefile
114116
}
115117
file.open(filepath_tmp);
116118
if (!file.is_open()) {
117119
LogWarning("Unable to open cookie authentication file %s for writing", fs::PathToString(filepath_tmp));
118-
returnfalse;
120+
returnGenerateAuthCookieResult::ERR;
119121
}
120-
file << cookie;
122+
file << COOKIEAUTH_USER << ":" << rand_pwd_hex;
121123
file.close();
122124

123125
fs::path filepath = GetAuthCookieFile(false);
124126
if (!RenameOver(filepath_tmp, filepath)) {
125127
LogWarning("Unable to rename cookie authentication file %s to %s", fs::PathToString(filepath_tmp), fs::PathToString(filepath));
126-
returnfalse;
128+
returnGenerateAuthCookieResult::ERR;
127129
}
128130
if (cookie_perms) {
129131
std::error_code code;
130132
fs::permissions(filepath, cookie_perms.value(), fs::perm_options::replace, code);
131133
if (code) {
132134
LogWarning("Unable to set permissions on cookie authentication file %s", fs::PathToString(filepath));
133-
returnfalse;
135+
returnGenerateAuthCookieResult::ERR;
134136
}
135137
}
136138

137139
g_generated_cookie = true;
138140
LogInfo("Generated RPC authentication cookie %s\n", fs::PathToString(filepath));
139141
LogInfo("Permissions used for cookie: %s\n", PermsToSymbolicString(fs::status(filepath).permissions()));
140142

141-
if (cookie_out)
142-
*cookie_out = cookie;
143-
returntrue;
143+
user = COOKIEAUTH_USER;
144+
pass = rand_pwd_hex;
145+
returnGenerateAuthCookieResult::OK;
144146
}
145147

146148
boolGetAuthCookie(std::string *cookie_out)

‎src/rpc/request.h‎

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,25 @@ UniValue JSONRPCRequestObj(const std::string& strMethod, const UniValue& params,
2323
UniValue JSONRPCReplyObj(UniValue result, UniValue error, std::optional<UniValue> id, JSONRPCVersion jsonrpc_version);
2424
UniValue JSONRPCError(int code, const std::string& message);
2525

26-
/** Generate a new RPC authentication cookie and write it to disk */
27-
boolGenerateAuthCookie(std::string* cookie_out, std::optional<fs::perms> cookie_perms=std::nullopt);
26+
enumclassGenerateAuthCookieResult : uint8_t {
27+
DISABLED, // -norpccookiefile
28+
ERR,
29+
OK,
30+
};
31+
32+
/**
33+
* Generate a new RPC authentication cookie and write it to disk
34+
* @param[in] cookie_perms Filesystem permissions to use for the cookie file.
35+
* @param[out] user Generated username, only set if `OK` is returned.
36+
* @param[out] pass Generated password, only set if `OK` is returned.
37+
* @retval GenerateAuthCookieResult::DISABLED Authentication via cookie is disabled.
38+
* @retval GenerateAuthCookieResult::ERROR Error occurred, auth data could not be saved to disk.
39+
* @retval GenerateAuthCookieResult::OK Auth data was generated, saved to disk and in `user` and `pass`.
40+
*/
41+
GenerateAuthCookieResult GenerateAuthCookie(const std::optional<fs::perms>& cookie_perms,
42+
std::string& user,
43+
std::string& pass);
44+
2845
/** Read the RPC authentication cookie from disk */
2946
boolGetAuthCookie(std::string *cookie_out);
3047
/** Delete RPC authentication cookie from disk */

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit 4272966

Browse files
committed
Merge bitcoin#32423: rpc: Undeprecate rpcuser/rpcpassword, store all credentials hashed in memory
e49a727 rpc: Avoid join-split roundtrip for user:pass for auth credentials (Vasil Dimov) 98ff38a rpc: Perform HTTP user:pass split once in `RPCAuthorized` (laanwj) 879a17b rpc: Store all credentials hashed in memory (laanwj) 4ab9bed rpc: Undeprecate rpcuser/rpcpassword, change message to security warning (laanwj) Pull request description: This PR does two things: ### Undeprecate rpcuser/rpcpassword, change message to security warning Back in 2015, in bitcoin#7044, we added configuration option `rpcauth` for multiple RPC users. At the same time the old settings for single-user configuration `rpcuser` and `rpcpassword` were "soon" to be deprecated. The main reason for this deprecation is that while `rpcpassword` stores the password in plain text, `rpcauth` stores a hash, so it doesn't appear in the configuration in plain text. As the options are still in active use, actually removing them is expected to be a hassle to many, and it's not clear that is worth it. As for the security risk, in many kinds of setups (no wallet, containerized, single-user-single-application, local-only, etc) it is an unlikely point of escalation. In the end, it is good to encourage secure practices, but it is the responsibility of the user. Log a clear warning but remove the deprecation notice (this is also the only place where the options appear as deprecated, they were never marked as such in the -help output). <hr> ### Store all credentials hashed in memory This gets rid of the special-casing of `strRPCUserColonPass` by hashing cookies as well as manually provided `-rpcuser`/`-rpcpassword` with a random salt before storing them. Also take the opportunity to modernize the surrounding code a bit. There should be no end-user visible differences in behavior. <hr> Closesbitcoin#29240. ACKs for top commit: 1440000bytes: utACK bitcoin@e49a727 janb84: reACK bitcoin@e49a727 vasild: ACK e49a727 Tree-SHA512: 7162848ada4545bc07b5843d1ab6fb7e31fb26de8d6385464b7c166491cd122eac2ec5e70887c414fc136600482df8277dc0cc0541d7b7cf62c4f72e25bb6145
2 parents ff1ee10 + e49a727 commit 4272966

3 files changed

Lines changed: 75 additions & 48 deletions

File tree

‎src/httprpc.cpp‎

Lines changed: 44 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -69,8 +69,6 @@ class HTTPRPCTimerInterface : public RPCTimerInterface
6969
};
7070

7171

72-
/* Pre-base64-encoded authentication token */
73-
static std::string strRPCUserColonPass;
7472
/* Stored RPC timer interface (for unregistration) */
7573
static std::unique_ptr<HTTPRPCTimerInterface> httpRPCTimerInterface;
7674
/* List of -rpcauth values */
@@ -101,31 +99,21 @@ static void JSONErrorReply(HTTPRequest* req, UniValue objError, const JSONRPCReq
10199

102100
//This function checks username and password against -rpcauth
103101
//entries from config file.
104-
staticboolmultiUserAuthorized(std::string strUserPass)
102+
staticboolCheckUserAuthorized(std::string_view user, std::string_view pass)
105103
{
106-
if (strUserPass.find(':') == std::string::npos) {
107-
returnfalse;
108-
}
109-
std::string strUser = strUserPass.substr(0, strUserPass.find(':'));
110-
std::string strPass = strUserPass.substr(strUserPass.find(':') + 1);
111-
112-
for (constauto& vFields : g_rpcauth) {
113-
std::string strName = vFields[0];
114-
if (!TimingResistantEqual(strName, strUser)) {
104+
for (constauto& fields : g_rpcauth) {
105+
if (!TimingResistantEqual(std::string_view(fields[0]), user)) {
115106
continue;
116107
}
117108

118-
std::string strSalt = vFields[1];
119-
std::string strHash = vFields[2];
109+
conststd::string& salt = fields[1];
110+
conststd::string& hash = fields[2];
120111

121-
staticconstunsignedintKEY_SIZE = 32;
122-
unsignedchar out[KEY_SIZE];
112+
std::array<unsignedchar, CHMAC_SHA256::OUTPUT_SIZE> out;
113+
CHMAC_SHA256(UCharCast(salt.data()), salt.size()).Write(UCharCast(pass.data()), pass.size()).Finalize(out.data());
114+
std::string hash_from_pass = HexStr(out);
123115

124-
CHMAC_SHA256(reinterpret_cast<constunsignedchar*>(strSalt.data()), strSalt.size()).Write(reinterpret_cast<constunsignedchar*>(strPass.data()), strPass.size()).Finalize(out);
125-
std::vector<unsignedchar> hexvec(out, out+KEY_SIZE);
126-
std::string strHashFromPass = HexStr(hexvec);
127-
128-
if (TimingResistantEqual(strHashFromPass, strHash)) {
116+
if (TimingResistantEqual(hash_from_pass, hash)) {
129117
returntrue;
130118
}
131119
}
@@ -142,15 +130,14 @@ static bool RPCAuthorized(const std::string& strAuth, std::string& strAuthUserna
142130
if (!userpass_data) returnfalse;
143131
strUserPass.assign(userpass_data->begin(), userpass_data->end());
144132

145-
if (strUserPass.find(':') != std::string::npos)
146-
strAuthUsernameOut = strUserPass.substr(0, strUserPass.find(':'));
147-
148-
// Check if authorized under single-user field.
149-
// (strRPCUserColonPass is empty when -norpccookiefile is specified).
150-
if (!strRPCUserColonPass.empty() && TimingResistantEqual(strUserPass, strRPCUserColonPass)) {
151-
returntrue;
133+
size_t colon_pos = strUserPass.find(':');
134+
if (colon_pos == std::string::npos) {
135+
returnfalse; // Invalid basic auth.
152136
}
153-
returnmultiUserAuthorized(strUserPass);
137+
std::string user = strUserPass.substr(0, colon_pos);
138+
std::string pass = strUserPass.substr(colon_pos + 1);
139+
strAuthUsernameOut = user;
140+
returnCheckUserAuthorized(user, pass);
154141
}
155142

156143
staticboolHTTPReq_JSONRPC(const std::any& context, HTTPRequest* req)
@@ -291,6 +278,9 @@ static bool HTTPReq_JSONRPC(const std::any& context, HTTPRequest* req)
291278

292279
staticboolInitRPCAuthentication()
293280
{
281+
std::string user;
282+
std::string pass;
283+
294284
if (gArgs.GetArg("-rpcpassword", "") == "")
295285
{
296286
std::optional<fs::perms> cookie_perms{std::nullopt};
@@ -304,18 +294,36 @@ static bool InitRPCAuthentication()
304294
cookie_perms = *perm_opt;
305295
}
306296

307-
assert(strRPCUserColonPass.empty()); // Only support initializing once
308-
if (!GenerateAuthCookie(&strRPCUserColonPass, cookie_perms)) {
297+
switch (GenerateAuthCookie(cookie_perms, user, pass)) {
298+
case GenerateAuthCookieResult::ERR:
309299
returnfalse;
310-
}
311-
if (strRPCUserColonPass.empty()) {
300+
case GenerateAuthCookieResult::DISABLED:
312301
LogInfo("RPC authentication cookie file generation is disabled.");
313-
} else {
302+
break;
303+
case GenerateAuthCookieResult::OK:
314304
LogInfo("Using random cookie authentication.");
305+
break;
315306
}
316307
} else {
317-
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");
318-
strRPCUserColonPass = gArgs.GetArg("-rpcuser", "") + ":" + gArgs.GetArg("-rpcpassword", "");
308+
LogInfo("Using rpcuser/rpcpassword authentication.");
309+
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+
user = gArgs.GetArg("-rpcuser", "");
311+
pass = gArgs.GetArg("-rpcpassword", "");
312+
}
313+
314+
// If there is a plaintext credential, hash it with a random salt before storage.
315+
if (!user.empty() || !pass.empty()) {
316+
// Generate a random 16 byte hex salt.
317+
std::array<unsignedchar, 16> raw_salt;
318+
GetStrongRandBytes(raw_salt);
319+
std::string salt = HexStr(raw_salt);
320+
321+
// Compute HMAC.
322+
std::array<unsignedchar, CHMAC_SHA256::OUTPUT_SIZE> out;
323+
CHMAC_SHA256(UCharCast(salt.data()), salt.size()).Write(UCharCast(pass.data()), pass.size()).Finalize(out.data());
324+
std::string hash = HexStr(out);
325+
326+
g_rpcauth.push_back({user, salt, hash});
319327
}
320328

321329
if (!gArgs.GetArgs("-rpcauth").empty()) {

‎src/rpc/request.cpp‎

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -97,50 +97,52 @@ static fs::path GetAuthCookieFile(bool temp=false)
9797

9898
staticbool g_generated_cookie = false;
9999

100-
boolGenerateAuthCookie(std::string* cookie_out, std::optional<fs::perms> cookie_perms)
100+
GenerateAuthCookieResult GenerateAuthCookie(const std::optional<fs::perms>& cookie_perms,
101+
std::string& user,
102+
std::string& pass)
101103
{
102104
constsize_tCOOKIE_SIZE = 32;
103105
unsignedchar rand_pwd[COOKIE_SIZE];
104106
GetRandBytes(rand_pwd);
105-
std::string cookie = COOKIEAUTH_USER + ":" + HexStr(rand_pwd);
107+
conststd::string rand_pwd_hex{HexStr(rand_pwd)};
106108

107109
/** the umask determines what permissions are used to create this file -
108110
* these are set to 0077 in common/system.cpp.
109111
*/
110112
std::ofstream file;
111113
fs::path filepath_tmp = GetAuthCookieFile(true);
112114
if (filepath_tmp.empty()) {
113-
returntrue; // -norpccookiefile
115+
returnGenerateAuthCookieResult::DISABLED; // -norpccookiefile
114116
}
115117
file.open(filepath_tmp);
116118
if (!file.is_open()) {
117119
LogWarning("Unable to open cookie authentication file %s for writing", fs::PathToString(filepath_tmp));
118-
returnfalse;
120+
returnGenerateAuthCookieResult::ERR;
119121
}
120-
file << cookie;
122+
file << COOKIEAUTH_USER << ":" << rand_pwd_hex;
121123
file.close();
122124

123125
fs::path filepath = GetAuthCookieFile(false);
124126
if (!RenameOver(filepath_tmp, filepath)) {
125127
LogWarning("Unable to rename cookie authentication file %s to %s", fs::PathToString(filepath_tmp), fs::PathToString(filepath));
126-
returnfalse;
128+
returnGenerateAuthCookieResult::ERR;
127129
}
128130
if (cookie_perms) {
129131
std::error_code code;
130132
fs::permissions(filepath, cookie_perms.value(), fs::perm_options::replace, code);
131133
if (code) {
132134
LogWarning("Unable to set permissions on cookie authentication file %s", fs::PathToString(filepath));
133-
returnfalse;
135+
returnGenerateAuthCookieResult::ERR;
134136
}
135137
}
136138

137139
g_generated_cookie = true;
138140
LogInfo("Generated RPC authentication cookie %s\n", fs::PathToString(filepath));
139141
LogInfo("Permissions used for cookie: %s\n", PermsToSymbolicString(fs::status(filepath).permissions()));
140142

141-
if (cookie_out)
142-
*cookie_out = cookie;
143-
returntrue;
143+
user = COOKIEAUTH_USER;
144+
pass = rand_pwd_hex;
145+
returnGenerateAuthCookieResult::OK;
144146
}
145147

146148
boolGetAuthCookie(std::string *cookie_out)

‎src/rpc/request.h‎

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,25 @@ UniValue JSONRPCRequestObj(const std::string& strMethod, const UniValue& params,
2323
UniValue JSONRPCReplyObj(UniValue result, UniValue error, std::optional<UniValue> id, JSONRPCVersion jsonrpc_version);
2424
UniValue JSONRPCError(int code, const std::string& message);
2525

26-
/** Generate a new RPC authentication cookie and write it to disk */
27-
boolGenerateAuthCookie(std::string* cookie_out, std::optional<fs::perms> cookie_perms=std::nullopt);
26+
enumclassGenerateAuthCookieResult : uint8_t {
27+
DISABLED, // -norpccookiefile
28+
ERR,
29+
OK,
30+
};
31+
32+
/**
33+
* Generate a new RPC authentication cookie and write it to disk
34+
* @param[in] cookie_perms Filesystem permissions to use for the cookie file.
35+
* @param[out] user Generated username, only set if `OK` is returned.
36+
* @param[out] pass Generated password, only set if `OK` is returned.
37+
* @retval GenerateAuthCookieResult::DISABLED Authentication via cookie is disabled.
38+
* @retval GenerateAuthCookieResult::ERROR Error occurred, auth data could not be saved to disk.
39+
* @retval GenerateAuthCookieResult::OK Auth data was generated, saved to disk and in `user` and `pass`.
40+
*/
41+
GenerateAuthCookieResult GenerateAuthCookie(const std::optional<fs::perms>& cookie_perms,
42+
std::string& user,
43+
std::string& pass);
44+
2845
/** Read the RPC authentication cookie from disk */
2946
boolGetAuthCookie(std::string *cookie_out);
3047
/** Delete RPC authentication cookie from disk */

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit 4272966

Browse files
committed
Merge bitcoin#32423: rpc: Undeprecate rpcuser/rpcpassword, store all credentials hashed in memory
e49a727 rpc: Avoid join-split roundtrip for user:pass for auth credentials (Vasil Dimov) 98ff38a rpc: Perform HTTP user:pass split once in `RPCAuthorized` (laanwj) 879a17b rpc: Store all credentials hashed in memory (laanwj) 4ab9bed rpc: Undeprecate rpcuser/rpcpassword, change message to security warning (laanwj) Pull request description: This PR does two things: ### Undeprecate rpcuser/rpcpassword, change message to security warning Back in 2015, in bitcoin#7044, we added configuration option `rpcauth` for multiple RPC users. At the same time the old settings for single-user configuration `rpcuser` and `rpcpassword` were "soon" to be deprecated. The main reason for this deprecation is that while `rpcpassword` stores the password in plain text, `rpcauth` stores a hash, so it doesn't appear in the configuration in plain text. As the options are still in active use, actually removing them is expected to be a hassle to many, and it's not clear that is worth it. As for the security risk, in many kinds of setups (no wallet, containerized, single-user-single-application, local-only, etc) it is an unlikely point of escalation. In the end, it is good to encourage secure practices, but it is the responsibility of the user. Log a clear warning but remove the deprecation notice (this is also the only place where the options appear as deprecated, they were never marked as such in the -help output). <hr> ### Store all credentials hashed in memory This gets rid of the special-casing of `strRPCUserColonPass` by hashing cookies as well as manually provided `-rpcuser`/`-rpcpassword` with a random salt before storing them. Also take the opportunity to modernize the surrounding code a bit. There should be no end-user visible differences in behavior. <hr> Closesbitcoin#29240. ACKs for top commit: 1440000bytes: utACK bitcoin@e49a727 janb84: reACK bitcoin@e49a727 vasild: ACK e49a727 Tree-SHA512: 7162848ada4545bc07b5843d1ab6fb7e31fb26de8d6385464b7c166491cd122eac2ec5e70887c414fc136600482df8277dc0cc0541d7b7cf62c4f72e25bb6145
2 parents ff1ee10 + e49a727 commit 4272966

3 files changed

Lines changed: 75 additions & 48 deletions

File tree

‎src/httprpc.cpp‎

Lines changed: 44 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -69,8 +69,6 @@ class HTTPRPCTimerInterface : public RPCTimerInterface
6969
};
7070

7171

72-
/* Pre-base64-encoded authentication token */
73-
static std::string strRPCUserColonPass;
7472
/* Stored RPC timer interface (for unregistration) */
7573
static std::unique_ptr<HTTPRPCTimerInterface> httpRPCTimerInterface;
7674
/* List of -rpcauth values */
@@ -101,31 +99,21 @@ static void JSONErrorReply(HTTPRequest* req, UniValue objError, const JSONRPCReq
10199

102100
//This function checks username and password against -rpcauth
103101
//entries from config file.
104-
staticboolmultiUserAuthorized(std::string strUserPass)
102+
staticboolCheckUserAuthorized(std::string_view user, std::string_view pass)
105103
{
106-
if (strUserPass.find(':') == std::string::npos) {
107-
returnfalse;
108-
}
109-
std::string strUser = strUserPass.substr(0, strUserPass.find(':'));
110-
std::string strPass = strUserPass.substr(strUserPass.find(':') + 1);
111-
112-
for (constauto& vFields : g_rpcauth) {
113-
std::string strName = vFields[0];
114-
if (!TimingResistantEqual(strName, strUser)) {
104+
for (constauto& fields : g_rpcauth) {
105+
if (!TimingResistantEqual(std::string_view(fields[0]), user)) {
115106
continue;
116107
}
117108

118-
std::string strSalt = vFields[1];
119-
std::string strHash = vFields[2];
109+
conststd::string& salt = fields[1];
110+
conststd::string& hash = fields[2];
120111

121-
staticconstunsignedintKEY_SIZE = 32;
122-
unsignedchar out[KEY_SIZE];
112+
std::array<unsignedchar, CHMAC_SHA256::OUTPUT_SIZE> out;
113+
CHMAC_SHA256(UCharCast(salt.data()), salt.size()).Write(UCharCast(pass.data()), pass.size()).Finalize(out.data());
114+
std::string hash_from_pass = HexStr(out);
123115

124-
CHMAC_SHA256(reinterpret_cast<constunsignedchar*>(strSalt.data()), strSalt.size()).Write(reinterpret_cast<constunsignedchar*>(strPass.data()), strPass.size()).Finalize(out);
125-
std::vector<unsignedchar> hexvec(out, out+KEY_SIZE);
126-
std::string strHashFromPass = HexStr(hexvec);
127-
128-
if (TimingResistantEqual(strHashFromPass, strHash)) {
116+
if (TimingResistantEqual(hash_from_pass, hash)) {
129117
returntrue;
130118
}
131119
}
@@ -142,15 +130,14 @@ static bool RPCAuthorized(const std::string& strAuth, std::string& strAuthUserna
142130
if (!userpass_data) returnfalse;
143131
strUserPass.assign(userpass_data->begin(), userpass_data->end());
144132

145-
if (strUserPass.find(':') != std::string::npos)
146-
strAuthUsernameOut = strUserPass.substr(0, strUserPass.find(':'));
147-
148-
// Check if authorized under single-user field.
149-
// (strRPCUserColonPass is empty when -norpccookiefile is specified).
150-
if (!strRPCUserColonPass.empty() && TimingResistantEqual(strUserPass, strRPCUserColonPass)) {
151-
returntrue;
133+
size_t colon_pos = strUserPass.find(':');
134+
if (colon_pos == std::string::npos) {
135+
returnfalse; // Invalid basic auth.
152136
}
153-
returnmultiUserAuthorized(strUserPass);
137+
std::string user = strUserPass.substr(0, colon_pos);
138+
std::string pass = strUserPass.substr(colon_pos + 1);
139+
strAuthUsernameOut = user;
140+
returnCheckUserAuthorized(user, pass);
154141
}
155142

156143
staticboolHTTPReq_JSONRPC(const std::any& context, HTTPRequest* req)
@@ -291,6 +278,9 @@ static bool HTTPReq_JSONRPC(const std::any& context, HTTPRequest* req)
291278

292279
staticboolInitRPCAuthentication()
293280
{
281+
std::string user;
282+
std::string pass;
283+
294284
if (gArgs.GetArg("-rpcpassword", "") == "")
295285
{
296286
std::optional<fs::perms> cookie_perms{std::nullopt};
@@ -304,18 +294,36 @@ static bool InitRPCAuthentication()
304294
cookie_perms = *perm_opt;
305295
}
306296

307-
assert(strRPCUserColonPass.empty()); // Only support initializing once
308-
if (!GenerateAuthCookie(&strRPCUserColonPass, cookie_perms)) {
297+
switch (GenerateAuthCookie(cookie_perms, user, pass)) {
298+
case GenerateAuthCookieResult::ERR:
309299
returnfalse;
310-
}
311-
if (strRPCUserColonPass.empty()) {
300+
case GenerateAuthCookieResult::DISABLED:
312301
LogInfo("RPC authentication cookie file generation is disabled.");
313-
} else {
302+
break;
303+
case GenerateAuthCookieResult::OK:
314304
LogInfo("Using random cookie authentication.");
305+
break;
315306
}
316307
} else {
317-
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");
318-
strRPCUserColonPass = gArgs.GetArg("-rpcuser", "") + ":" + gArgs.GetArg("-rpcpassword", "");
308+
LogInfo("Using rpcuser/rpcpassword authentication.");
309+
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+
user = gArgs.GetArg("-rpcuser", "");
311+
pass = gArgs.GetArg("-rpcpassword", "");
312+
}
313+
314+
// If there is a plaintext credential, hash it with a random salt before storage.
315+
if (!user.empty() || !pass.empty()) {
316+
// Generate a random 16 byte hex salt.
317+
std::array<unsignedchar, 16> raw_salt;
318+
GetStrongRandBytes(raw_salt);
319+
std::string salt = HexStr(raw_salt);
320+
321+
// Compute HMAC.
322+
std::array<unsignedchar, CHMAC_SHA256::OUTPUT_SIZE> out;
323+
CHMAC_SHA256(UCharCast(salt.data()), salt.size()).Write(UCharCast(pass.data()), pass.size()).Finalize(out.data());
324+
std::string hash = HexStr(out);
325+
326+
g_rpcauth.push_back({user, salt, hash});
319327
}
320328

321329
if (!gArgs.GetArgs("-rpcauth").empty()) {

‎src/rpc/request.cpp‎

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -97,50 +97,52 @@ static fs::path GetAuthCookieFile(bool temp=false)
9797

9898
staticbool g_generated_cookie = false;
9999

100-
boolGenerateAuthCookie(std::string* cookie_out, std::optional<fs::perms> cookie_perms)
100+
GenerateAuthCookieResult GenerateAuthCookie(const std::optional<fs::perms>& cookie_perms,
101+
std::string& user,
102+
std::string& pass)
101103
{
102104
constsize_tCOOKIE_SIZE = 32;
103105
unsignedchar rand_pwd[COOKIE_SIZE];
104106
GetRandBytes(rand_pwd);
105-
std::string cookie = COOKIEAUTH_USER + ":" + HexStr(rand_pwd);
107+
conststd::string rand_pwd_hex{HexStr(rand_pwd)};
106108

107109
/** the umask determines what permissions are used to create this file -
108110
* these are set to 0077 in common/system.cpp.
109111
*/
110112
std::ofstream file;
111113
fs::path filepath_tmp = GetAuthCookieFile(true);
112114
if (filepath_tmp.empty()) {
113-
returntrue; // -norpccookiefile
115+
returnGenerateAuthCookieResult::DISABLED; // -norpccookiefile
114116
}
115117
file.open(filepath_tmp);
116118
if (!file.is_open()) {
117119
LogWarning("Unable to open cookie authentication file %s for writing", fs::PathToString(filepath_tmp));
118-
returnfalse;
120+
returnGenerateAuthCookieResult::ERR;
119121
}
120-
file << cookie;
122+
file << COOKIEAUTH_USER << ":" << rand_pwd_hex;
121123
file.close();
122124

123125
fs::path filepath = GetAuthCookieFile(false);
124126
if (!RenameOver(filepath_tmp, filepath)) {
125127
LogWarning("Unable to rename cookie authentication file %s to %s", fs::PathToString(filepath_tmp), fs::PathToString(filepath));
126-
returnfalse;
128+
returnGenerateAuthCookieResult::ERR;
127129
}
128130
if (cookie_perms) {
129131
std::error_code code;
130132
fs::permissions(filepath, cookie_perms.value(), fs::perm_options::replace, code);
131133
if (code) {
132134
LogWarning("Unable to set permissions on cookie authentication file %s", fs::PathToString(filepath));
133-
returnfalse;
135+
returnGenerateAuthCookieResult::ERR;
134136
}
135137
}
136138

137139
g_generated_cookie = true;
138140
LogInfo("Generated RPC authentication cookie %s\n", fs::PathToString(filepath));
139141
LogInfo("Permissions used for cookie: %s\n", PermsToSymbolicString(fs::status(filepath).permissions()));
140142

141-
if (cookie_out)
142-
*cookie_out = cookie;
143-
returntrue;
143+
user = COOKIEAUTH_USER;
144+
pass = rand_pwd_hex;
145+
returnGenerateAuthCookieResult::OK;
144146
}
145147

146148
boolGetAuthCookie(std::string *cookie_out)

‎src/rpc/request.h‎

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,25 @@ UniValue JSONRPCRequestObj(const std::string& strMethod, const UniValue& params,
2323
UniValue JSONRPCReplyObj(UniValue result, UniValue error, std::optional<UniValue> id, JSONRPCVersion jsonrpc_version);
2424
UniValue JSONRPCError(int code, const std::string& message);
2525

26-
/** Generate a new RPC authentication cookie and write it to disk */
27-
boolGenerateAuthCookie(std::string* cookie_out, std::optional<fs::perms> cookie_perms=std::nullopt);
26+
enumclassGenerateAuthCookieResult : uint8_t {
27+
DISABLED, // -norpccookiefile
28+
ERR,
29+
OK,
30+
};
31+
32+
/**
33+
* Generate a new RPC authentication cookie and write it to disk
34+
* @param[in] cookie_perms Filesystem permissions to use for the cookie file.
35+
* @param[out] user Generated username, only set if `OK` is returned.
36+
* @param[out] pass Generated password, only set if `OK` is returned.
37+
* @retval GenerateAuthCookieResult::DISABLED Authentication via cookie is disabled.
38+
* @retval GenerateAuthCookieResult::ERROR Error occurred, auth data could not be saved to disk.
39+
* @retval GenerateAuthCookieResult::OK Auth data was generated, saved to disk and in `user` and `pass`.
40+
*/
41+
GenerateAuthCookieResult GenerateAuthCookie(const std::optional<fs::perms>& cookie_perms,
42+
std::string& user,
43+
std::string& pass);
44+
2845
/** Read the RPC authentication cookie from disk */
2946
boolGetAuthCookie(std::string *cookie_out);
3047
/** Delete RPC authentication cookie from disk */

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Commit 4272966

Browse files
committed
Merge bitcoin#32423: rpc: Undeprecate rpcuser/rpcpassword, store all credentials hashed in memory
e49a727 rpc: Avoid join-split roundtrip for user:pass for auth credentials (Vasil Dimov) 98ff38a rpc: Perform HTTP user:pass split once in `RPCAuthorized` (laanwj) 879a17b rpc: Store all credentials hashed in memory (laanwj) 4ab9bed rpc: Undeprecate rpcuser/rpcpassword, change message to security warning (laanwj) Pull request description: This PR does two things: ### Undeprecate rpcuser/rpcpassword, change message to security warning Back in 2015, in bitcoin#7044, we added configuration option `rpcauth` for multiple RPC users. At the same time the old settings for single-user configuration `rpcuser` and `rpcpassword` were "soon" to be deprecated. The main reason for this deprecation is that while `rpcpassword` stores the password in plain text, `rpcauth` stores a hash, so it doesn't appear in the configuration in plain text. As the options are still in active use, actually removing them is expected to be a hassle to many, and it's not clear that is worth it. As for the security risk, in many kinds of setups (no wallet, containerized, single-user-single-application, local-only, etc) it is an unlikely point of escalation. In the end, it is good to encourage secure practices, but it is the responsibility of the user. Log a clear warning but remove the deprecation notice (this is also the only place where the options appear as deprecated, they were never marked as such in the -help output). <hr> ### Store all credentials hashed in memory This gets rid of the special-casing of `strRPCUserColonPass` by hashing cookies as well as manually provided `-rpcuser`/`-rpcpassword` with a random salt before storing them. Also take the opportunity to modernize the surrounding code a bit. There should be no end-user visible differences in behavior. <hr> Closesbitcoin#29240. ACKs for top commit: 1440000bytes: utACK bitcoin@e49a727 janb84: reACK bitcoin@e49a727 vasild: ACK e49a727 Tree-SHA512: 7162848ada4545bc07b5843d1ab6fb7e31fb26de8d6385464b7c166491cd122eac2ec5e70887c414fc136600482df8277dc0cc0541d7b7cf62c4f72e25bb6145
2 parents ff1ee10 + e49a727 commit 4272966

3 files changed

Lines changed: 75 additions & 48 deletions

File tree

‎src/httprpc.cpp‎

Lines changed: 44 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -69,8 +69,6 @@ class HTTPRPCTimerInterface : public RPCTimerInterface
6969
};
7070

7171

72-
/* Pre-base64-encoded authentication token */
73-
static std::string strRPCUserColonPass;
7472
/* Stored RPC timer interface (for unregistration) */
7573
static std::unique_ptr<HTTPRPCTimerInterface> httpRPCTimerInterface;
7674
/* List of -rpcauth values */
@@ -101,31 +99,21 @@ static void JSONErrorReply(HTTPRequest* req, UniValue objError, const JSONRPCReq
10199

102100
//This function checks username and password against -rpcauth
103101
//entries from config file.
104-
staticboolmultiUserAuthorized(std::string strUserPass)
102+
staticboolCheckUserAuthorized(std::string_view user, std::string_view pass)
105103
{
106-
if (strUserPass.find(':') == std::string::npos) {
107-
returnfalse;
108-
}
109-
std::string strUser = strUserPass.substr(0, strUserPass.find(':'));
110-
std::string strPass = strUserPass.substr(strUserPass.find(':') + 1);
111-
112-
for (constauto& vFields : g_rpcauth) {
113-
std::string strName = vFields[0];
114-
if (!TimingResistantEqual(strName, strUser)) {
104+
for (constauto& fields : g_rpcauth) {
105+
if (!TimingResistantEqual(std::string_view(fields[0]), user)) {
115106
continue;
116107
}
117108

118-
std::string strSalt = vFields[1];
119-
std::string strHash = vFields[2];
109+
conststd::string& salt = fields[1];
110+
conststd::string& hash = fields[2];
120111

121-
staticconstunsignedintKEY_SIZE = 32;
122-
unsignedchar out[KEY_SIZE];
112+
std::array<unsignedchar, CHMAC_SHA256::OUTPUT_SIZE> out;
113+
CHMAC_SHA256(UCharCast(salt.data()), salt.size()).Write(UCharCast(pass.data()), pass.size()).Finalize(out.data());
114+
std::string hash_from_pass = HexStr(out);
123115

124-
CHMAC_SHA256(reinterpret_cast<constunsignedchar*>(strSalt.data()), strSalt.size()).Write(reinterpret_cast<constunsignedchar*>(strPass.data()), strPass.size()).Finalize(out);
125-
std::vector<unsignedchar> hexvec(out, out+KEY_SIZE);
126-
std::string strHashFromPass = HexStr(hexvec);
127-
128-
if (TimingResistantEqual(strHashFromPass, strHash)) {
116+
if (TimingResistantEqual(hash_from_pass, hash)) {
129117
returntrue;
130118
}
131119
}
@@ -142,15 +130,14 @@ static bool RPCAuthorized(const std::string& strAuth, std::string& strAuthUserna
142130
if (!userpass_data) returnfalse;
143131
strUserPass.assign(userpass_data->begin(), userpass_data->end());
144132

145-
if (strUserPass.find(':') != std::string::npos)
146-
strAuthUsernameOut = strUserPass.substr(0, strUserPass.find(':'));
147-
148-
// Check if authorized under single-user field.
149-
// (strRPCUserColonPass is empty when -norpccookiefile is specified).
150-
if (!strRPCUserColonPass.empty() && TimingResistantEqual(strUserPass, strRPCUserColonPass)) {
151-
returntrue;
133+
size_t colon_pos = strUserPass.find(':');
134+
if (colon_pos == std::string::npos) {
135+
returnfalse; // Invalid basic auth.
152136
}
153-
returnmultiUserAuthorized(strUserPass);
137+
std::string user = strUserPass.substr(0, colon_pos);
138+
std::string pass = strUserPass.substr(colon_pos + 1);
139+
strAuthUsernameOut = user;
140+
returnCheckUserAuthorized(user, pass);
154141
}
155142

156143
staticboolHTTPReq_JSONRPC(const std::any& context, HTTPRequest* req)
@@ -291,6 +278,9 @@ static bool HTTPReq_JSONRPC(const std::any& context, HTTPRequest* req)
291278

292279
staticboolInitRPCAuthentication()
293280
{
281+
std::string user;
282+
std::string pass;
283+
294284
if (gArgs.GetArg("-rpcpassword", "") == "")
295285
{
296286
std::optional<fs::perms> cookie_perms{std::nullopt};
@@ -304,18 +294,36 @@ static bool InitRPCAuthentication()
304294
cookie_perms = *perm_opt;
305295
}
306296

307-
assert(strRPCUserColonPass.empty()); // Only support initializing once
308-
if (!GenerateAuthCookie(&strRPCUserColonPass, cookie_perms)) {
297+
switch (GenerateAuthCookie(cookie_perms, user, pass)) {
298+
case GenerateAuthCookieResult::ERR:
309299
returnfalse;
310-
}
311-
if (strRPCUserColonPass.empty()) {
300+
case GenerateAuthCookieResult::DISABLED:
312301
LogInfo("RPC authentication cookie file generation is disabled.");
313-
} else {
302+
break;
303+
case GenerateAuthCookieResult::OK:
314304
LogInfo("Using random cookie authentication.");
305+
break;
315306
}
316307
} else {
317-
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");
318-
strRPCUserColonPass = gArgs.GetArg("-rpcuser", "") + ":" + gArgs.GetArg("-rpcpassword", "");
308+
LogInfo("Using rpcuser/rpcpassword authentication.");
309+
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+
user = gArgs.GetArg("-rpcuser", "");
311+
pass = gArgs.GetArg("-rpcpassword", "");
312+
}
313+
314+
// If there is a plaintext credential, hash it with a random salt before storage.
315+
if (!user.empty() || !pass.empty()) {
316+
// Generate a random 16 byte hex salt.
317+
std::array<unsignedchar, 16> raw_salt;
318+
GetStrongRandBytes(raw_salt);
319+
std::string salt = HexStr(raw_salt);
320+
321+
// Compute HMAC.
322+
std::array<unsignedchar, CHMAC_SHA256::OUTPUT_SIZE> out;
323+
CHMAC_SHA256(UCharCast(salt.data()), salt.size()).Write(UCharCast(pass.data()), pass.size()).Finalize(out.data());
324+
std::string hash = HexStr(out);
325+
326+
g_rpcauth.push_back({user, salt, hash});
319327
}
320328

321329
if (!gArgs.GetArgs("-rpcauth").empty()) {

‎src/rpc/request.cpp‎

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -97,50 +97,52 @@ static fs::path GetAuthCookieFile(bool temp=false)
9797

9898
staticbool g_generated_cookie = false;
9999

100-
boolGenerateAuthCookie(std::string* cookie_out, std::optional<fs::perms> cookie_perms)
100+
GenerateAuthCookieResult GenerateAuthCookie(const std::optional<fs::perms>& cookie_perms,
101+
std::string& user,
102+
std::string& pass)
101103
{
102104
constsize_tCOOKIE_SIZE = 32;
103105
unsignedchar rand_pwd[COOKIE_SIZE];
104106
GetRandBytes(rand_pwd);
105-
std::string cookie = COOKIEAUTH_USER + ":" + HexStr(rand_pwd);
107+
conststd::string rand_pwd_hex{HexStr(rand_pwd)};
106108

107109
/** the umask determines what permissions are used to create this file -
108110
* these are set to 0077 in common/system.cpp.
109111
*/
110112
std::ofstream file;
111113
fs::path filepath_tmp = GetAuthCookieFile(true);
112114
if (filepath_tmp.empty()) {
113-
returntrue; // -norpccookiefile
115+
returnGenerateAuthCookieResult::DISABLED; // -norpccookiefile
114116
}
115117
file.open(filepath_tmp);
116118
if (!file.is_open()) {
117119
LogWarning("Unable to open cookie authentication file %s for writing", fs::PathToString(filepath_tmp));
118-
returnfalse;
120+
returnGenerateAuthCookieResult::ERR;
119121
}
120-
file << cookie;
122+
file << COOKIEAUTH_USER << ":" << rand_pwd_hex;
121123
file.close();
122124

123125
fs::path filepath = GetAuthCookieFile(false);
124126
if (!RenameOver(filepath_tmp, filepath)) {
125127
LogWarning("Unable to rename cookie authentication file %s to %s", fs::PathToString(filepath_tmp), fs::PathToString(filepath));
126-
returnfalse;
128+
returnGenerateAuthCookieResult::ERR;
127129
}
128130
if (cookie_perms) {
129131
std::error_code code;
130132
fs::permissions(filepath, cookie_perms.value(), fs::perm_options::replace, code);
131133
if (code) {
132134
LogWarning("Unable to set permissions on cookie authentication file %s", fs::PathToString(filepath));
133-
returnfalse;
135+
returnGenerateAuthCookieResult::ERR;
134136
}
135137
}
136138

137139
g_generated_cookie = true;
138140
LogInfo("Generated RPC authentication cookie %s\n", fs::PathToString(filepath));
139141
LogInfo("Permissions used for cookie: %s\n", PermsToSymbolicString(fs::status(filepath).permissions()));
140142

141-
if (cookie_out)
142-
*cookie_out = cookie;
143-
returntrue;
143+
user = COOKIEAUTH_USER;
144+
pass = rand_pwd_hex;
145+
returnGenerateAuthCookieResult::OK;
144146
}
145147

146148
boolGetAuthCookie(std::string *cookie_out)

‎src/rpc/request.h‎

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,25 @@ UniValue JSONRPCRequestObj(const std::string& strMethod, const UniValue& params,
2323
UniValue JSONRPCReplyObj(UniValue result, UniValue error, std::optional<UniValue> id, JSONRPCVersion jsonrpc_version);
2424
UniValue JSONRPCError(int code, const std::string& message);
2525

26-
/** Generate a new RPC authentication cookie and write it to disk */
27-
boolGenerateAuthCookie(std::string* cookie_out, std::optional<fs::perms> cookie_perms=std::nullopt);
26+
enumclassGenerateAuthCookieResult : uint8_t {
27+
DISABLED, // -norpccookiefile
28+
ERR,
29+
OK,
30+
};
31+
32+
/**
33+
* Generate a new RPC authentication cookie and write it to disk
34+
* @param[in] cookie_perms Filesystem permissions to use for the cookie file.
35+
* @param[out] user Generated username, only set if `OK` is returned.
36+
* @param[out] pass Generated password, only set if `OK` is returned.
37+
* @retval GenerateAuthCookieResult::DISABLED Authentication via cookie is disabled.
38+
* @retval GenerateAuthCookieResult::ERROR Error occurred, auth data could not be saved to disk.
39+
* @retval GenerateAuthCookieResult::OK Auth data was generated, saved to disk and in `user` and `pass`.
40+
*/
41+
GenerateAuthCookieResult GenerateAuthCookie(const std::optional<fs::perms>& cookie_perms,
42+
std::string& user,
43+
std::string& pass);
44+
2845
/** Read the RPC authentication cookie from disk */
2946
boolGetAuthCookie(std::string *cookie_out);
3047
/** Delete RPC authentication cookie from disk */

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit 4272966

Browse files
committed
Merge bitcoin#32423: rpc: Undeprecate rpcuser/rpcpassword, store all credentials hashed in memory
e49a727 rpc: Avoid join-split roundtrip for user:pass for auth credentials (Vasil Dimov) 98ff38a rpc: Perform HTTP user:pass split once in `RPCAuthorized` (laanwj) 879a17b rpc: Store all credentials hashed in memory (laanwj) 4ab9bed rpc: Undeprecate rpcuser/rpcpassword, change message to security warning (laanwj) Pull request description: This PR does two things: ### Undeprecate rpcuser/rpcpassword, change message to security warning Back in 2015, in bitcoin#7044, we added configuration option `rpcauth` for multiple RPC users. At the same time the old settings for single-user configuration `rpcuser` and `rpcpassword` were "soon" to be deprecated. The main reason for this deprecation is that while `rpcpassword` stores the password in plain text, `rpcauth` stores a hash, so it doesn't appear in the configuration in plain text. As the options are still in active use, actually removing them is expected to be a hassle to many, and it's not clear that is worth it. As for the security risk, in many kinds of setups (no wallet, containerized, single-user-single-application, local-only, etc) it is an unlikely point of escalation. In the end, it is good to encourage secure practices, but it is the responsibility of the user. Log a clear warning but remove the deprecation notice (this is also the only place where the options appear as deprecated, they were never marked as such in the -help output). <hr> ### Store all credentials hashed in memory This gets rid of the special-casing of `strRPCUserColonPass` by hashing cookies as well as manually provided `-rpcuser`/`-rpcpassword` with a random salt before storing them. Also take the opportunity to modernize the surrounding code a bit. There should be no end-user visible differences in behavior. <hr> Closesbitcoin#29240. ACKs for top commit: 1440000bytes: utACK bitcoin@e49a727 janb84: reACK bitcoin@e49a727 vasild: ACK e49a727 Tree-SHA512: 7162848ada4545bc07b5843d1ab6fb7e31fb26de8d6385464b7c166491cd122eac2ec5e70887c414fc136600482df8277dc0cc0541d7b7cf62c4f72e25bb6145
2 parents ff1ee10 + e49a727 commit 4272966

3 files changed

Lines changed: 75 additions & 48 deletions

File tree

‎src/httprpc.cpp‎

Lines changed: 44 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -69,8 +69,6 @@ class HTTPRPCTimerInterface : public RPCTimerInterface
6969
};
7070

7171

72-
/* Pre-base64-encoded authentication token */
73-
static std::string strRPCUserColonPass;
7472
/* Stored RPC timer interface (for unregistration) */
7573
static std::unique_ptr<HTTPRPCTimerInterface> httpRPCTimerInterface;
7674
/* List of -rpcauth values */
@@ -101,31 +99,21 @@ static void JSONErrorReply(HTTPRequest* req, UniValue objError, const JSONRPCReq
10199

102100
//This function checks username and password against -rpcauth
103101
//entries from config file.
104-
staticboolmultiUserAuthorized(std::string strUserPass)
102+
staticboolCheckUserAuthorized(std::string_view user, std::string_view pass)
105103
{
106-
if (strUserPass.find(':') == std::string::npos) {
107-
returnfalse;
108-
}
109-
std::string strUser = strUserPass.substr(0, strUserPass.find(':'));
110-
std::string strPass = strUserPass.substr(strUserPass.find(':') + 1);
111-
112-
for (constauto& vFields : g_rpcauth) {
113-
std::string strName = vFields[0];
114-
if (!TimingResistantEqual(strName, strUser)) {
104+
for (constauto& fields : g_rpcauth) {
105+
if (!TimingResistantEqual(std::string_view(fields[0]), user)) {
115106
continue;
116107
}
117108

118-
std::string strSalt = vFields[1];
119-
std::string strHash = vFields[2];
109+
conststd::string& salt = fields[1];
110+
conststd::string& hash = fields[2];
120111

121-
staticconstunsignedintKEY_SIZE = 32;
122-
unsignedchar out[KEY_SIZE];
112+
std::array<unsignedchar, CHMAC_SHA256::OUTPUT_SIZE> out;
113+
CHMAC_SHA256(UCharCast(salt.data()), salt.size()).Write(UCharCast(pass.data()), pass.size()).Finalize(out.data());
114+
std::string hash_from_pass = HexStr(out);
123115

124-
CHMAC_SHA256(reinterpret_cast<constunsignedchar*>(strSalt.data()), strSalt.size()).Write(reinterpret_cast<constunsignedchar*>(strPass.data()), strPass.size()).Finalize(out);
125-
std::vector<unsignedchar> hexvec(out, out+KEY_SIZE);
126-
std::string strHashFromPass = HexStr(hexvec);
127-
128-
if (TimingResistantEqual(strHashFromPass, strHash)) {
116+
if (TimingResistantEqual(hash_from_pass, hash)) {
129117
returntrue;
130118
}
131119
}
@@ -142,15 +130,14 @@ static bool RPCAuthorized(const std::string& strAuth, std::string& strAuthUserna
142130
if (!userpass_data) returnfalse;
143131
strUserPass.assign(userpass_data->begin(), userpass_data->end());
144132

145-
if (strUserPass.find(':') != std::string::npos)
146-
strAuthUsernameOut = strUserPass.substr(0, strUserPass.find(':'));
147-
148-
// Check if authorized under single-user field.
149-
// (strRPCUserColonPass is empty when -norpccookiefile is specified).
150-
if (!strRPCUserColonPass.empty() && TimingResistantEqual(strUserPass, strRPCUserColonPass)) {
151-
returntrue;
133+
size_t colon_pos = strUserPass.find(':');
134+
if (colon_pos == std::string::npos) {
135+
returnfalse; // Invalid basic auth.
152136
}
153-
returnmultiUserAuthorized(strUserPass);
137+
std::string user = strUserPass.substr(0, colon_pos);
138+
std::string pass = strUserPass.substr(colon_pos + 1);
139+
strAuthUsernameOut = user;
140+
returnCheckUserAuthorized(user, pass);
154141
}
155142

156143
staticboolHTTPReq_JSONRPC(const std::any& context, HTTPRequest* req)
@@ -291,6 +278,9 @@ static bool HTTPReq_JSONRPC(const std::any& context, HTTPRequest* req)
291278

292279
staticboolInitRPCAuthentication()
293280
{
281+
std::string user;
282+
std::string pass;
283+
294284
if (gArgs.GetArg("-rpcpassword", "") == "")
295285
{
296286
std::optional<fs::perms> cookie_perms{std::nullopt};
@@ -304,18 +294,36 @@ static bool InitRPCAuthentication()
304294
cookie_perms = *perm_opt;
305295
}
306296

307-
assert(strRPCUserColonPass.empty()); // Only support initializing once
308-
if (!GenerateAuthCookie(&strRPCUserColonPass, cookie_perms)) {
297+
switch (GenerateAuthCookie(cookie_perms, user, pass)) {
298+
case GenerateAuthCookieResult::ERR:
309299
returnfalse;
310-
}
311-
if (strRPCUserColonPass.empty()) {
300+
case GenerateAuthCookieResult::DISABLED:
312301
LogInfo("RPC authentication cookie file generation is disabled.");
313-
} else {
302+
break;
303+
case GenerateAuthCookieResult::OK:
314304
LogInfo("Using random cookie authentication.");
305+
break;
315306
}
316307
} else {
317-
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");
318-
strRPCUserColonPass = gArgs.GetArg("-rpcuser", "") + ":" + gArgs.GetArg("-rpcpassword", "");
308+
LogInfo("Using rpcuser/rpcpassword authentication.");
309+
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+
user = gArgs.GetArg("-rpcuser", "");
311+
pass = gArgs.GetArg("-rpcpassword", "");
312+
}
313+
314+
// If there is a plaintext credential, hash it with a random salt before storage.
315+
if (!user.empty() || !pass.empty()) {
316+
// Generate a random 16 byte hex salt.
317+
std::array<unsignedchar, 16> raw_salt;
318+
GetStrongRandBytes(raw_salt);
319+
std::string salt = HexStr(raw_salt);
320+
321+
// Compute HMAC.
322+
std::array<unsignedchar, CHMAC_SHA256::OUTPUT_SIZE> out;
323+
CHMAC_SHA256(UCharCast(salt.data()), salt.size()).Write(UCharCast(pass.data()), pass.size()).Finalize(out.data());
324+
std::string hash = HexStr(out);
325+
326+
g_rpcauth.push_back({user, salt, hash});
319327
}
320328

321329
if (!gArgs.GetArgs("-rpcauth").empty()) {

‎src/rpc/request.cpp‎

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -97,50 +97,52 @@ static fs::path GetAuthCookieFile(bool temp=false)
9797

9898
staticbool g_generated_cookie = false;
9999

100-
boolGenerateAuthCookie(std::string* cookie_out, std::optional<fs::perms> cookie_perms)
100+
GenerateAuthCookieResult GenerateAuthCookie(const std::optional<fs::perms>& cookie_perms,
101+
std::string& user,
102+
std::string& pass)
101103
{
102104
constsize_tCOOKIE_SIZE = 32;
103105
unsignedchar rand_pwd[COOKIE_SIZE];
104106
GetRandBytes(rand_pwd);
105-
std::string cookie = COOKIEAUTH_USER + ":" + HexStr(rand_pwd);
107+
conststd::string rand_pwd_hex{HexStr(rand_pwd)};
106108

107109
/** the umask determines what permissions are used to create this file -
108110
* these are set to 0077 in common/system.cpp.
109111
*/
110112
std::ofstream file;
111113
fs::path filepath_tmp = GetAuthCookieFile(true);
112114
if (filepath_tmp.empty()) {
113-
returntrue; // -norpccookiefile
115+
returnGenerateAuthCookieResult::DISABLED; // -norpccookiefile
114116
}
115117
file.open(filepath_tmp);
116118
if (!file.is_open()) {
117119
LogWarning("Unable to open cookie authentication file %s for writing", fs::PathToString(filepath_tmp));
118-
returnfalse;
120+
returnGenerateAuthCookieResult::ERR;
119121
}
120-
file << cookie;
122+
file << COOKIEAUTH_USER << ":" << rand_pwd_hex;
121123
file.close();
122124

123125
fs::path filepath = GetAuthCookieFile(false);
124126
if (!RenameOver(filepath_tmp, filepath)) {
125127
LogWarning("Unable to rename cookie authentication file %s to %s", fs::PathToString(filepath_tmp), fs::PathToString(filepath));
126-
returnfalse;
128+
returnGenerateAuthCookieResult::ERR;
127129
}
128130
if (cookie_perms) {
129131
std::error_code code;
130132
fs::permissions(filepath, cookie_perms.value(), fs::perm_options::replace, code);
131133
if (code) {
132134
LogWarning("Unable to set permissions on cookie authentication file %s", fs::PathToString(filepath));
133-
returnfalse;
135+
returnGenerateAuthCookieResult::ERR;
134136
}
135137
}
136138

137139
g_generated_cookie = true;
138140
LogInfo("Generated RPC authentication cookie %s\n", fs::PathToString(filepath));
139141
LogInfo("Permissions used for cookie: %s\n", PermsToSymbolicString(fs::status(filepath).permissions()));
140142

141-
if (cookie_out)
142-
*cookie_out = cookie;
143-
returntrue;
143+
user = COOKIEAUTH_USER;
144+
pass = rand_pwd_hex;
145+
returnGenerateAuthCookieResult::OK;
144146
}
145147

146148
boolGetAuthCookie(std::string *cookie_out)

‎src/rpc/request.h‎

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,25 @@ UniValue JSONRPCRequestObj(const std::string& strMethod, const UniValue& params,
2323
UniValue JSONRPCReplyObj(UniValue result, UniValue error, std::optional<UniValue> id, JSONRPCVersion jsonrpc_version);
2424
UniValue JSONRPCError(int code, const std::string& message);
2525

26-
/** Generate a new RPC authentication cookie and write it to disk */
27-
boolGenerateAuthCookie(std::string* cookie_out, std::optional<fs::perms> cookie_perms=std::nullopt);
26+
enumclassGenerateAuthCookieResult : uint8_t {
27+
DISABLED, // -norpccookiefile
28+
ERR,
29+
OK,
30+
};
31+
32+
/**
33+
* Generate a new RPC authentication cookie and write it to disk
34+
* @param[in] cookie_perms Filesystem permissions to use for the cookie file.
35+
* @param[out] user Generated username, only set if `OK` is returned.
36+
* @param[out] pass Generated password, only set if `OK` is returned.
37+
* @retval GenerateAuthCookieResult::DISABLED Authentication via cookie is disabled.
38+
* @retval GenerateAuthCookieResult::ERROR Error occurred, auth data could not be saved to disk.
39+
* @retval GenerateAuthCookieResult::OK Auth data was generated, saved to disk and in `user` and `pass`.
40+
*/
41+
GenerateAuthCookieResult GenerateAuthCookie(const std::optional<fs::perms>& cookie_perms,
42+
std::string& user,
43+
std::string& pass);
44+
2845
/** Read the RPC authentication cookie from disk */
2946
boolGetAuthCookie(std::string *cookie_out);
3047
/** Delete RPC authentication cookie from disk */

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit 4272966

Browse files
committed
Merge bitcoin#32423: rpc: Undeprecate rpcuser/rpcpassword, store all credentials hashed in memory
e49a727 rpc: Avoid join-split roundtrip for user:pass for auth credentials (Vasil Dimov) 98ff38a rpc: Perform HTTP user:pass split once in `RPCAuthorized` (laanwj) 879a17b rpc: Store all credentials hashed in memory (laanwj) 4ab9bed rpc: Undeprecate rpcuser/rpcpassword, change message to security warning (laanwj) Pull request description: This PR does two things: ### Undeprecate rpcuser/rpcpassword, change message to security warning Back in 2015, in bitcoin#7044, we added configuration option `rpcauth` for multiple RPC users. At the same time the old settings for single-user configuration `rpcuser` and `rpcpassword` were "soon" to be deprecated. The main reason for this deprecation is that while `rpcpassword` stores the password in plain text, `rpcauth` stores a hash, so it doesn't appear in the configuration in plain text. As the options are still in active use, actually removing them is expected to be a hassle to many, and it's not clear that is worth it. As for the security risk, in many kinds of setups (no wallet, containerized, single-user-single-application, local-only, etc) it is an unlikely point of escalation. In the end, it is good to encourage secure practices, but it is the responsibility of the user. Log a clear warning but remove the deprecation notice (this is also the only place where the options appear as deprecated, they were never marked as such in the -help output). <hr> ### Store all credentials hashed in memory This gets rid of the special-casing of `strRPCUserColonPass` by hashing cookies as well as manually provided `-rpcuser`/`-rpcpassword` with a random salt before storing them. Also take the opportunity to modernize the surrounding code a bit. There should be no end-user visible differences in behavior. <hr> Closesbitcoin#29240. ACKs for top commit: 1440000bytes: utACK bitcoin@e49a727 janb84: reACK bitcoin@e49a727 vasild: ACK e49a727 Tree-SHA512: 7162848ada4545bc07b5843d1ab6fb7e31fb26de8d6385464b7c166491cd122eac2ec5e70887c414fc136600482df8277dc0cc0541d7b7cf62c4f72e25bb6145
2 parents ff1ee10 + e49a727 commit 4272966

3 files changed

Lines changed: 75 additions & 48 deletions

File tree

‎src/httprpc.cpp‎

Lines changed: 44 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -69,8 +69,6 @@ class HTTPRPCTimerInterface : public RPCTimerInterface
6969
};
7070

7171

72-
/* Pre-base64-encoded authentication token */
73-
static std::string strRPCUserColonPass;
7472
/* Stored RPC timer interface (for unregistration) */
7573
static std::unique_ptr<HTTPRPCTimerInterface> httpRPCTimerInterface;
7674
/* List of -rpcauth values */
@@ -101,31 +99,21 @@ static void JSONErrorReply(HTTPRequest* req, UniValue objError, const JSONRPCReq
10199

102100
//This function checks username and password against -rpcauth
103101
//entries from config file.
104-
staticboolmultiUserAuthorized(std::string strUserPass)
102+
staticboolCheckUserAuthorized(std::string_view user, std::string_view pass)
105103
{
106-
if (strUserPass.find(':') == std::string::npos) {
107-
returnfalse;
108-
}
109-
std::string strUser = strUserPass.substr(0, strUserPass.find(':'));
110-
std::string strPass = strUserPass.substr(strUserPass.find(':') + 1);
111-
112-
for (constauto& vFields : g_rpcauth) {
113-
std::string strName = vFields[0];
114-
if (!TimingResistantEqual(strName, strUser)) {
104+
for (constauto& fields : g_rpcauth) {
105+
if (!TimingResistantEqual(std::string_view(fields[0]), user)) {
115106
continue;
116107
}
117108

118-
std::string strSalt = vFields[1];
119-
std::string strHash = vFields[2];
109+
conststd::string& salt = fields[1];
110+
conststd::string& hash = fields[2];
120111

121-
staticconstunsignedintKEY_SIZE = 32;
122-
unsignedchar out[KEY_SIZE];
112+
std::array<unsignedchar, CHMAC_SHA256::OUTPUT_SIZE> out;
113+
CHMAC_SHA256(UCharCast(salt.data()), salt.size()).Write(UCharCast(pass.data()), pass.size()).Finalize(out.data());
114+
std::string hash_from_pass = HexStr(out);
123115

124-
CHMAC_SHA256(reinterpret_cast<constunsignedchar*>(strSalt.data()), strSalt.size()).Write(reinterpret_cast<constunsignedchar*>(strPass.data()), strPass.size()).Finalize(out);
125-
std::vector<unsignedchar> hexvec(out, out+KEY_SIZE);
126-
std::string strHashFromPass = HexStr(hexvec);
127-
128-
if (TimingResistantEqual(strHashFromPass, strHash)) {
116+
if (TimingResistantEqual(hash_from_pass, hash)) {
129117
returntrue;
130118
}
131119
}
@@ -142,15 +130,14 @@ static bool RPCAuthorized(const std::string& strAuth, std::string& strAuthUserna
142130
if (!userpass_data) returnfalse;
143131
strUserPass.assign(userpass_data->begin(), userpass_data->end());
144132

145-
if (strUserPass.find(':') != std::string::npos)
146-
strAuthUsernameOut = strUserPass.substr(0, strUserPass.find(':'));
147-
148-
// Check if authorized under single-user field.
149-
// (strRPCUserColonPass is empty when -norpccookiefile is specified).
150-
if (!strRPCUserColonPass.empty() && TimingResistantEqual(strUserPass, strRPCUserColonPass)) {
151-
returntrue;
133+
size_t colon_pos = strUserPass.find(':');
134+
if (colon_pos == std::string::npos) {
135+
returnfalse; // Invalid basic auth.
152136
}
153-
returnmultiUserAuthorized(strUserPass);
137+
std::string user = strUserPass.substr(0, colon_pos);
138+
std::string pass = strUserPass.substr(colon_pos + 1);
139+
strAuthUsernameOut = user;
140+
returnCheckUserAuthorized(user, pass);
154141
}
155142

156143
staticboolHTTPReq_JSONRPC(const std::any& context, HTTPRequest* req)
@@ -291,6 +278,9 @@ static bool HTTPReq_JSONRPC(const std::any& context, HTTPRequest* req)
291278

292279
staticboolInitRPCAuthentication()
293280
{
281+
std::string user;
282+
std::string pass;
283+
294284
if (gArgs.GetArg("-rpcpassword", "") == "")
295285
{
296286
std::optional<fs::perms> cookie_perms{std::nullopt};
@@ -304,18 +294,36 @@ static bool InitRPCAuthentication()
304294
cookie_perms = *perm_opt;
305295
}
306296

307-
assert(strRPCUserColonPass.empty()); // Only support initializing once
308-
if (!GenerateAuthCookie(&strRPCUserColonPass, cookie_perms)) {
297+
switch (GenerateAuthCookie(cookie_perms, user, pass)) {
298+
case GenerateAuthCookieResult::ERR:
309299
returnfalse;
310-
}
311-
if (strRPCUserColonPass.empty()) {
300+
case GenerateAuthCookieResult::DISABLED:
312301
LogInfo("RPC authentication cookie file generation is disabled.");
313-
} else {
302+
break;
303+
case GenerateAuthCookieResult::OK:
314304
LogInfo("Using random cookie authentication.");
305+
break;
315306
}
316307
} else {
317-
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");
318-
strRPCUserColonPass = gArgs.GetArg("-rpcuser", "") + ":" + gArgs.GetArg("-rpcpassword", "");
308+
LogInfo("Using rpcuser/rpcpassword authentication.");
309+
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+
user = gArgs.GetArg("-rpcuser", "");
311+
pass = gArgs.GetArg("-rpcpassword", "");
312+
}
313+
314+
// If there is a plaintext credential, hash it with a random salt before storage.
315+
if (!user.empty() || !pass.empty()) {
316+
// Generate a random 16 byte hex salt.
317+
std::array<unsignedchar, 16> raw_salt;
318+
GetStrongRandBytes(raw_salt);
319+
std::string salt = HexStr(raw_salt);
320+
321+
// Compute HMAC.
322+
std::array<unsignedchar, CHMAC_SHA256::OUTPUT_SIZE> out;
323+
CHMAC_SHA256(UCharCast(salt.data()), salt.size()).Write(UCharCast(pass.data()), pass.size()).Finalize(out.data());
324+
std::string hash = HexStr(out);
325+
326+
g_rpcauth.push_back({user, salt, hash});
319327
}
320328

321329
if (!gArgs.GetArgs("-rpcauth").empty()) {

‎src/rpc/request.cpp‎

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -97,50 +97,52 @@ static fs::path GetAuthCookieFile(bool temp=false)
9797

9898
staticbool g_generated_cookie = false;
9999

100-
boolGenerateAuthCookie(std::string* cookie_out, std::optional<fs::perms> cookie_perms)
100+
GenerateAuthCookieResult GenerateAuthCookie(const std::optional<fs::perms>& cookie_perms,
101+
std::string& user,
102+
std::string& pass)
101103
{
102104
constsize_tCOOKIE_SIZE = 32;
103105
unsignedchar rand_pwd[COOKIE_SIZE];
104106
GetRandBytes(rand_pwd);
105-
std::string cookie = COOKIEAUTH_USER + ":" + HexStr(rand_pwd);
107+
conststd::string rand_pwd_hex{HexStr(rand_pwd)};
106108

107109
/** the umask determines what permissions are used to create this file -
108110
* these are set to 0077 in common/system.cpp.
109111
*/
110112
std::ofstream file;
111113
fs::path filepath_tmp = GetAuthCookieFile(true);
112114
if (filepath_tmp.empty()) {
113-
returntrue; // -norpccookiefile
115+
returnGenerateAuthCookieResult::DISABLED; // -norpccookiefile
114116
}
115117
file.open(filepath_tmp);
116118
if (!file.is_open()) {
117119
LogWarning("Unable to open cookie authentication file %s for writing", fs::PathToString(filepath_tmp));
118-
returnfalse;
120+
returnGenerateAuthCookieResult::ERR;
119121
}
120-
file << cookie;
122+
file << COOKIEAUTH_USER << ":" << rand_pwd_hex;
121123
file.close();
122124

123125
fs::path filepath = GetAuthCookieFile(false);
124126
if (!RenameOver(filepath_tmp, filepath)) {
125127
LogWarning("Unable to rename cookie authentication file %s to %s", fs::PathToString(filepath_tmp), fs::PathToString(filepath));
126-
returnfalse;
128+
returnGenerateAuthCookieResult::ERR;
127129
}
128130
if (cookie_perms) {
129131
std::error_code code;
130132
fs::permissions(filepath, cookie_perms.value(), fs::perm_options::replace, code);
131133
if (code) {
132134
LogWarning("Unable to set permissions on cookie authentication file %s", fs::PathToString(filepath));
133-
returnfalse;
135+
returnGenerateAuthCookieResult::ERR;
134136
}
135137
}
136138

137139
g_generated_cookie = true;
138140
LogInfo("Generated RPC authentication cookie %s\n", fs::PathToString(filepath));
139141
LogInfo("Permissions used for cookie: %s\n", PermsToSymbolicString(fs::status(filepath).permissions()));
140142

141-
if (cookie_out)
142-
*cookie_out = cookie;
143-
returntrue;
143+
user = COOKIEAUTH_USER;
144+
pass = rand_pwd_hex;
145+
returnGenerateAuthCookieResult::OK;
144146
}
145147

146148
boolGetAuthCookie(std::string *cookie_out)

‎src/rpc/request.h‎

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,25 @@ UniValue JSONRPCRequestObj(const std::string& strMethod, const UniValue& params,
2323
UniValue JSONRPCReplyObj(UniValue result, UniValue error, std::optional<UniValue> id, JSONRPCVersion jsonrpc_version);
2424
UniValue JSONRPCError(int code, const std::string& message);
2525

26-
/** Generate a new RPC authentication cookie and write it to disk */
27-
boolGenerateAuthCookie(std::string* cookie_out, std::optional<fs::perms> cookie_perms=std::nullopt);
26+
enumclassGenerateAuthCookieResult : uint8_t {
27+
DISABLED, // -norpccookiefile
28+
ERR,
29+
OK,
30+
};
31+
32+
/**
33+
* Generate a new RPC authentication cookie and write it to disk
34+
* @param[in] cookie_perms Filesystem permissions to use for the cookie file.
35+
* @param[out] user Generated username, only set if `OK` is returned.
36+
* @param[out] pass Generated password, only set if `OK` is returned.
37+
* @retval GenerateAuthCookieResult::DISABLED Authentication via cookie is disabled.
38+
* @retval GenerateAuthCookieResult::ERROR Error occurred, auth data could not be saved to disk.
39+
* @retval GenerateAuthCookieResult::OK Auth data was generated, saved to disk and in `user` and `pass`.
40+
*/
41+
GenerateAuthCookieResult GenerateAuthCookie(const std::optional<fs::perms>& cookie_perms,
42+
std::string& user,
43+
std::string& pass);
44+
2845
/** Read the RPC authentication cookie from disk */
2946
boolGetAuthCookie(std::string *cookie_out);
3047
/** Delete RPC authentication cookie from disk */

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Commit 4272966

Browse files
committed
Merge bitcoin#32423: rpc: Undeprecate rpcuser/rpcpassword, store all credentials hashed in memory
e49a727 rpc: Avoid join-split roundtrip for user:pass for auth credentials (Vasil Dimov) 98ff38a rpc: Perform HTTP user:pass split once in `RPCAuthorized` (laanwj) 879a17b rpc: Store all credentials hashed in memory (laanwj) 4ab9bed rpc: Undeprecate rpcuser/rpcpassword, change message to security warning (laanwj) Pull request description: This PR does two things: ### Undeprecate rpcuser/rpcpassword, change message to security warning Back in 2015, in bitcoin#7044, we added configuration option `rpcauth` for multiple RPC users. At the same time the old settings for single-user configuration `rpcuser` and `rpcpassword` were "soon" to be deprecated. The main reason for this deprecation is that while `rpcpassword` stores the password in plain text, `rpcauth` stores a hash, so it doesn't appear in the configuration in plain text. As the options are still in active use, actually removing them is expected to be a hassle to many, and it's not clear that is worth it. As for the security risk, in many kinds of setups (no wallet, containerized, single-user-single-application, local-only, etc) it is an unlikely point of escalation. In the end, it is good to encourage secure practices, but it is the responsibility of the user. Log a clear warning but remove the deprecation notice (this is also the only place where the options appear as deprecated, they were never marked as such in the -help output). <hr> ### Store all credentials hashed in memory This gets rid of the special-casing of `strRPCUserColonPass` by hashing cookies as well as manually provided `-rpcuser`/`-rpcpassword` with a random salt before storing them. Also take the opportunity to modernize the surrounding code a bit. There should be no end-user visible differences in behavior. <hr> Closesbitcoin#29240. ACKs for top commit: 1440000bytes: utACK bitcoin@e49a727 janb84: reACK bitcoin@e49a727 vasild: ACK e49a727 Tree-SHA512: 7162848ada4545bc07b5843d1ab6fb7e31fb26de8d6385464b7c166491cd122eac2ec5e70887c414fc136600482df8277dc0cc0541d7b7cf62c4f72e25bb6145
2 parents ff1ee10 + e49a727 commit 4272966

3 files changed

Lines changed: 75 additions & 48 deletions

File tree

‎src/httprpc.cpp‎

Lines changed: 44 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -69,8 +69,6 @@ class HTTPRPCTimerInterface : public RPCTimerInterface
6969
};
7070

7171

72-
/* Pre-base64-encoded authentication token */
73-
static std::string strRPCUserColonPass;
7472
/* Stored RPC timer interface (for unregistration) */
7573
static std::unique_ptr<HTTPRPCTimerInterface> httpRPCTimerInterface;
7674
/* List of -rpcauth values */
@@ -101,31 +99,21 @@ static void JSONErrorReply(HTTPRequest* req, UniValue objError, const JSONRPCReq
10199

102100
//This function checks username and password against -rpcauth
103101
//entries from config file.
104-
staticboolmultiUserAuthorized(std::string strUserPass)
102+
staticboolCheckUserAuthorized(std::string_view user, std::string_view pass)
105103
{
106-
if (strUserPass.find(':') == std::string::npos) {
107-
returnfalse;
108-
}
109-
std::string strUser = strUserPass.substr(0, strUserPass.find(':'));
110-
std::string strPass = strUserPass.substr(strUserPass.find(':') + 1);
111-
112-
for (constauto& vFields : g_rpcauth) {
113-
std::string strName = vFields[0];
114-
if (!TimingResistantEqual(strName, strUser)) {
104+
for (constauto& fields : g_rpcauth) {
105+
if (!TimingResistantEqual(std::string_view(fields[0]), user)) {
115106
continue;
116107
}
117108

118-
std::string strSalt = vFields[1];
119-
std::string strHash = vFields[2];
109+
conststd::string& salt = fields[1];
110+
conststd::string& hash = fields[2];
120111

121-
staticconstunsignedintKEY_SIZE = 32;
122-
unsignedchar out[KEY_SIZE];
112+
std::array<unsignedchar, CHMAC_SHA256::OUTPUT_SIZE> out;
113+
CHMAC_SHA256(UCharCast(salt.data()), salt.size()).Write(UCharCast(pass.data()), pass.size()).Finalize(out.data());
114+
std::string hash_from_pass = HexStr(out);
123115

124-
CHMAC_SHA256(reinterpret_cast<constunsignedchar*>(strSalt.data()), strSalt.size()).Write(reinterpret_cast<constunsignedchar*>(strPass.data()), strPass.size()).Finalize(out);
125-
std::vector<unsignedchar> hexvec(out, out+KEY_SIZE);
126-
std::string strHashFromPass = HexStr(hexvec);
127-
128-
if (TimingResistantEqual(strHashFromPass, strHash)) {
116+
if (TimingResistantEqual(hash_from_pass, hash)) {
129117
returntrue;
130118
}
131119
}
@@ -142,15 +130,14 @@ static bool RPCAuthorized(const std::string& strAuth, std::string& strAuthUserna
142130
if (!userpass_data) returnfalse;
143131
strUserPass.assign(userpass_data->begin(), userpass_data->end());
144132

145-
if (strUserPass.find(':') != std::string::npos)
146-
strAuthUsernameOut = strUserPass.substr(0, strUserPass.find(':'));
147-
148-
// Check if authorized under single-user field.
149-
// (strRPCUserColonPass is empty when -norpccookiefile is specified).
150-
if (!strRPCUserColonPass.empty() && TimingResistantEqual(strUserPass, strRPCUserColonPass)) {
151-
returntrue;
133+
size_t colon_pos = strUserPass.find(':');
134+
if (colon_pos == std::string::npos) {
135+
returnfalse; // Invalid basic auth.
152136
}
153-
returnmultiUserAuthorized(strUserPass);
137+
std::string user = strUserPass.substr(0, colon_pos);
138+
std::string pass = strUserPass.substr(colon_pos + 1);
139+
strAuthUsernameOut = user;
140+
returnCheckUserAuthorized(user, pass);
154141
}
155142

156143
staticboolHTTPReq_JSONRPC(const std::any& context, HTTPRequest* req)
@@ -291,6 +278,9 @@ static bool HTTPReq_JSONRPC(const std::any& context, HTTPRequest* req)
291278

292279
staticboolInitRPCAuthentication()
293280
{
281+
std::string user;
282+
std::string pass;
283+
294284
if (gArgs.GetArg("-rpcpassword", "") == "")
295285
{
296286
std::optional<fs::perms> cookie_perms{std::nullopt};
@@ -304,18 +294,36 @@ static bool InitRPCAuthentication()
304294
cookie_perms = *perm_opt;
305295
}
306296

307-
assert(strRPCUserColonPass.empty()); // Only support initializing once
308-
if (!GenerateAuthCookie(&strRPCUserColonPass, cookie_perms)) {
297+
switch (GenerateAuthCookie(cookie_perms, user, pass)) {
298+
case GenerateAuthCookieResult::ERR:
309299
returnfalse;
310-
}
311-
if (strRPCUserColonPass.empty()) {
300+
case GenerateAuthCookieResult::DISABLED:
312301
LogInfo("RPC authentication cookie file generation is disabled.");
313-
} else {
302+
break;
303+
case GenerateAuthCookieResult::OK:
314304
LogInfo("Using random cookie authentication.");
305+
break;
315306
}
316307
} else {
317-
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");
318-
strRPCUserColonPass = gArgs.GetArg("-rpcuser", "") + ":" + gArgs.GetArg("-rpcpassword", "");
308+
LogInfo("Using rpcuser/rpcpassword authentication.");
309+
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+
user = gArgs.GetArg("-rpcuser", "");
311+
pass = gArgs.GetArg("-rpcpassword", "");
312+
}
313+
314+
// If there is a plaintext credential, hash it with a random salt before storage.
315+
if (!user.empty() || !pass.empty()) {
316+
// Generate a random 16 byte hex salt.
317+
std::array<unsignedchar, 16> raw_salt;
318+
GetStrongRandBytes(raw_salt);
319+
std::string salt = HexStr(raw_salt);
320+
321+
// Compute HMAC.
322+
std::array<unsignedchar, CHMAC_SHA256::OUTPUT_SIZE> out;
323+
CHMAC_SHA256(UCharCast(salt.data()), salt.size()).Write(UCharCast(pass.data()), pass.size()).Finalize(out.data());
324+
std::string hash = HexStr(out);
325+
326+
g_rpcauth.push_back({user, salt, hash});
319327
}
320328

321329
if (!gArgs.GetArgs("-rpcauth").empty()) {

‎src/rpc/request.cpp‎

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -97,50 +97,52 @@ static fs::path GetAuthCookieFile(bool temp=false)
9797

9898
staticbool g_generated_cookie = false;
9999

100-
boolGenerateAuthCookie(std::string* cookie_out, std::optional<fs::perms> cookie_perms)
100+
GenerateAuthCookieResult GenerateAuthCookie(const std::optional<fs::perms>& cookie_perms,
101+
std::string& user,
102+
std::string& pass)
101103
{
102104
constsize_tCOOKIE_SIZE = 32;
103105
unsignedchar rand_pwd[COOKIE_SIZE];
104106
GetRandBytes(rand_pwd);
105-
std::string cookie = COOKIEAUTH_USER + ":" + HexStr(rand_pwd);
107+
conststd::string rand_pwd_hex{HexStr(rand_pwd)};
106108

107109
/** the umask determines what permissions are used to create this file -
108110
* these are set to 0077 in common/system.cpp.
109111
*/
110112
std::ofstream file;
111113
fs::path filepath_tmp = GetAuthCookieFile(true);
112114
if (filepath_tmp.empty()) {
113-
returntrue; // -norpccookiefile
115+
returnGenerateAuthCookieResult::DISABLED; // -norpccookiefile
114116
}
115117
file.open(filepath_tmp);
116118
if (!file.is_open()) {
117119
LogWarning("Unable to open cookie authentication file %s for writing", fs::PathToString(filepath_tmp));
118-
returnfalse;
120+
returnGenerateAuthCookieResult::ERR;
119121
}
120-
file << cookie;
122+
file << COOKIEAUTH_USER << ":" << rand_pwd_hex;
121123
file.close();
122124

123125
fs::path filepath = GetAuthCookieFile(false);
124126
if (!RenameOver(filepath_tmp, filepath)) {
125127
LogWarning("Unable to rename cookie authentication file %s to %s", fs::PathToString(filepath_tmp), fs::PathToString(filepath));
126-
returnfalse;
128+
returnGenerateAuthCookieResult::ERR;
127129
}
128130
if (cookie_perms) {
129131
std::error_code code;
130132
fs::permissions(filepath, cookie_perms.value(), fs::perm_options::replace, code);
131133
if (code) {
132134
LogWarning("Unable to set permissions on cookie authentication file %s", fs::PathToString(filepath));
133-
returnfalse;
135+
returnGenerateAuthCookieResult::ERR;
134136
}
135137
}
136138

137139
g_generated_cookie = true;
138140
LogInfo("Generated RPC authentication cookie %s\n", fs::PathToString(filepath));
139141
LogInfo("Permissions used for cookie: %s\n", PermsToSymbolicString(fs::status(filepath).permissions()));
140142

141-
if (cookie_out)
142-
*cookie_out = cookie;
143-
returntrue;
143+
user = COOKIEAUTH_USER;
144+
pass = rand_pwd_hex;
145+
returnGenerateAuthCookieResult::OK;
144146
}
145147

146148
boolGetAuthCookie(std::string *cookie_out)

‎src/rpc/request.h‎

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,25 @@ UniValue JSONRPCRequestObj(const std::string& strMethod, const UniValue& params,
2323
UniValue JSONRPCReplyObj(UniValue result, UniValue error, std::optional<UniValue> id, JSONRPCVersion jsonrpc_version);
2424
UniValue JSONRPCError(int code, const std::string& message);
2525

26-
/** Generate a new RPC authentication cookie and write it to disk */
27-
boolGenerateAuthCookie(std::string* cookie_out, std::optional<fs::perms> cookie_perms=std::nullopt);
26+
enumclassGenerateAuthCookieResult : uint8_t {
27+
DISABLED, // -norpccookiefile
28+
ERR,
29+
OK,
30+
};
31+
32+
/**
33+
* Generate a new RPC authentication cookie and write it to disk
34+
* @param[in] cookie_perms Filesystem permissions to use for the cookie file.
35+
* @param[out] user Generated username, only set if `OK` is returned.
36+
* @param[out] pass Generated password, only set if `OK` is returned.
37+
* @retval GenerateAuthCookieResult::DISABLED Authentication via cookie is disabled.
38+
* @retval GenerateAuthCookieResult::ERROR Error occurred, auth data could not be saved to disk.
39+
* @retval GenerateAuthCookieResult::OK Auth data was generated, saved to disk and in `user` and `pass`.
40+
*/
41+
GenerateAuthCookieResult GenerateAuthCookie(const std::optional<fs::perms>& cookie_perms,
42+
std::string& user,
43+
std::string& pass);
44+
2845
/** Read the RPC authentication cookie from disk */
2946
boolGetAuthCookie(std::string *cookie_out);
3047
/** Delete RPC authentication cookie from disk */

0 commit comments

Comments
 (0)