Skip to content

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

Add related origin check including PSL to Passkey RpId validations (#2161)

Leendert de Borstdce38203523a
diff --git a/apps/browser-extension/src/entrypoints/background.ts b/apps/browser-extension/src/entrypoints/background.ts
index 4977b07cb..269566b9d 100644
--- a/apps/browser-extension/src/entrypoints/background.ts
+++ b/apps/browser-extension/src/entrypoints/background.ts
@@ -17,8 +17,9 @@ import { logFailure } from '@/utils/Diagnostics';
import { LocalPreferencesService } from '@/utils/LocalPreferencesService';
import { onMessage, sendMessage } from "@/utils/messaging/ExtensionMessaging";
import type { IExtensionMessageProtocol } from "@/utils/messaging/ExtensionMessaging";
+import { isRpIdAllowedForCaller } from '@/utils/passkey/RelyingPartyValidation';
import type { MatchingPasskeysResponse, WebAuthnAssertionResponse, WebAuthnPublicKeyGetPayload } from '@/utils/passkey/types';
-import { isRpIdAllowedForHost, validateWebAuthnRequest } from '@/utils/passkey/WebAuthnRequestValidation';
+import { getWebAuthnRequestRpId, validateWebAuthnRequest } from '@/utils/passkey/WebAuthnRequestValidation';
import type { WebAuthnBridgeRequest } from '@/utils/passkey/WebAuthnRequestValidation';
import { runStartupMigrations } from '@/migrations';
@@ -75,18 +76,30 @@ function getTrustedWebAuthnSenderContext(sender: WebAuthnMessageSender): Trusted
* so each WebAuthn message keeps its own validation rule and fallback shape while sharing the
* trust resolution and guard plumbing.
*/
-function withTrustedWebAuthnSender<T, U>(
+async function withTrustedWebAuthnSender<T, U>(
sender: WebAuthnMessageSender,
- validate: (context: TrustedWebAuthnSenderContext) => boolean,
+ validate: (context: TrustedWebAuthnSenderContext) => MaybePromise<boolean>,
handle: (context: TrustedWebAuthnSenderContext) => T,
onInvalid: U
-): T | U {
+): Promise<Awaited<T> | U> {
const senderContext = getTrustedWebAuthnSenderContext(sender);
- if (!senderContext || !validate(senderContext)) {
+ if (!senderContext || !(await validate(senderContext))) {
return onInvalid;
}
- return handle(senderContext);
+ return await handle(senderContext);
+}
+
+/**
+ * Validate a WebAuthn request and check that the sender may use the RP ID it names.
+ */
+async function isValidWebAuthnRequest(type: 'create' | 'get', request: WebAuthnBridgeRequest, context: TrustedWebAuthnSenderContext): Promise<boolean> {
+ if (!validateWebAuthnRequest(type, request, context.origin)) {
+ return false;
+ }
+
+ const rpId = getWebAuthnRequestRpId(type, request);
+ return rpId === undefined || (typeof rpId === 'string' && await isRpIdAllowedForCaller(rpId, context.origin, context.host));
}
/**
@@ -148,10 +161,10 @@ async function broadcastVaultUnlocked(): Promise<void> {
* Validate a WebAuthn create request against the sender's trusted origin, then forward it to the
* passkey create flow. Falls back when the sender is untrusted or validation fails.
*/
-function handleValidatedWebAuthnCreate(data: WebAuthnBridgeRequest, sender: WebAuthnMessageSender): Promise<unknown> | { fallback: true } {
+function handleValidatedWebAuthnCreate(data: WebAuthnBridgeRequest, sender: WebAuthnMessageSender): Promise<unknown> {
return withTrustedWebAuthnSender(
sender,
- (ctx) => validateWebAuthnRequest('create', data, ctx.origin, ctx.host),
+ (ctx) => isValidWebAuthnRequest('create', data, ctx),
(ctx) => handleWebAuthnCreate({ ...data, origin: ctx.origin }),
{ fallback: true }
);
@@ -161,10 +174,10 @@ function handleValidatedWebAuthnCreate(data: WebAuthnBridgeRequest, sender: WebA
* Validate a WebAuthn get request against the sender's trusted origin, then forward it to the
* passkey get flow. Falls back when the sender is untrusted or validation fails.
*/
-function handleValidatedWebAuthnGet(data: WebAuthnBridgeRequest, sender: WebAuthnMessageSender): Promise<unknown> | { fallback: true } {
+function handleValidatedWebAuthnGet(data: WebAuthnBridgeRequest, sender: WebAuthnMessageSender): Promise<unknown> {
return withTrustedWebAuthnSender(
sender,
- (ctx) => validateWebAuthnRequest('get', data, ctx.origin, ctx.host),
+ (ctx) => isValidWebAuthnRequest('get', data, ctx),
(ctx) => handleWebAuthnGet({ ...data, origin: ctx.origin }),
{ fallback: true }
);
@@ -178,10 +191,10 @@ function handleValidatedWebAuthnGet(data: WebAuthnBridgeRequest, sender: WebAuth
function handleValidatedGetMatchingPasskeys(
data: { rpId: string; allowCredentialIds?: string[] },
sender: WebAuthnMessageSender
-): Promise<MatchingPasskeysResponse> | MatchingPasskeysResponse {
+): Promise<MatchingPasskeysResponse> {
return withTrustedWebAuthnSender(
sender,
- (ctx) => typeof data?.rpId === 'string' && isRpIdAllowedForHost(data.rpId, ctx.host),
+ async (ctx) => typeof data?.rpId === 'string' && await isRpIdAllowedForCaller(data.rpId, ctx.origin, ctx.host),
() => handleGetMatchingPasskeys(data),
{ success: false, locked: false, passkeys: [] }
);
@@ -194,10 +207,10 @@ function handleValidatedGetMatchingPasskeys(
function handleValidatedWebAuthnGetAssertion(
data: { passkeyId: string; manifestId: string; origin: string; publicKey: WebAuthnPublicKeyGetPayload },
sender: WebAuthnMessageSender
-): Promise<WebAuthnAssertionResponse> | WebAuthnAssertionResponse {
+): Promise<WebAuthnAssertionResponse> {
return withTrustedWebAuthnSender(
sender,
- (ctx) => typeof data?.passkeyId === 'string' && typeof data?.manifestId === 'string' && validateWebAuthnRequest('get', data, ctx.origin, ctx.host),
+ async (ctx) => typeof data?.passkeyId === 'string' && typeof data?.manifestId === 'string' && await isValidWebAuthnRequest('get', data, ctx),
(ctx) => handleWebAuthnGetAssertion({ ...data, origin: ctx.origin }),
{ success: false, error: 'Invalid request' }
);
@@ -317,7 +330,6 @@ export default defineBackground({
// Remember login save state (for surviving page navigation)
onMessage('STORE_SAVE_PROMPT_STATE', ({ data, sender }) => handleStoreSavePromptState({ tabId: sender.tab!.id!, state: data }));
- onMessage('GET_SAVE_PROMPT_STATE', ({ sender }) => handleGetSavePromptState({ tabId: sender.tab!.id! }));
onMessage('CLEAR_SAVE_PROMPT_STATE', ({ sender }) => handleClearSavePromptState({ tabId: sender.tab!.id! }));
// Track last autofilled credential (for "Add URL to existing credential" prompt)
diff --git a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts
index f5d69bef2..50184cc61 100644
--- a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts
+++ b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts
@@ -865,6 +865,7 @@ export async function handleCheckLoginDuplicate(
// Find items with matching domain and username
const normalizedDomain = message.domain.toLowerCase();
const normalizedUsername = message.username.toLowerCase();
+ const currentRootDomain = await extractRootDomain(normalizedDomain);
for (const item of allItems) {
// Check LoginUrl field for domain match (supports multi-value URLs)
@@ -894,8 +895,8 @@ export async function handleCheckLoginDuplicate(
itemDomain = singleUrl.toLowerCase();
}
- // Check if domains match (including subdomains)
- if (itemDomain === normalizedDomain || itemDomain.endsWith(`.${normalizedDomain}`) || normalizedDomain.endsWith(`.${itemDomain}`)) {
+ // Same host, or the same root domain per the Public Suffix List
+ if (itemDomain === normalizedDomain || await extractRootDomain(itemDomain) === currentRootDomain) {
domainsMatch = true;
break;
}
diff --git a/apps/browser-extension/src/entrypoints/contentScript/WebAuthnInterceptor.ts b/apps/browser-extension/src/entrypoints/contentScript/WebAuthnInterceptor.ts
index 1310d7fe7..f3809a56c 100644
--- a/apps/browser-extension/src/entrypoints/contentScript/WebAuthnInterceptor.ts
+++ b/apps/browser-extension/src/entrypoints/contentScript/WebAuthnInterceptor.ts
@@ -121,7 +121,7 @@ export async function initializeWebAuthnInterceptor(_ctx: any): Promise<void> {
return;
}
- if (!validateWebAuthnEventDetail('create', detail, window.location.origin, window.location.hostname)) {
+ if (!validateWebAuthnEventDetail('create', detail, window.location.origin)) {
dispatchResponse({
requestId,
fallback: true
@@ -221,7 +221,7 @@ export async function initializeWebAuthnInterceptor(_ctx: any): Promise<void> {
return;
}
- if (!validateWebAuthnEventDetail('get', detail, window.location.origin, window.location.hostname)) {
+ if (!validateWebAuthnEventDetail('get', detail, window.location.origin)) {
dispatchResponse({
requestId,
fallback: true
diff --git a/apps/browser-extension/src/entrypoints/contentScript/__tests__/WebAuthnInterceptor.test.ts b/apps/browser-extension/src/entrypoints/contentScript/__tests__/WebAuthnInterceptor.test.ts
index 93846448b..d5e3ffccd 100644
--- a/apps/browser-extension/src/entrypoints/contentScript/__tests__/WebAuthnInterceptor.test.ts
+++ b/apps/browser-extension/src/entrypoints/contentScript/__tests__/WebAuthnInterceptor.test.ts
@@ -3,7 +3,7 @@ import { describe, expect, it } from 'vitest';
import type { WebAuthnGetEventDetail } from '@/utils/passkey/webauthn.types';
import {
cloneWebAuthnEventDetail,
- isRpIdAllowedForHost,
+ getWebAuthnRequestRpId,
validateWebAuthnEventDetail,
validateWebAuthnRequest
} from '@/utils/passkey/WebAuthnRequestValidation';
@@ -89,17 +89,11 @@ describe('WebAuthnInterceptor request validation', () => {
expect(isSameOriginWithAncestors(createFrameWithInaccessibleParent())).toBe(false);
});
- it('allows exact RP ID matches', () => {
- expect(isRpIdAllowedForHost('example.com', 'example.com')).toBe(true);
- });
-
- it('allows parent-domain RP IDs', () => {
- expect(isRpIdAllowedForHost('example.com', 'login.example.com')).toBe(true);
- });
-
- it('rejects sibling or unrelated RP IDs', () => {
- expect(isRpIdAllowedForHost('accounts.example.com', 'evil.example.com')).toBe(false);
- expect(isRpIdAllowedForHost('example.com', 'evil.com')).toBe(false);
+ it('reads the RP ID from create and get requests', () => {
+ expect(getWebAuthnRequestRpId('create', { origin: 'https://a.example.com', publicKey: { rp: { id: 'example.com' } } })).toBe('example.com');
+ expect(getWebAuthnRequestRpId('get', { origin: 'https://a.example.com', publicKey: { rpId: 'example.com' } })).toBe('example.com');
+ expect(getWebAuthnRequestRpId('create', { origin: 'https://a.example.com', publicKey: {} })).toBeUndefined();
+ expect(getWebAuthnRequestRpId('get', { origin: 'https://a.example.com' })).toBeUndefined();
});
it('rejects a forged origin in create requests', () => {
@@ -118,18 +112,26 @@ describe('WebAuthnInterceptor request validation', () => {
},
challenge: 'Y2hhbGxlbmdl',
},
- }, 'https://evil.example', 'evil.example')).toBe(false);
+ }, 'https://evil.example')).toBe(false);
});
- it('rejects a forged RP ID in get requests even when origin is honest', () => {
+ it('leaves the RP ID decision to the background', () => {
+ expect(validateWebAuthnEventDetail('get', {
+ requestId: 'request-1',
+ origin: 'https://twitter.com',
+ publicKey: {
+ challenge: 'Y2hhbGxlbmdl',
+ rpId: 'x.com',
+ },
+ }, 'https://twitter.com')).toBe(true);
expect(validateWebAuthnEventDetail('get', {
requestId: 'request-1',
- origin: 'https://evil.example',
+ origin: 'https://twitter.com',
publicKey: {
challenge: 'Y2hhbGxlbmdl',
- rpId: 'accounts.example.com',
+ rpId: 42,
},
- }, 'https://evil.example', 'evil.example')).toBe(false);
+ } as unknown as WebAuthnGetEventDetail, 'https://twitter.com')).toBe(false);
});
it('allows get requests without explicit RP ID for the current origin', () => {
@@ -139,7 +141,7 @@ describe('WebAuthnInterceptor request validation', () => {
publicKey: {
challenge: 'Y2hhbGxlbmdl',
},
- }, 'https://login.example.com', 'login.example.com')).toBe(true);
+ }, 'https://login.example.com')).toBe(true);
});
it('clones page event details before validation and forwarding', () => {
@@ -169,7 +171,6 @@ describe('WebAuthnInterceptor request validation', () => {
'get',
clonedDetail,
'https://login.example.com',
- 'login.example.com',
)).toBe(true);
});
@@ -180,7 +181,7 @@ describe('WebAuthnInterceptor request validation', () => {
publicKey: {
challenge: 123,
},
- } as unknown as WebAuthnGetEventDetail, 'https://login.example.com', 'login.example.com')).toBe(false);
+ } as unknown as WebAuthnGetEventDetail, 'https://login.example.com')).toBe(false);
});
it('rejects a background request when sender origin and payload origin differ', () => {
@@ -190,6 +191,6 @@ describe('WebAuthnInterceptor request validation', () => {
challenge: 'Y2hhbGxlbmdl',
rpId: 'victim.example.com',
},
- }, 'https://attacker.example.com', 'attacker.example.com')).toBe(false);
+ }, 'https://attacker.example.com')).toBe(false);
});
});
diff --git a/apps/browser-extension/src/utils/passkey/RelyingPartyValidation.ts b/apps/browser-extension/src/utils/passkey/RelyingPartyValidation.ts
new file mode 100644
index 000000000..eec26e577
--- /dev/null
+++ b/apps/browser-extension/src/utils/passkey/RelyingPartyValidation.ts
@@ -0,0 +1,168 @@
+import { isRelatedOriginAllowed, isRpIdAllowedForHost } from '@aliasvault/client/rust/RustCore';
+
+const CACHE_TTL_MS = 5 * 60 * 1000;
+const FAILED_FETCH_TTL_MS = 15 * 1000;
+const FETCH_TIMEOUT_MS = 5000;
+const MAX_RESPONSE_BYTES = 64 * 1024;
+const MAX_CACHE_ENTRIES = 100;
+const relatedOriginsCache = new Map<string, { origins: string[]; expiresAt: number }>();
+
+/**
+ * Returns whether a page may use `rpId` as its WebAuthn RP ID.
+ * @param rpId - Claimed RP ID.
+ * @param callerOrigin - Origin of the requesting page.
+ * @param callerHost - Hostname of the requesting page.
+ * @returns True if the RP ID is allowed.
+ */
+export async function isRpIdAllowedForCaller(rpId: string, callerOrigin: string, callerHost: string): Promise<boolean> {
+ if (await isRpIdAllowedForHost(rpId, callerHost)) {
+ return true;
+ }
+
+ const origins = await getRelatedOrigins(rpId);
+ return origins.length > 0 && await isRelatedOriginAllowed(callerOrigin, origins);
+}
+
+/**
+ * Origins listed in `/.well-known/webauthn` for `rpId`, or an empty list.
+ * @param rpId - Claimed RP ID.
+ * @returns Normalized origins.
+ */
+async function getRelatedOrigins(rpId: string): Promise<string[]> {
+ const url = getWellKnownUrl(rpId);
+ if (!url) {
+ return [];
+ }
+
+ const cached = relatedOriginsCache.get(url.hostname);
+ if (cached && cached.expiresAt > Date.now()) {
+ return cached.origins;
+ }
+
+ const origins = await fetchRelatedOrigins(url);
+ const ttl = origins === null ? FAILED_FETCH_TTL_MS : CACHE_TTL_MS;
+ relatedOriginsCache.delete(url.hostname);
+ relatedOriginsCache.set(url.hostname, { origins: origins ?? [], expiresAt: Date.now() + ttl });
+ if (relatedOriginsCache.size > MAX_CACHE_ENTRIES) {
+ relatedOriginsCache.delete(relatedOriginsCache.keys().next().value as string);
+ }
+ return origins ?? [];
+}
+
+/**
+ * Well-known WebAuthn URL for `rpId`, or null if `rpId` is not a domain name.
+ * @param rpId - Claimed RP ID.
+ * @returns The URL, or null.
+ */
+function getWellKnownUrl(rpId: string): URL | null {
+ const host = rpId.trim().toLowerCase();
+ if (!/^[a-z0-9-]+(\.[a-z0-9-]+)+\.?$/.test(host) || /^[\d.]+$/.test(host)) {
+ return null;
+ }
+
+ try {
+ const url = new URL(`https://${host}/.well-known/webauthn`);
+ return url.hostname === host && url.port === '' ? url : null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Fetches related origins from `url`.
+ * @param url - Well-known WebAuthn URL.
+ * @returns Normalized origins, empty when the RP has no valid list, or null when the fetch failed.
+ */
+async function fetchRelatedOrigins(url: URL): Promise<string[] | null> {
+ let response: Response;
+ try {
+ response = await fetch(url, {
+ credentials: 'omit',
+ redirect: 'error',
+ referrerPolicy: 'no-referrer',
+ cache: 'no-store',
+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
+ });
+ } catch {
+ return null;
+ }
+
+ if (response.status >= 500) {
+ return null;
+ }
+
+ const contentType = response.headers.get('content-type')?.split(';')[0].trim().toLowerCase();
+ const contentLength = Number(response.headers.get('content-length') ?? 0);
+ if (response.status !== 200 || contentType !== 'application/json' || contentLength > MAX_RESPONSE_BYTES) {
+ await response.body?.cancel().catch(() => {});
+ return [];
+ }
+
+ let text: string | null;
+ try {
+ text = await readLimitedText(response);
+ } catch {
+ return null;
+ }
+ if (text === null) {
+ return [];
+ }
+
+ try {
+ const origins: unknown = (JSON.parse(text) as { origins?: unknown })?.origins;
+ return Array.isArray(origins) ? origins.flatMap(normalizeOrigin) : [];
+ } catch {
+ return [];
+ }
+}
+
+/**
+ * Reads the response body as text, stopping as soon as it grows past `MAX_RESPONSE_BYTES`.
+ * @param response - The response to read.
+ * @returns The body, or null when it is too large.
+ */
+async function readLimitedText(response: Response): Promise<string | null> {
+ if (!response.body) {
+ return '';
+ }
+
+ const reader = response.body.getReader();
+ const chunks: Uint8Array[] = [];
+ let size = 0;
+ for (;;) {
+ const { done, value } = await reader.read();
+ if (done) {
+ break;
+ }
+ size += value.byteLength;
+ if (size > MAX_RESPONSE_BYTES) {
+ await reader.cancel().catch(() => {});
+ return null;
+ }
+ chunks.push(value);
+ }
+
+ const bytes = new Uint8Array(size);
+ let offset = 0;
+ for (const chunk of chunks) {
+ bytes.set(chunk, offset);
+ offset += chunk.byteLength;
+ }
+ return new TextDecoder().decode(bytes);
+}
+
+/**
+ * The serialized origin of an entry in the `origins` list, as a list of zero or one.
+ * @param origin - Entry from the list.
+ * @returns The origin, or an empty list when the entry is not a URL.
+ */
+function normalizeOrigin(origin: unknown): string[] {
+ if (typeof origin !== 'string') {
+ return [];
+ }
+ try {
+ return [new URL(origin).origin];
+ } catch {
+ return [];
+ }
+}
diff --git a/apps/browser-extension/src/utils/passkey/WebAuthnRequestValidation.ts b/apps/browser-extension/src/utils/passkey/WebAuthnRequestValidation.ts
index d63f2f229..b0dd237e7 100644
--- a/apps/browser-extension/src/utils/passkey/WebAuthnRequestValidation.ts
+++ b/apps/browser-extension/src/utils/passkey/WebAuthnRequestValidation.ts
@@ -8,22 +8,6 @@ export type WebAuthnBridgeRequest = {
publicKey?: unknown;
};
-/**
- * Normalize a host or RP ID for WebAuthn comparison.
- */
-function normalizeWebAuthnHost(value: string | undefined): string | null {
- if (!value) {
- return null;
- }
-
- const normalized = value.trim().toLowerCase().replace(/\.$/, '');
- if (!normalized || normalized.includes('/') || normalized.includes(':')) {
- return null;
- }
-
- return normalized;
-}
-
/**
* Type guard that narrows an unknown value to a non-null object.
*/
@@ -32,19 +16,16 @@ function isObject(value: unknown): value is Record<string, unknown> {
}
/**
- * Check whether an RP ID is valid for the current origin host.
- * WebAuthn allows the RP ID to be the current host or a parent domain.
- * This prevents a page from asking AliasVault to sign for another RP.
+ * The RP ID a WebAuthn request names, or undefined when it names none (the RP ID then defaults to the host).
*/
-export function isRpIdAllowedForHost(rpId: string | undefined, host: string): boolean {
- const normalizedHost = normalizeWebAuthnHost(host);
- const normalizedRpId = normalizeWebAuthnHost(rpId);
-
- if (!normalizedHost || !normalizedRpId) {
- return false;
+export function getWebAuthnRequestRpId(type: WebAuthnRequestType, request: WebAuthnBridgeRequest | undefined): unknown {
+ if (!isObject(request) || !isObject(request.publicKey)) {
+ return undefined;
}
-
- return normalizedHost === normalizedRpId || normalizedHost.endsWith(`.${normalizedRpId}`);
+ if (type === 'create') {
+ return isObject(request.publicKey.rp) ? request.publicKey.rp.id : undefined;
+ }
+ return request.publicKey.rpId;
}
/**
@@ -65,13 +46,12 @@ export function cloneWebAuthnEventDetail<T extends WebAuthnBridgeDetail>(detail:
}
/**
- * Validate a WebAuthn request before forwarding it to the passkey signing flow.
+ * Validate the shape and origin of a WebAuthn request. The RP ID itself is checked in the background.
*/
export function validateWebAuthnRequest(
type: WebAuthnRequestType,
request: WebAuthnBridgeRequest | undefined,
expectedOrigin: string,
- currentHost: string,
): boolean {
if (
!isObject(request) ||
@@ -99,7 +79,7 @@ export function validateWebAuthnRequest(
}
const rpId = isObject(rp) ? rp.id : undefined;
- return rpId === undefined || (typeof rpId === 'string' && isRpIdAllowedForHost(rpId, currentHost));
+ return rpId === undefined || typeof rpId === 'string';
}
const publicKey = request.publicKey;
@@ -108,7 +88,7 @@ export function validateWebAuthnRequest(
}
const rpId = publicKey.rpId;
- return rpId === undefined || (typeof rpId === 'string' && isRpIdAllowedForHost(rpId, currentHost));
+ return rpId === undefined || typeof rpId === 'string';
}
/**
@@ -120,10 +100,9 @@ export function validateWebAuthnEventDetail(
type: WebAuthnRequestType,
detail: WebAuthnBridgeDetail | undefined,
expectedOrigin: string,
- currentHost: string,
): detail is WebAuthnBridgeDetail {
return (
typeof detail?.requestId === 'string' &&
- validateWebAuthnRequest(type, detail, expectedOrigin, currentHost)
+ validateWebAuthnRequest(type, detail, expectedOrigin)
);
}
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/OriginVerifier.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/OriginVerifier.kt
index ce71c3bf1..4141c4361 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/OriginVerifier.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/OriginVerifier.kt
@@ -5,10 +5,16 @@ import android.util.Base64
import android.util.Log
import androidx.annotation.RequiresApi
import androidx.credentials.provider.CallingAppInfo
+import net.aliasvault.app.rustcore.JnaInitializer
import org.json.JSONArray
+import org.json.JSONObject
+import uniffi.aliasvault_core.isRelatedOriginAllowed
+import uniffi.aliasvault_core.isRpIdAllowedForHost
import java.io.BufferedReader
+import java.io.ByteArrayOutputStream
import java.io.InputStreamReader
import java.net.HttpURLConnection
+import java.net.URI
import java.net.URL
import java.security.MessageDigest
@@ -25,6 +31,9 @@ class OriginVerifier {
companion object {
private const val TAG = "OriginVerifier"
+ private const val MAX_RELATED_ORIGINS_BYTES = 64 * 1024
+ private val RP_ID_HOST_REGEX = Regex("^[a-z0-9-]+(\\.[a-z0-9-]+)+\\.?$")
+
/**
* Privileged app allowlist for CallingAppInfo.getOrigin().
* Includes major browsers trusted to make requests on behalf of web origins.
@@ -1137,24 +1146,88 @@ class OriginVerifier {
}
/**
- * Verify that an origin is valid for the given RP ID.
- * The origin must be https:// and the host must equal or be a subdomain of the RP ID.
+ * Verify that an https origin may use the given RP ID: its own host, a parent domain that is not a
+ * public suffix, or an RP that lists the origin in its /.well-known/webauthn file (related origins).
*/
private fun isOriginValidForRpId(origin: String, rpId: String): Boolean {
- val originHost = try {
- val url = URL(origin)
- if (url.protocol != "https") {
- Log.w(TAG, "Origin is not HTTPS: $origin")
- return false
- }
- url.host.lowercase()
+ val url = try {
+ URL(origin)
} catch (e: Exception) {
Log.w(TAG, "Invalid origin URL: $origin", e)
return false
}
+ if (url.protocol != "https") {
+ Log.w(TAG, "Origin is not HTTPS: $origin")
+ return false
+ }
+
+ JnaInitializer.ensureInitialized()
+ if (isRpIdAllowedForHost(rpId, url.host)) {
+ return true
+ }
+
+ val callerOrigin = normalizeOrigin(origin) ?: return false
+ val relatedOrigins = fetchRelatedOrigins(rpId)
+ return relatedOrigins.isNotEmpty() && isRelatedOriginAllowed(callerOrigin, relatedOrigins)
+ }
+
+ /**
+ * Fetch the origins listed in https://<rpId>/.well-known/webauthn, or an empty list on any failure.
+ */
+ private fun fetchRelatedOrigins(rpId: String): List<String> {
+ val host = rpId.trim().lowercase()
+ if (!RP_ID_HOST_REGEX.matches(host) || host.all { it.isDigit() || it == '.' }) {
+ return emptyList()
+ }
+
+ return try {
+ val connection = URL("https://$host/.well-known/webauthn").openConnection() as HttpURLConnection
+ connection.instanceFollowRedirects = false
+ connection.useCaches = false
+ connection.connectTimeout = 5000
+ connection.readTimeout = 5000
+ try {
+ val contentType = connection.contentType?.substringBefore(';')?.trim()?.lowercase()
+ if (connection.responseCode != HttpURLConnection.HTTP_OK || contentType != "application/json" ||
+ connection.contentLengthLong > MAX_RELATED_ORIGINS_BYTES
+ ) {
+ return emptyList()
+ }
+
+ val body = readLimited(connection) ?: return emptyList()
+ val origins = JSONObject(body).optJSONArray("origins") ?: return emptyList()
+ (0 until origins.length()).mapNotNull { i -> origins.optString(i, null)?.let(::normalizeOrigin) }
+ } finally {
+ connection.disconnect()
+ }
+ } catch (e: Exception) {
+ Log.w(TAG, "Related origins lookup failed for $rpId", e)
+ emptyList()
+ }
+ }
+
+ /** Read the response body, or null when it is larger than MAX_RELATED_ORIGINS_BYTES. */
+ private fun readLimited(connection: HttpURLConnection): String? {
+ val output = ByteArrayOutputStream()
+ val buffer = ByteArray(8192)
+ connection.inputStream.use { input ->
+ while (true) {
+ val read = input.read(buffer)
+ if (read < 0) break
+ if (output.size() + read > MAX_RELATED_ORIGINS_BYTES) return null
+ output.write(buffer, 0, read)
+ }
+ }
+ return output.toString(Charsets.UTF_8.name())
+ }
- val rpIdLower = rpId.lowercase()
- return originHost == rpIdLower || originHost.endsWith(".$rpIdLower")
+ /** Serialize an origin as scheme://host[:port], lowercased and without a default port, or null if invalid. */
+ private fun normalizeOrigin(value: String): String? {
+ val uri = runCatching { URI(value) }.getOrNull() ?: return null
+ val scheme = uri.scheme?.lowercase() ?: return null
+ val host = uri.host?.lowercase() ?: return null
+ val defaultPort = if (scheme == "https") 443 else if (scheme == "http") 80 else -1
+ return if (uri.port == -1 || uri.port == defaultPort) "$scheme://$host" else "$scheme://$host:${uri.port}"
}
/**
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/RustCoreDispatcher.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/RustCoreDispatcher.kt
index 56612e989..22211a144 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/RustCoreDispatcher.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/RustCoreDispatcher.kt
@@ -18,6 +18,8 @@ import uniffi.aliasvault_core.getDicewareLanguages
import uniffi.aliasvault_core.getIdentityAgeRanges
import uniffi.aliasvault_core.getIdentityLanguages
import uniffi.aliasvault_core.getSyncableTableNames
+import uniffi.aliasvault_core.isRelatedOriginAllowed
+import uniffi.aliasvault_core.isRpIdAllowedForHost
import uniffi.aliasvault_core.parseEmailSource
import uniffi.aliasvault_core.pruneVaultJson
import uniffi.aliasvault_core.selectFaviconTarget
@@ -53,6 +55,8 @@ object RustCoreDispatcher {
return when (name) {
"extractDomain" -> json(extractDomain(args.string(0)))
"extractRootDomain" -> json(extractRootDomain(args.string(0)))
+ "isRpIdAllowedForHost" -> isRpIdAllowedForHost(args.string(0), args.string(1)).toString()
+ "isRelatedOriginAllowed" -> isRelatedOriginAllowed(args.string(0), args.strings(1)).toString()
"selectFaviconTarget" -> {
val target = selectFaviconTarget(args.strings(0)) ?: return "null"
JSONObject().put("url", target.url).put("source", target.source).toString()
diff --git a/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift b/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift
index 47ddb40c6..bc35a533b 100644
--- a/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift
+++ b/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift
@@ -1572,6 +1572,8 @@ private enum RustCoreDispatcher {
switch name {
case "extractDomain": return try json(RustCoreFramework.extractDomain(url: try args.string(0)))
case "extractRootDomain": return try json(RustCoreFramework.extractRootDomain(domain: try args.string(0)))
+ case "isRpIdAllowedForHost": return try json(RustCoreFramework.isRpIdAllowedForHost(rpId: try args.string(0), host: try args.string(1)))
+ case "isRelatedOriginAllowed": return try json(RustCoreFramework.isRelatedOriginAllowed(callerOrigin: try args.string(0), origins: try args.strings(1)))
case "selectFaviconTarget":
guard let target = RustCoreFramework.selectFaviconTarget(urls: try args.strings(0)) else { return "null" }
return try json(["url": target.url, "source": target.source])
diff --git a/apps/mobile-app/platform/NativeRustCore.ts b/apps/mobile-app/platform/NativeRustCore.ts
index 283ac0b01..2bc91662b 100644
--- a/apps/mobile-app/platform/NativeRustCore.ts
+++ b/apps/mobile-app/platform/NativeRustCore.ts
@@ -38,6 +38,8 @@ export const nativeRustCore: IRustCore = {
extractDomain: (url) => call('extractDomain', url),
extractRootDomain: (domain) => call('extractRootDomain', domain),
+ isRpIdAllowedForHost: (rpId, host) => call('isRpIdAllowedForHost', rpId, host),
+ isRelatedOriginAllowed: (callerOrigin, origins) => call('isRelatedOriginAllowed', callerOrigin, origins),
selectFaviconTarget: (urls) => call('selectFaviconTarget', urls),
filterCredentials: (input) => call('filterCredentialsJson', JSON.stringify(input)),
diff --git a/core/client/src/rust/RustCore.ts b/core/client/src/rust/RustCore.ts
index 8070287a0..dfe15bafe 100644
--- a/core/client/src/rust/RustCore.ts
+++ b/core/client/src/rust/RustCore.ts
@@ -44,6 +44,20 @@ export async function extractRootDomain(domain: string): Promise<string> {
return rustCore().extractRootDomain(domain);
}
+/**
+ * Whether a page on `host` may use `rpId` as its WebAuthn RP ID (the host or a parent that is not a public suffix).
+ */
+export async function isRpIdAllowedForHost(rpId: string, host: string): Promise<boolean> {
+ return rustCore().isRpIdAllowedForHost(rpId, host);
+}
+
+/**
+ * Whether `callerOrigin` is listed in `origins` from an RP's `/.well-known/webauthn` file.
+ */
+export async function isRelatedOriginAllowed(callerOrigin: string, origins: string[]): Promise<boolean> {
+ return rustCore().isRelatedOriginAllowed(callerOrigin, origins);
+}
+
/**
* Read a URL field value as an ordered list, accepting the single-string and multi-value
* shapes a field can hold.
diff --git a/core/client/src/rust/RustCoreBinding.ts b/core/client/src/rust/RustCoreBinding.ts
index 3bf01d109..6b10c1981 100644
--- a/core/client/src/rust/RustCoreBinding.ts
+++ b/core/client/src/rust/RustCoreBinding.ts
@@ -22,6 +22,8 @@ export interface IRustCore {
extractDomain(url: string): Promise<string>;
extractRootDomain(domain: string): Promise<string>;
+ isRpIdAllowedForHost(rpId: string, host: string): Promise<boolean>;
+ isRelatedOriginAllowed(callerOrigin: string, origins: string[]): Promise<boolean>;
selectFaviconTarget(urls: string[]): Promise<FaviconTarget | null>;
filterCredentials(input: FilterCredentialsInput): Promise<FilterCredentialsOutput>;
diff --git a/core/client/src/rust/WasmRustCore.ts b/core/client/src/rust/WasmRustCore.ts
index e4f9648fb..3b7960cb8 100644
--- a/core/client/src/rust/WasmRustCore.ts
+++ b/core/client/src/rust/WasmRustCore.ts
@@ -49,6 +49,8 @@ export function createWasmRustCore(loadWasm: WasmLoader): IRustCore {
extractDomain: (url): Promise<string> => ready(() => core.extractDomain(url)),
extractRootDomain: (domain): Promise<string> => ready(() => core.extractRootDomain(domain)),
+ isRpIdAllowedForHost: (rpId, host): Promise<boolean> => ready(() => core.isRpIdAllowedForHost(rpId, host)),
+ isRelatedOriginAllowed: (callerOrigin, origins): Promise<boolean> => ready(() => core.isRelatedOriginAllowed(callerOrigin, origins)),
selectFaviconTarget: (urls): Promise<FaviconTarget | null> => ready(() => (core.selectFaviconTarget(urls) ?? null) as FaviconTarget | null),
filterCredentials: (input: FilterCredentialsInput): Promise<FilterCredentialsOutput> => ready(() => core.filterCredentials(input) as FilterCredentialsOutput),
diff --git a/core/client/src/transfer/shared/FolderPaths.ts b/core/client/src/transfer/shared/FolderPaths.ts
index 641f60f7d..b6a9db191 100644
--- a/core/client/src/transfer/shared/FolderPaths.ts
+++ b/core/client/src/transfer/shared/FolderPaths.ts
@@ -34,7 +34,7 @@ export function buildFolderPath(folderId: string | null | undefined, foldersById
}
/**
- * Split a folder path into its folder names, at most five levels deep: "Root/Business/Banking" results in ["Root", "Business", "Banking"].
+ * Split a folder path into its folder names, at most ten levels deep: "Root/Business/Banking" results in ["Root", "Business", "Banking"].
* @param folderPath - The folder path, with "/" or "\" separators
* @returns The folder names in order, empty when there are none
*/
diff --git a/core/rust/src/bindings/uniffi_api.rs b/core/rust/src/bindings/uniffi_api.rs
index 34b4773ec..8f1c412eb 100644
--- a/core/rust/src/bindings/uniffi_api.rs
+++ b/core/rust/src/bindings/uniffi_api.rs
@@ -44,6 +44,18 @@ pub fn extract_root_domain(domain: String) -> String {
crate::credential_matcher::extract_root_domain(&domain)
}
+/// Whether a page on `host` may use `rp_id` as its WebAuthn relying party id: the host or a parent that is not a public suffix.
+#[uniffi::export]
+pub fn is_rp_id_allowed_for_host(rp_id: String, host: String) -> bool {
+ crate::credential_matcher::is_rp_id_allowed_for_host(&rp_id, &host)
+}
+
+/// Whether `caller_origin` is listed in the `origins` of an rp id's `/.well-known/webauthn` file (WebAuthn related origins).
+#[uniffi::export]
+pub fn is_related_origin_allowed(caller_origin: String, origins: Vec<String>) -> bool {
+ crate::credential_matcher::is_related_origin_allowed(&caller_origin, &origins)
+}
+
// ═══════════════════════════════════════════════════════════════════════════════
// Favicon Functions
// ═══════════════════════════════════════════════════════════════════════════════
diff --git a/core/rust/src/bindings/wasm.rs b/core/rust/src/bindings/wasm.rs
index 52597f529..f1f543eca 100644
--- a/core/rust/src/bindings/wasm.rs
+++ b/core/rust/src/bindings/wasm.rs
@@ -104,6 +104,18 @@ pub fn extract_root_domain_js(domain: &str) -> String {
crate::credential_matcher::extract_root_domain(domain)
}
+/// Whether a page on `host` may use `rpId` as its WebAuthn relying party id: the host or a parent that is not a public suffix.
+#[wasm_bindgen(js_name = isRpIdAllowedForHost)]
+pub fn is_rp_id_allowed_for_host_js(rp_id: &str, host: &str) -> bool {
+ crate::credential_matcher::is_rp_id_allowed_for_host(rp_id, host)
+}
+
+/// Whether `callerOrigin` is listed in the `origins` of an rp id's `/.well-known/webauthn` file (WebAuthn related origins).
+#[wasm_bindgen(js_name = isRelatedOriginAllowed)]
+pub fn is_related_origin_allowed_js(caller_origin: &str, origins: Vec<String>) -> bool {
+ crate::credential_matcher::is_related_origin_allowed(caller_origin, &origins)
+}
+
// ═══════════════════════════════════════════════════════════════════════════════
// Favicon WASM Bindings
// ═══════════════════════════════════════════════════════════════════════════════
diff --git a/core/rust/src/credential_matcher/domain.rs b/core/rust/src/credential_matcher/domain.rs
index 8bfec459f..c1092e954 100644
--- a/core/rust/src/credential_matcher/domain.rs
+++ b/core/rust/src/credential_matcher/domain.rs
@@ -182,6 +182,75 @@ pub fn domains_match(domain1: &str, domain2: &str) -> bool {
}
}
+/// Check if a WebAuthn rpId is allowed for a host based on the Public Suffix List.
+pub fn is_rp_id_allowed_for_host(rp_id: &str, host: &str) -> bool {
+ let (Some(rp_id), Some(host)) = (normalize_rp_host(rp_id), normalize_rp_host(host)) else {
+ return false;
+ };
+
+ if rp_id == host {
+ return true;
+ }
+ if is_ip_literal(&rp_id) || is_ip_literal(&host) || !host.ends_with(&format!(".{rp_id}")) {
+ return false;
+ }
+
+ match (public_suffix::registrable_domain(&rp_id), public_suffix::registrable_domain(&host)) {
+ (Some(_), Some(host_root)) => rp_id == host_root || rp_id.ends_with(&format!(".{host_root}")),
+ _ => false,
+ }
+}
+
+/// At most this many distinct registrable domain labels are read from a `/.well-known/webauthn` file.
+const MAX_RELATED_ORIGIN_LABELS: usize = 10;
+
+/// WebAuthn related origins validation.
+pub fn is_related_origin_allowed(caller_origin: &str, origins: &[String]) -> bool {
+ let mut labels_seen: Vec<&str> = Vec::new();
+ for origin in origins {
+ let Some(host) = origin_host(origin) else { continue };
+ if is_ip_literal(host) {
+ continue;
+ }
+ let Some(label) = public_suffix::registrable_domain(host).and_then(|domain| domain.split('.').next()) else { continue };
+
+ let seen = labels_seen.contains(&label);
+ if labels_seen.len() >= MAX_RELATED_ORIGIN_LABELS && !seen {
+ continue;
+ }
+ if origin == caller_origin {
+ return true;
+ }
+ if !seen {
+ labels_seen.push(label);
+ }
+ }
+ false
+}
+
+/// The host of a serialized web origin ("https://login.example.com:8443" gives "login.example.com").
+fn origin_host(origin: &str) -> Option<&str> {
+ let (scheme, authority) = origin.split_once("://")?;
+ if !is_web_scheme(scheme) || authority.is_empty() || authority.contains(['/', '?', '#', '@']) {
+ return None;
+ }
+ let host = match authority.rsplit_once(':') {
+ Some((host, port)) if !host.ends_with(':') && port.chars().all(|c| c.is_ascii_digit()) => host,
+ _ => authority,
+ };
+ (!host.is_empty()).then_some(host)
+}
+
+/// A host or rp id lowercased and without its trailing dot, or None when empty or holding a port or path.
+fn normalize_rp_host(value: &str) -> Option<String> {
+ let lowered = value.trim().to_ascii_lowercase();
+ let normalized = lowered.strip_suffix('.').unwrap_or(&lowered);
+ if normalized.is_empty() || normalized.contains(['/', ':']) {
+ return None;
+ }
+ Some(normalized.to_string())
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -322,6 +391,17 @@ mod tests {
assert_eq!(extract_root_domain("github.io"), "github.io");
assert_eq!(extract_root_domain("localhost"), "localhost");
assert_eq!(extract_root_domain("plex"), "plex");
+
+ // A trailing dot never reduces a domain to its TLD: "bank.com." and "evil.com." must not share "com.".
+ assert_eq!(extract_root_domain("bank.com."), "bank.com");
+ assert_eq!(extract_root_domain("login.bank.com."), "bank.com");
+ assert_eq!(extract_root_domain("victim.vercel.app."), "victim.vercel.app");
+ assert_eq!(extract_root_domain("com."), "com.");
+
+ // A malformed domain has no root domain and is returned as-is.
+ assert_eq!(extract_root_domain(".com"), ".com");
+ assert_eq!(extract_root_domain("a..b.com"), "a..b.com");
+ assert_eq!(extract_root_domain(".."), "..");
}
#[test]
@@ -330,6 +410,57 @@ mod tests {
assert_eq!(extract_root_domain("10.0.0.1"), "10.0.0.1");
assert_eq!(extract_root_domain("::1"), "::1");
assert_eq!(extract_root_domain("[2001:db8::1]"), "[2001:db8::1]");
+ assert_eq!(extract_root_domain("192.168.1.5."), "192.168.1.5.");
+ }
+
+ #[test]
+ fn test_is_related_origin_allowed() {
+ let origins = |list: &[&str]| list.iter().map(|o| o.to_string()).collect::<Vec<_>>();
+
+ let x = origins(&["https://twitter.com", "https://x.com", "https://mobile.twitter.com:8443"]);
+ assert!(is_related_origin_allowed("https://twitter.com", &x));
+ assert!(is_related_origin_allowed("https://mobile.twitter.com:8443", &x));
+ assert!(!is_related_origin_allowed("https://mobile.twitter.com", &x));
+ assert!(!is_related_origin_allowed("http://twitter.com", &x));
+ assert!(!is_related_origin_allowed("https://evil.com", &x));
+ assert!(!is_related_origin_allowed("https://twitter.com", &[]));
+
+ // Only the first MAX_RELATED_ORIGIN_LABELS distinct labels count; origins sharing a counted label stay reachable.
+ let mut many: Vec<String> = (0..=MAX_RELATED_ORIGIN_LABELS).map(|i| format!("https://site{i}.com")).collect();
+ many.extend(origins(&["https://shop.site0.co.uk", "https://www.site1.com"]));
+ assert!(is_related_origin_allowed(&format!("https://site{}.com", MAX_RELATED_ORIGIN_LABELS - 1), &many));
+ assert!(!is_related_origin_allowed(&format!("https://site{MAX_RELATED_ORIGIN_LABELS}.com"), &many));
+ assert!(is_related_origin_allowed("https://shop.site0.co.uk", &many));
+ assert!(is_related_origin_allowed("https://www.site1.com", &many));
+
+ // Entries without a registrable domain neither match nor use up a label.
+ let mut skipped = origins(&["https://vercel.app", "https://192.168.1.5", "https://localhost", "null"]);
+ skipped.extend((1..=MAX_RELATED_ORIGIN_LABELS).map(|i| format!("https://{i}.com")));
+ assert!(!is_related_origin_allowed("https://vercel.app", &skipped));
+ assert!(!is_related_origin_allowed("https://192.168.1.5", &skipped));
+ assert!(!is_related_origin_allowed("null", &skipped));
+ assert!(is_related_origin_allowed(&format!("https://{MAX_RELATED_ORIGIN_LABELS}.com"), &skipped));
+ }
+
+ #[test]
+ fn test_is_rp_id_allowed_for_host() {
+ // The host itself and parent domains below the public suffix.
+ assert!(is_rp_id_allowed_for_host("example.com", "login.example.com"));
+ assert!(is_rp_id_allowed_for_host("Example.COM.", "login.example.com"));
+ assert!(is_rp_id_allowed_for_host("myproject.vercel.app", "preview.myproject.vercel.app"));
+ assert!(is_rp_id_allowed_for_host("github.io", "github.io"));
+
+ // Public suffixes, siblings and lookalikes.
+ assert!(!is_rp_id_allowed_for_host("vercel.app", "evil.vercel.app"));
+ assert!(!is_rp_id_allowed_for_host("district.sch.uk", "myschool.district.sch.uk"));
+ assert!(!is_rp_id_allowed_for_host("accounts.example.com", "evil.example.com"));
+ assert!(!is_rp_id_allowed_for_host("example.com", "myexample.com"));
+
+ // IP addresses only as themselves, malformed input never.
+ assert!(is_rp_id_allowed_for_host("192.168.1.5", "192.168.1.5"));
+ assert!(!is_rp_id_allowed_for_host("1.5", "192.168.1.5"));
+ assert!(!is_rp_id_allowed_for_host("", "example.com"));
+ assert!(!is_rp_id_allowed_for_host("example.com:443", "example.com"));
}
#[test]
diff --git a/core/rust/src/credential_matcher/mod.rs b/core/rust/src/credential_matcher/mod.rs
index 2d3a66217..1e9eba7f1 100644
--- a/core/rust/src/credential_matcher/mod.rs
+++ b/core/rust/src/credential_matcher/mod.rs
@@ -16,7 +16,7 @@ mod stop_words;
use serde::{Deserialize, Serialize};
-pub use domain::{extract_domain, extract_domain_with_port, extract_root_domain, DomainWithPort};
+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 stop_words::STOP_WORD_SET;