Skip to content

Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.

Tweak credential_matcher logic for improved security (#2469)

Leendert de Borstee3f46f6f524
diff --git a/core/rust/src/credential_matcher/domain.rs b/core/rust/src/credential_matcher/domain.rs
index c1092e954..14a6664b8 100644
--- a/core/rust/src/credential_matcher/domain.rs
+++ b/core/rust/src/credential_matcher/domain.rs
@@ -90,7 +90,10 @@ impl DomainWithPort {
/// Returns DomainWithPort with empty domain if not a valid URL/domain.
pub fn extract_domain_with_port(url: &str) -> DomainWithPort {
let lowered = url.trim().to_lowercase();
- let (scheme, authority, _) = split_url(&lowered);
+
+ // A blob URL ("blob:https://example.com/<uuid>") belongs to the origin it wraps.
+ let lowered = lowered.strip_prefix("blob:").unwrap_or(&lowered);
+ let (scheme, authority, _) = split_url(lowered);
// A web scheme is what allows single-word hostnames like "http://plex" or "https://nas",
// common in self-hosted setups. Any other scheme names something that is not a website.
@@ -105,19 +108,24 @@ pub fn extract_domain_with_port(url: &str) -> DomainWithPort {
return DomainWithPort::default();
}
- let host = authority.strip_prefix("www.").unwrap_or(authority);
- let (domain, port) = match host.split_once(':') {
- Some((domain, port)) if !port.is_empty() && port.chars().all(|c| c.is_ascii_digit()) => (domain, Some(port.to_string())),
- Some((domain, _)) => (domain, None),
- None => (host, None),
- };
+ // The host is what follows any userinfo: "https://[email protected]" opens example.com.
+ let host_and_port = authority.rsplit_once('@').map_or(authority, |(_, host)| host);
+ let (host, port) = split_host_port(host_and_port);
+
+ // A fully qualified name ("bank.com.") is the same host as without its trailing dot.
+ let host = host.strip_suffix('.').unwrap_or(host);
+ let domain = host.strip_prefix("www.").unwrap_or(host);
+
+ if is_ip_literal(domain) {
+ return DomainWithPort { domain: domain.to_string(), port };
+ }
// Without a scheme, require at least one dot to distinguish a hostname from random text.
if domain.is_empty() || (!domain.contains('.') && !has_protocol) {
return DomainWithPort::default();
}
- let valid_chars = domain.chars().all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '-');
+ let valid_chars = domain.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_'));
let valid_structure = !domain.starts_with('.') && !domain.ends_with('.') && !domain.contains("..");
if !valid_chars || !valid_structure {
return DomainWithPort::default();
@@ -126,6 +134,22 @@ pub fn extract_domain_with_port(url: &str) -> DomainWithPort {
DomainWithPort { domain: domain.to_string(), port }
}
+/// Split an authority without userinfo into its host and numeric port; a bracketed IPv6 host keeps its brackets.
+fn split_host_port(authority: &str) -> (&str, Option<String>) {
+ let (host, port) = match authority.strip_prefix('[').and_then(|rest| rest.find(']')) {
+ Some(end) => {
+ let (host, rest) = authority.split_at(end + 2);
+ (host, rest.strip_prefix(':'))
+ }
+ None => match authority.split_once(':') {
+ Some((host, port)) => (host, Some(port)),
+ None => (authority, None),
+ },
+ };
+ let port = port.filter(|p| !p.is_empty() && p.chars().all(|c| c.is_ascii_digit())).map(String::from);
+ (host, port)
+}
+
/// Extract domain from URL, handling both full URLs and partial domains.
/// Returns empty string if not a valid URL/domain.
/// Note: This strips port numbers. Use extract_domain_with_port() to preserve port info.
@@ -378,6 +402,34 @@ mod tests {
assert_eq!(result.port, None); // Invalid port should be None
}
+ #[test]
+ fn test_extract_domain_normalizes_host() {
+ // Userinfo is dropped: the host is what follows the last "@".
+ assert_eq!(extract_domain("https://[email protected]/"), "evil.com");
+ assert_eq!(extract_domain("https://user:[email protected]:8443/"), "example.com");
+
+ // One trailing dot is dropped, before the "www." prefix.
+ assert_eq!(extract_domain("https://paypal.com./"), "paypal.com");
+ assert_eq!(extract_domain("https://www.paypal.com./"), "paypal.com");
+ assert_eq!(extract_domain("https://paypal.com../"), "");
+
+ // Underscores are accepted in host labels.
+ assert_eq!(extract_domain("https://www_paypal.evil.com/"), "www_paypal.evil.com");
+
+ // Bracketed IPv6 keeps its brackets and splits off the port after the bracket.
+ let ipv6 = extract_domain_with_port("http://[::1]:8080/paypal");
+ assert_eq!(ipv6.domain, "[::1]");
+ assert_eq!(ipv6.port, Some("8080".to_string()));
+ assert_eq!(extract_domain("http://[2001:db8::1]/"), "[2001:db8::1]");
+ assert_eq!(extract_domain("http://[::1/"), "");
+
+ // A blob URL resolves to the origin it wraps; other non-web schemes give no domain.
+ assert_eq!(extract_domain("blob:https://paypal.evil.com/0b2c3d4e"), "paypal.evil.com");
+ assert_eq!(extract_domain("blob:null/0b2c3d4e"), "");
+ assert_eq!(extract_domain("filesystem:https://paypal.com/temporary/x"), "");
+ assert_eq!(extract_domain("data:text/html,paypal.com"), "");
+ }
+
#[test]
fn test_extract_root_domain() {
assert_eq!(extract_root_domain("sub.example.com"), "example.com");
diff --git a/core/rust/src/credential_matcher/mod.rs b/core/rust/src/credential_matcher/mod.rs
index 1e9eba7f1..2c0098536 100644
--- a/core/rust/src/credential_matcher/mod.rs
+++ b/core/rust/src/credential_matcher/mod.rs
@@ -8,7 +8,10 @@
//! 2. Priority 2: URL domain matching (exact, subdomain, root domain)
//! 3. Priority 3b: root domain word matching against item names (only credentials without URLs)
//! 4. Priority 3: page title fallback (only credentials without URLs, anti-phishing)
-//! 5. Priority 4: text matching of the search string against item names
+//! 5. Priority 4: text matching of the search string against item names (only credentials without URLs)
+//!
+//! Anti-phishing: a name match never returns a credential that has a URL, and a URL (any input with a
+//! scheme) whose host cannot be extracted matches nothing instead of falling through to the name stages.
pub(crate) mod domain;
mod public_suffix;
@@ -17,7 +20,7 @@ mod stop_words;
use serde::{Deserialize, Serialize};
pub use domain::{extract_domain, extract_domain_with_port, extract_root_domain, is_related_origin_allowed, is_rp_id_allowed_for_host, DomainWithPort};
-use domain::{domains_match, is_app_package_name};
+use domain::{domains_match, is_app_package_name, split_url};
use stop_words::STOP_WORD_SET;
/// Default per-priority cap on returned matches when the caller does not supply `max_results`.
@@ -120,7 +123,7 @@ pub fn filter_credentials(input: CredentialMatcherInput) -> CredentialMatcherOut
// Default mode adds on top of URL matching, so the URL-only modes must not fall back to it.
if matching_mode == AutofillMatchingMode::Default {
let domain_words = extract_words(&extract_root_domain(&current.domain));
- let ids = match_item_names(&credentials, &domain_words, true, max_results);
+ let ids = match_item_names(&credentials, &domain_words, max_results);
if !ids.is_empty() {
return CredentialMatcherOutput::matched(3, ids);
}
@@ -129,19 +132,25 @@ pub fn filter_credentials(input: CredentialMatcherInput) -> CredentialMatcherOut
// A web page never falls through to the text stages.
return CredentialMatcherOutput::default();
}
+
+ // Input with a scheme is a URL whose host could not be extracted: it never falls through either.
+ if split_url(&current_url.trim().to_lowercase()).0.is_some() {
+ return CredentialMatcherOutput::default();
+ }
}
- // Priority 3: page title against item names when domain extraction failed (desktop apps, malformed
- // URLs). Anti-phishing: only credentials with no URLs are eligible.
+ // Priority 3: page title against item names for input that is neither a URL nor a linked app package.
+ // Anti-phishing: only credentials with no URLs are eligible.
let title_words = extract_words(&page_title);
- let ids = match_item_names(&credentials, &title_words, true, max_results);
+ let ids = match_item_names(&credentials, &title_words, max_results);
if !ids.is_empty() {
return CredentialMatcherOutput::matched(3, ids);
}
- // Priority 4: the search string itself against item names.
+ // Priority 4: the search string itself against item names. Anti-phishing: only credentials with no URLs
+ // are eligible, so an app package like "com.paypal.rewards" never gets the PayPal website credential.
let search_words = extract_words(&current_url);
- let ids = match_item_names(&credentials, &search_words, false, max_results);
+ let ids = match_item_names(&credentials, &search_words, max_results);
if !ids.is_empty() {
return CredentialMatcherOutput::matched(4, ids);
}
@@ -207,18 +216,17 @@ fn domain_match_rank(cred: &Credential, current: &DomainWithPort, allow_subdomai
best
}
-/// Ids of credentials whose item name shares a complete word with `words`.
+/// Ids of credentials without URLs whose item name shares a complete word with `words`.
///
-/// With `require_no_urls`, credentials that have any URL are skipped: a name match must never
-/// surface a credential bound to another site (anti-phishing).
-fn match_item_names(credentials: &[Credential], words: &[String], require_no_urls: bool, max_results: usize) -> Vec<String> {
+/// Credentials that have any URL are skipped: a name match must never surface a credential bound to another site (anti-phishing).
+fn match_item_names(credentials: &[Credential], words: &[String], max_results: usize) -> Vec<String> {
if words.is_empty() {
return vec![];
}
credentials
.iter()
- .filter(|cred| !require_no_urls || !cred.item_urls.iter().any(|url| !url.trim().is_empty()))
+ .filter(|cred| cred.item_urls.iter().all(|url| url.trim().is_empty()))
.filter(|cred| {
cred.item_name.as_deref().is_some_and(|name| {
let name_words = extract_words(name);
diff --git a/core/rust/src/credential_matcher/tests.rs b/core/rust/src/credential_matcher/tests.rs
index b41670ec4..08274c30f 100644
--- a/core/rust/src/credential_matcher/tests.rs
+++ b/core/rust/src/credential_matcher/tests.rs
@@ -1084,3 +1084,87 @@ fn test_stored_urls_are_trimmed() {
assert_eq!(filter(credentials.clone(), "https://amazon.it", "").len(), 1, "Trailing whitespace should be ignored");
assert_eq!(filter(credentials, "com.amazon.app", "").len(), 1, "Package name should match when padded");
}
+
+/// Runs the matcher in every matching mode and returns the matched ids per mode.
+fn filter_all_modes(credentials: &[Credential], current_url: &str) -> Vec<(AutofillMatchingMode, CredentialMatcherOutput)> {
+ [AutofillMatchingMode::Default, AutofillMatchingMode::UrlSubdomain, AutofillMatchingMode::UrlExact]
+ .into_iter()
+ .map(|mode| {
+ let input = CredentialMatcherInput {
+ credentials: credentials.to_vec(),
+ current_url: current_url.to_string(),
+ page_title: String::new(),
+ matching_mode: mode,
+ ignore_port: false,
+ max_results: None,
+ };
+ (mode, filter_credentials(input))
+ })
+ .collect()
+}
+
+/// [#45] - A URL whose host fails validation must not fall through to name matching (phishing autofill)
+#[test]
+fn test_unusual_hosts_never_fall_through_to_name_matching() {
+ let credentials = vec![
+ create_test_credential("PayPal", "https://paypal.com", "[email protected]"),
+ create_test_credential("PayPal Notes", "", ""),
+ ];
+
+ for phishing_url in [
+ "https://www_paypal.evil.com/",
+ "https://paypal.evil.com./",
+ "https://[email protected]/",
+ "https://[::1]:8080/paypal",
+ "blob:https://paypal.evil.com/0b2c3d4e-0000-4000-8000-000000000000",
+ "filesystem:https://paypal.evil.com/temporary/paypal",
+ "data:text/html,paypal",
+ ] {
+ for (mode, output) in filter_all_modes(&credentials, phishing_url) {
+ assert!(output.matched_ids.is_empty(), "{phishing_url} in {mode:?} mode must not match: {output:?}");
+ }
+ }
+}
+
+/// [#46] - An app package without a linked credential never gets a website credential through its name
+#[test]
+fn test_unlinked_app_package_only_matches_credentials_without_urls() {
+ let paypal_web = create_test_credential("PayPal", "https://paypal.com", "[email protected]");
+ let paypal_note = create_test_credential("PayPal Notes", "", "");
+ let credentials = vec![paypal_web.clone(), paypal_note.clone()];
+
+ for package in ["com.fake.paypal", "com.paypal.rewards", "net.paypal.cashback"] {
+ let output = filter_all_modes(&credentials, package);
+ for (mode, output) in output {
+ assert_eq!(output.matched_ids, vec![paypal_note.id.clone()], "{package} in {mode:?} mode");
+ assert_eq!(output.matched_priority, 4);
+ }
+ }
+
+ // Without a credential lacking URLs there is nothing left to offer.
+ let matches = filter(vec![paypal_web], "com.paypal.rewards", "PayPal Rewards");
+ assert!(matches.is_empty());
+}
+
+/// [#47] - Hosts are normalized before matching, so legitimate pages in those shapes still match their own credential
+#[test]
+fn test_unusual_hosts_match_their_own_credential() {
+ let credentials = vec![
+ create_test_credential("PayPal", "https://paypal.com", "[email protected]"),
+ create_test_credential("Intranet", "https://my_host.corp.example", "[email protected]"),
+ create_test_credential("Local IPv6", "http://[::1]:8080", "admin"),
+ create_test_credential("Evil", "https://evil.com", "attacker"),
+ ];
+ let name_of = |url: &str| filter(credentials.clone(), url, "").into_iter().map(|c| c.item_name.unwrap_or_default()).collect::<Vec<_>>();
+
+ assert_eq!(name_of("https://paypal.com./login"), vec!["PayPal"]);
+ assert_eq!(name_of("https://www.paypal.com./"), vec!["PayPal"]);
+ assert_eq!(name_of("blob:https://www.paypal.com/0b2c3d4e-0000-4000-8000-000000000000"), vec!["PayPal"]);
+ assert_eq!(name_of("https://my_host.corp.example/login"), vec!["Intranet"]);
+ assert_eq!(name_of("http://[::1]:8080/login"), vec!["Local IPv6"]);
+ assert!(name_of("http://[::2]:8080/login").is_empty());
+
+ // The host is what follows the userinfo: the page is evil.com, not paypal.com.
+ assert_eq!(name_of("https://[email protected]/"), vec!["Evil"]);
+ assert_eq!(name_of("https://paypal.com:[email protected]/"), vec!["Evil"]);
+}