diff --git a/Cargo.lock b/Cargo.lock index 58a34da8dd..17df68abb8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1203,7 +1203,7 @@ checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" [[package]] name = "sv1_api" -version = "7.0.0" +version = "7.0.1" dependencies = [ "binary_sv2", "bitcoin", diff --git a/fuzz/Cargo.lock b/fuzz/Cargo.lock index 79d118bb53..3840f93d77 100644 --- a/fuzz/Cargo.lock +++ b/fuzz/Cargo.lock @@ -559,7 +559,7 @@ checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" [[package]] name = "sv1_api" -version = "7.0.0" +version = "7.0.1" dependencies = [ "binary_sv2", "bitcoin", diff --git a/sv1/Cargo.toml b/sv1/Cargo.toml index 33b1b3233c..a91e0c7435 100644 --- a/sv1/Cargo.toml +++ b/sv1/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "sv1_api" -version = "7.0.0" +version = "7.0.1" authors = ["The Stratum V2 Developers"] edition = "2021" readme = "README.md" diff --git a/sv1/src/json_rpc.rs b/sv1/src/json_rpc.rs index 7400b8fe08..1742e91534 100644 --- a/sv1/src/json_rpc.rs +++ b/sv1/src/json_rpc.rs @@ -1,6 +1,7 @@ //! https://www.jsonrpc.org/specification#response_object use serde::{Deserialize, Deserializer, Serialize, Serializer}; -use std::{fmt, fmt::Display}; +use serde_json::Value; +use std::{borrow::Cow, fmt, fmt::Display}; #[derive(Clone, Serialize, Debug)] #[serde(untagged)] @@ -55,17 +56,85 @@ impl Display for Message { } } -#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq)] +/// Printed in place of credentials a peer sent. +pub(crate) const REDACTED: &str = ""; + +/// Formats as [`REDACTED`], for `Debug` impls of fields that hold credentials. +pub(crate) struct Redacted; + +impl fmt::Debug for Redacted { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(REDACTED) + } +} + +/// Returns `params` with the credentials a request for `method` can carry replaced by +/// [`REDACTED`], so that they never reach formatted output. +/// +/// Those are everything but the worker name in `mining.authorize`, and `info.connection-url` in +/// `mining.configure`, which can embed `user:password@`. +pub(crate) fn redact_params<'a>(method: &str, params: &'a Value) -> Cow<'a, Value> { + match method { + "mining.authorize" => Cow::Owned(match params.as_array() { + Some(params) => params + .iter() + .enumerate() + .map(|(i, param)| { + if i == 0 { + param.clone() + } else { + REDACTED.into() + } + }) + .collect(), + None => REDACTED.into(), + }), + "mining.configure" => { + let mut params = params.clone(); + redact_connection_url(&mut params); + Cow::Owned(params) + } + _ => Cow::Borrowed(params), + } +} + +fn redact_connection_url(value: &mut Value) { + match value { + Value::Array(values) => values.iter_mut().for_each(redact_connection_url), + Value::Object(fields) => { + for (key, value) in fields.iter_mut() { + if key == "info.connection-url" { + *value = REDACTED.into(); + } else { + redact_connection_url(value); + } + } + } + _ => {} + } +} + +#[derive(Clone, Serialize, Deserialize, PartialEq, Eq)] pub struct StandardRequest { pub id: u64, pub method: String, pub params: serde_json::Value, } +impl fmt::Debug for StandardRequest { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("StandardRequest") + .field("id", &self.id) + .field("method", &self.method) + .field("params", &redact_params(&self.method, &self.params)) + .finish() + } +} + impl fmt::Display for StandardRequest { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let params = - serde_json::to_string_pretty(&self.params).unwrap_or_else(|_| self.params.to_string()); + let params = redact_params(&self.method, &self.params); + let params = serde_json::to_string_pretty(¶ms).unwrap_or_else(|_| params.to_string()); write!( f, "{{ id: {}, method: {}, params: {} }}", @@ -74,16 +143,25 @@ impl fmt::Display for StandardRequest { } } -#[derive(Clone, Serialize, Deserialize, Debug)] +#[derive(Clone, Serialize, Deserialize)] pub struct Notification { pub method: String, pub params: serde_json::Value, } +impl fmt::Debug for Notification { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Notification") + .field("method", &self.method) + .field("params", &redact_params(&self.method, &self.params)) + .finish() + } +} + impl fmt::Display for Notification { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let params = - serde_json::to_string_pretty(&self.params).unwrap_or_else(|_| self.params.to_string()); + let params = redact_params(&self.method, &self.params); + let params = serde_json::to_string_pretty(¶ms).unwrap_or_else(|_| params.to_string()); write!(f, "{{ method: \"{}\", params: {} }}", self.method, params) } @@ -327,4 +405,36 @@ mod tests { .unwrap(); assert!(matches!(success, Message::OkResponse(_))); } + + #[test] + fn formatted_requests_redact_credentials() { + for wire in [ + r#"{"id":1,"method":"mining.authorize","params":["worker","hunter2"]}"#, + r#"{"id":1,"method":"mining.authorize","params":["worker","hunter2","extra"]}"#, + r#"{"id":1,"method":"mining.authorize","params":{"password":"hunter2"}}"#, + r#"{"id":null,"method":"mining.authorize","params":["worker","hunter2"]}"#, + r#"{"id":2,"method":"mining.configure","params":[["info"],{"info.connection-url":"stratum+tcp://worker:hunter2@pool.example:3333"}]}"#, + ] { + let message: Message = serde_json::from_str(wire).unwrap(); + for formatted in [format!("{message}"), format!("{message:?}")] { + assert!(!formatted.contains("hunter2"), "{formatted}"); + assert!(formatted.contains(REDACTED), "{formatted}"); + } + } + } + + #[test] + fn formatted_requests_keep_other_params() { + let message: Message = serde_json::from_str( + r#"{"id":1,"method":"mining.authorize","params":["worker","hunter2"]}"#, + ) + .unwrap(); + assert!(format!("{message}").contains("worker")); + + let message: Message = + serde_json::from_str(r#"{"id":1,"method":"mining.subscribe","params":["agent"]}"#) + .unwrap(); + assert!(format!("{message}").contains("agent")); + assert!(format!("{message:?}").contains("agent")); + } } diff --git a/sv1/src/lib.rs b/sv1/src/lib.rs index 26dcac8a05..7c03f8c2da 100644 --- a/sv1/src/lib.rs +++ b/sv1/src/lib.rs @@ -1056,4 +1056,47 @@ mod tests { let msg: Message = serde_json::from_value(raw).unwrap(); assert!(Method::try_from(msg).is_err()); } + + #[test] + fn credentials_never_reach_formatted_output() { + let secret = "hunter2"; + let authorize = client_to_server::Authorize { + id: 1, + name: "worker".to_string(), + password: secret.to_string(), + }; + let wrapped = Error::InvalidReceiver(Box::new(Method::Client2Server( + methods::Client2Server::Authorize(authorize.clone()), + ))); + for formatted in [ + format!("{authorize}"), + format!("{authorize:?}"), + format!("{wrapped}"), + format!("{wrapped:?}"), + ] { + assert!(!formatted.contains(secret), "{formatted}"); + } + + for wire in [ + r#"{"id":1,"method":"mining.authorize","params":["worker","hunter2",1]}"#, + r#"{"id":1,"method":"mining.authorize","params":{"password":"hunter2"}}"#, + r#"{"id":2,"method":"mining.configure","params":[["info"],{"info.connection-url":"stratum+tcp://worker:hunter2@pool.example:3333"}]}"#, + r#"{"id":2,"method":"mining.configure","params":{"info.connection-url":"stratum+tcp://worker:hunter2@pool.example:3333"}}"#, + ] { + let message: Message = serde_json::from_str(wire).unwrap(); + let formatted = match methods::Client2Server::try_from(message) { + Ok(methods::Client2Server::Configure(configure)) => { + vec![format!("{configure}"), format!("{configure:?}")] + } + Ok(request) => vec![format!("{request:?}")], + Err(error) => { + let error = Error::from(error); + vec![format!("{error}"), format!("{error:?}")] + } + }; + for formatted in formatted { + assert!(!formatted.contains(secret), "{formatted}"); + } + } + } } diff --git a/sv1/src/methods/client_to_server.rs b/sv1/src/methods/client_to_server.rs index ac98b9136b..9ebb8cb835 100644 --- a/sv1/src/methods/client_to_server.rs +++ b/sv1/src/methods/client_to_server.rs @@ -9,7 +9,7 @@ use std::fmt; use crate::{ error::Error, - json_rpc::{JsonRpcError, Message, Response, StandardRequest}, + json_rpc::{redact_params, JsonRpcError, Message, Redacted, Response, StandardRequest}, methods::ParsingMethodError, utils::{Extranonce, HexU32Be, VERSION_ROLLING_MASK}, }; @@ -24,13 +24,23 @@ use quickcheck_macros; /// /// The result from an authorize request is usually true (successful), or false. /// The password may be omitted if the server does not require passwords. -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Clone, PartialEq, Eq)] pub struct Authorize { pub id: u64, pub name: String, pub password: String, } +impl fmt::Debug for Authorize { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Authorize") + .field("id", &self.id) + .field("name", &self.name) + .field("password", &Redacted) + .finish() + } +} + impl fmt::Display for Authorize { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( @@ -71,12 +81,18 @@ impl TryFrom for Authorize { Some(params) => { let (name, password) = match ¶ms[..] { [JString(a), JString(b)] => (a.into(), b.into()), - _ => return Err(ParsingMethodError::wrong_args_from_value(msg.params)), + _ => { + return Err(ParsingMethodError::wrong_args_from_value( + redact_params(&msg.method, &msg.params).into_owned(), + )) + } }; let id = msg.id; Ok(Self { id, name, password }) } - None => Err(ParsingMethodError::not_array_from_value(msg.params)), + None => Err(ParsingMethodError::not_array_from_value( + redact_params(&msg.method, &msg.params).into_owned(), + )), } } } @@ -647,9 +663,11 @@ impl fmt::Display for ConfigureExtension { impl ConfigureExtension { pub fn from_value(val: &Value) -> Result, ParsingMethodError> { let mut res = vec![]; - let root = val - .as_array() - .ok_or_else(|| ParsingMethodError::not_array_from_value(val.clone()))?; + let root = val.as_array().ok_or_else(|| { + ParsingMethodError::not_array_from_value( + redact_params("mining.configure", val).into_owned(), + ) + })?; if root.is_empty() { return Err(ParsingMethodError::Todo); }; @@ -841,7 +859,7 @@ impl From for serde_json::Map { } } -#[derive(Debug, Clone)] +#[derive(Clone)] pub struct InfoParams { pub connection_url: Option, #[allow(dead_code)] @@ -852,6 +870,21 @@ pub struct InfoParams { pub sw_version: Option, } +impl fmt::Debug for InfoParams { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + // The connection URL can embed `user:password@`. + f.debug_struct("InfoParams") + .field( + "connection_url", + &self.connection_url.as_ref().map(|_| Redacted), + ) + .field("hw_id", &self.hw_id) + .field("hw_version", &self.hw_version) + .field("sw_version", &self.sw_version) + .finish() + } +} + impl From for serde_json::Map { fn from(info: InfoParams) -> Self { let mut params = serde_json::Map::new();