Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions lwk_bindings/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
## Unreleased

* Breaking: If a PSET has a non-default sighash, `Signer.sign()` and `SecretKey.sign()` now return an error. To sign with non-default sighashes, pass `SignOptions.allow_sighash_single_anyonecanpay()` or `SignOptions.dangerous_allow_any_sighash()` to `Signer.sign_with_options()`
* Add `validate_domain` to `ElectrumClientBuilder`, `true` by default, to connect over TLS to a server with a self-signed certificate or an IP address as host. `false` disables the verification of the server certificate: the server is no longer authenticated.
* Fix `ElectrumClient(url, tls, validate_domain)` ignoring `validate_domain=false` and rejecting a TLS url with an IP address as host, a regression in 0.19.0.

## 0.20.0

Expand Down
10 changes: 8 additions & 2 deletions lwk_bindings/src/electrum_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,11 @@ pub struct ElectrumClientBuilder {
/// `tcp://` url is refused.
#[uniffi(default = false)]
allow_plaintext_with_token: bool,
/// Verify the server certificate of a TLS (`ssl://`) url. `false` allows a self-signed
/// certificate or an IP address as host, but the server is then not authenticated: anyone
/// able to intercept the connection can impersonate it and capture a token. On by default.
#[uniffi(default = true)]
validate_domain: bool,
}

impl From<ElectrumClientBuilder> for lwk_wollet::ElectrumClientBuilder {
Expand All @@ -48,7 +53,7 @@ impl From<ElectrumClientBuilder> for lwk_wollet::ElectrumClientBuilder {
if builder.allow_plaintext_with_token {
result = result.allow_plaintext_with_token(true);
}
result
result.validate_domain(builder.validate_domain)
}
}

Expand All @@ -63,7 +68,8 @@ impl ElectrumClient {
) -> Result<Arc<Self>, LwkError> {
let url = lwk_wollet::ElectrumUrl::new(electrum_url, tls, validate_domain)
.map_err(lwk_wollet::Error::Url)?;
let builder = lwk_wollet::ElectrumClientBuilder::new(&url.to_string());
let builder = lwk_wollet::ElectrumClientBuilder::new(&url.to_string())
.validate_domain(validate_domain);
let client = builder.clone().build()?;
Ok(Arc::new(Self {
inner: Arc::new(Mutex::new(client)),
Expand Down
3 changes: 3 additions & 0 deletions lwk_wollet/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@

## Unreleased

* Add `ElectrumClientBuilder::validate_domain()` to connect over TLS to a server with a self-signed certificate or an IP address as host. `false` disables the verification of the server certificate: the server is no longer authenticated.
* Fix `ElectrumClient::new()` and `ElectrumClient::with_options()` ignoring the `validate_domain = false` of an `ElectrumUrl` built with `ElectrumUrl::new()`, and rejecting such a url with an IP address as host, a regression in 0.19.0.

## 0.20.0

* Breaking: update to `elements` 0.27 and `elements-miniscript` 0.5. Types re-exported from `elements` changed, for example the hex helpers (`ToHex`, `FromHex`), `AssetId` and `Txid` constructors, the issuance entropy (now `AssetEntropy`) and the pegin witness.
Expand Down
72 changes: 68 additions & 4 deletions lwk_wollet/src/clients/blocking/electrum_client.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::cache::Height;
use crate::clients::electrum_url::ElectrumUrl;
use crate::clients::electrum_url::{parse_electrum_url, ElectrumUrl};
use crate::clients::TokenProvider;
use crate::Error;
use crate::History;
Expand Down Expand Up @@ -61,14 +61,14 @@ impl ElectrumClient {
/// provider, use [`ElectrumClientBuilder`].
// TODO: deprecate in favour of ElectrumClientBuilder.
pub fn new(url: &ElectrumUrl) -> Result<Self, Error> {
ElectrumClientBuilder::new(&url.to_string()).build()
url.client_builder().build()
}

/// Creates an Electrum client specifying non default options like timeout.
#[deprecated(note = "use ElectrumClientBuilder instead")]
#[allow(deprecated)]
pub fn with_options(url: &ElectrumUrl, options: ElectrumOptions) -> Result<Self, Error> {
let mut builder = ElectrumClientBuilder::new(&url.to_string());
let mut builder = url.client_builder();
if let Some(timeout) = options.timeout {
builder = builder.timeout(Duration::from_secs(timeout as u64));
}
Expand Down Expand Up @@ -160,6 +160,7 @@ pub struct ElectrumClientBuilder {
timeout: Option<Duration>,
token_provider: TokenProvider,
allow_plaintext_with_token: bool,
validate_domain: bool,
}

impl ElectrumClientBuilder {
Expand All @@ -171,6 +172,7 @@ impl ElectrumClientBuilder {
timeout: None,
token_provider: TokenProvider::None,
allow_plaintext_with_token: false,
validate_domain: true,
}
}

Expand Down Expand Up @@ -219,9 +221,29 @@ impl ElectrumClientBuilder {
self
}

/// Set whether a TLS (`ssl://`) connection verifies the server certificate, `true` by
/// default. Plaintext (`tcp://`) urls ignore it.
///
/// Setting `false` allows a server with a self-signed certificate, or a TLS url with an
/// IP address as host (e.g. `ssl://192.168.1.10:50002`), which is otherwise rejected.
///
/// Security:
/// - With the rustls backend used by this crate, `false` disables the verification of
/// the server certificate entirely, not only the match with the host name: the
/// connection is encrypted but the server is not authenticated, so anyone able to
/// intercept it can impersonate the server and see or alter the wallet's requests and
/// their answers. Use it only for a server reached through a network path you trust.
/// - A token set with [`Self::token_provider`] is sent to whoever answers, so an
/// interceptor can capture it. `false` does not allow sending a token over a plaintext
/// connection, which still requires [`Self::allow_plaintext_with_token`].
pub fn validate_domain(mut self, validate: bool) -> Self {
self.validate_domain = validate;
self
}

/// Build the [`ElectrumClient`], opening the connection.
pub fn build(self) -> Result<ElectrumClient, Error> {
let url: ElectrumUrl = self.url.parse()?;
let url = parse_electrum_url(&self.url, self.validate_domain)?;
if matches!(url, ElectrumUrl::Plaintext(_))
&& !matches!(self.token_provider, TokenProvider::None)
&& !self.allow_plaintext_with_token
Expand Down Expand Up @@ -341,6 +363,16 @@ impl From<GetHistoryRes> for History {
}

impl ElectrumUrl {
/// A builder for this url. The domain validation flag of a TLS url is passed explicitly
/// because the url's string form cannot carry it.
fn client_builder(&self) -> ElectrumClientBuilder {
let validate_domain = match self {
ElectrumUrl::Tls(_, validate_domain) => *validate_domain,
ElectrumUrl::Plaintext(_) => true,
};
ElectrumClientBuilder::new(&self.to_string()).validate_domain(validate_domain)
}

/// Build an Electrum client from the url and options.
#[deprecated(note = "use ElectrumClientBuilder instead")]
#[allow(deprecated)]
Expand Down Expand Up @@ -812,4 +844,36 @@ mod tests {
"expected an error when a token is set on a plaintext connection without opt-in"
);
}

#[test]
fn electrum_tls_domain_validation_flag() {
#[allow(deprecated)]
use super::{ElectrumClient, ElectrumClientBuilder, ElectrumOptions};
use crate::{Error, UrlError};

// A TLS url on an IP host is refused by default: the domain cannot be validated.
let err = ElectrumClientBuilder::new("ssl://127.0.0.1:1")
.build()
.unwrap_err();
assert!(
matches!(err, Error::Url(UrlError::SslWithoutDomain)),
"{err:?}"
);

// Without domain validation it is accepted and the client tries to connect (nothing
// listens on port 1), through the builder and through the deprecated constructors.
let url = ElectrumUrl::new("127.0.0.1:1", true, false).unwrap();
#[allow(deprecated)]
let results = [
ElectrumClientBuilder::new("ssl://127.0.0.1:1")
.validate_domain(false)
.build(),
ElectrumClient::new(&url),
ElectrumClient::with_options(&url, ElectrumOptions::default()),
];
for result in results {
let err = result.unwrap_err();
assert!(!matches!(err, Error::Url(_)), "{err:?}");
}
}
}
45 changes: 25 additions & 20 deletions lwk_wollet/src/clients/electrum_url.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,27 +16,32 @@ impl FromStr for ElectrumUrl {
type Err = crate::UrlError;

fn from_str(s: &str) -> Result<Self, Self::Err> {
let url: url::Url = s.parse()?;
let ssl = url.scheme() == "ssl";
if !(ssl || url.scheme() == "tcp") {
return Err(crate::UrlError::Schema(url.scheme().to_string()));
}
if url.port().is_none() {
return Err(crate::UrlError::MissingPort);
}
match url.domain() {
Some(domain) => match domain.parse::<IpAddr>() {
Ok(_) => {
if ssl {
Err(crate::UrlError::SslWithoutDomain)
} else {
ElectrumUrl::new(&s[6..], false, false)
}
}
Err(_) => ElectrumUrl::new(&s[6..], ssl, ssl),
},
None => Err(crate::UrlError::MissingDomain),
parse_electrum_url(s, true)
}
}

/// Parse an Electrum url like [`ElectrumUrl::from_str`], with the given domain validation
/// flag for a TLS url. Without validation, a TLS url may have an IP address as host.
pub(crate) fn parse_electrum_url(
s: &str,
validate_domain: bool,
) -> Result<ElectrumUrl, crate::UrlError> {
let url: url::Url = s.parse()?;
let ssl = url.scheme() == "ssl";
if !(ssl || url.scheme() == "tcp") {
return Err(crate::UrlError::Schema(url.scheme().to_string()));
}
if url.port().is_none() {
return Err(crate::UrlError::MissingPort);
}
match url.domain() {
Some(domain) => {
if ssl && validate_domain && domain.parse::<IpAddr>().is_ok() {
return Err(crate::UrlError::SslWithoutDomain);
}
ElectrumUrl::new(&s[6..], ssl, ssl && validate_domain)
}
None => Err(crate::UrlError::MissingDomain),
}
}

Expand Down