Skip to content
Merged
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
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,9 @@ Generate a persistent RSA key with `just generate-key /absolute/path/key.pem` (u
OpenSSL CLI; piqueld generates its own, see `infra/README.md`).
Keep the same key and ID across restarts. Replacing the only configured key
invalidates issued tokens; overlapping signing-key rotation is not implemented.
It also changes the decoy passkey IDs that username sign-in returns for unknown
usernames, while real accounts keep theirs, so comparing responses from before and
after a replacement reveals which usernames exist.

Provider callback URLs are `/login/github/callback` and `/login/google/callback`
on the auth origin. GitHub uses `read:user user:email`; Google uses `openid email profile`.
Expand Down
61 changes: 43 additions & 18 deletions apps/auth-service/src/config.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
//! Validated startup configuration, grouped by application.

use crate::passkey::DecoyKey;
use ipnet::IpNet;
use piquel_auth_protocol::{Provider, oauth::Scope};
use piquel_common::{ConfigurationError, Origin, PublicUrl, SecretReference, Variable};
use piquel_common::{
ConfigurationError, Origin, PublicUrl, SecretBytes, SecretReference, Variable,
};
use piquel_crypto::{Digest, Rs256Key, Secret};
use piquel_repository::{BootstrapOidcClient, DatabaseConfig};
use serde::Deserialize;
Expand All @@ -21,6 +24,8 @@ const MAX_SIGNING_KEY_ID_LENGTH: usize = 128;
const DEFAULT_SIGNING_KEY_ID: &str = "primary";
/// Separates refresh digests from every other use of the persistent PEM bytes.
const REFRESH_DIGEST_CONTEXT: &[u8] = b"piquel-refresh-token-digest-v1";
/// Separates the passkey decoy key from every other use of the persistent PEM bytes.
const PASSKEY_DECOY_CONTEXT: &[u8] = b"piquel-passkey-decoy-credential-v1";
/// Default number of pooled authentication connections.
const DATABASE_POOL_SIZE: u32 = 10;
/// Maximum startup wait for a pooled database connection.
Expand Down Expand Up @@ -60,17 +65,27 @@ pub(crate) struct PasskeyConfig {
pub origin: Origin,
/// Registration admission policy.
pub invite_required: bool,
/// Domain-separated key for the stable decoy credentials of unknown usernames.
pub decoy_key: DecoyKey,
}
impl PasskeyConfig {
/// Reads the passkey policy and validates that the origin has a domain RP ID.
pub(crate) fn from_environment(origin: &Origin) -> Result<Self, ConfigurationError> {
/// Reads the passkey policy, validates that the origin has a domain RP ID and
/// derives the decoy key from the persistent PEM key.
pub(crate) fn from_environment(
origin: &Origin,
persistent_key: &SecretBytes,
) -> Result<Self, ConfigurationError> {
if !matches!(origin.as_url().host(), Some(url::Host::Domain(_))) {
return Err(PUBLIC_BASE_URL
.invalid("must use a domain name for WebAuthn, e.g. https://auth.piquel.fr"));
}
Ok(Self {
origin: origin.clone(),
invite_required: INVITE_REQUIRED.flag(true)?,
decoy_key: DecoyKey::new(AuthConfig::derive_key(
persistent_key,
PASSKEY_DECOY_CONTEXT,
)?),
})
}
}
Expand Down Expand Up @@ -169,15 +184,11 @@ pub(crate) struct OidcConfig {
}

impl OidcConfig {
/// Loads the required persistent key and statically reviewed clients.
pub(crate) fn from_environment(origin: &Origin) -> Result<Self, ConfigurationError> {
let reference: SecretReference = KEY_PROVIDER.parse()?;
let secret = reference.resolve().map_err(|source| {
KEY_PROVIDER.error(
"must resolve to an RSA private PEM key of at least 2048 bits",
source,
)
})?;
/// Parses the persistent signing key and loads statically reviewed clients.
pub(crate) fn from_environment(
origin: &Origin,
secret: &SecretBytes,
) -> Result<Self, ConfigurationError> {
let pem = secret
.utf8()
.map_err(|source| KEY_PROVIDER.error("must contain UTF-8 PEM", source))?;
Expand All @@ -198,10 +209,7 @@ impl OidcConfig {
source,
)
})?;
let refresh_key =
Secret::derive(secret.expose_secret(), REFRESH_DIGEST_CONTEXT).map_err(|source| {
KEY_PROVIDER.error("could not derive the refresh-token key", source)
})?;
let refresh_key = AuthConfig::derive_key(secret, REFRESH_DIGEST_CONTEXT)?;
let clients = Self::clients()?;
let public_redirects = clients
.iter()
Expand Down Expand Up @@ -392,15 +400,32 @@ impl AuthConfig {
pub fn from_environment() -> Result<Self, ConfigurationError> {
let origin: Origin = PUBLIC_BASE_URL.parse()?;
let settings_url: PublicUrl = SETTINGS_URL.parse_or(DEFAULT_SETTINGS_URL)?;
let persistent_key: SecretReference = KEY_PROVIDER.parse()?;
let persistent_key = persistent_key.resolve().map_err(|source| {
KEY_PROVIDER.error(
"must resolve to an RSA private PEM key of at least 2048 bits",
source,
)
})?;
Ok(Self {
public_listener: PUBLIC_LISTENER.parse_or(DEFAULT_PUBLIC_LISTENER)?,
passkey: PasskeyConfig::from_environment(&origin)?,
passkey: PasskeyConfig::from_environment(&origin, &persistent_key)?,
federation: FederationConfig::from_environment(&origin, &settings_url)?,
oidc: OidcConfig::from_environment(&origin)?,
oidc: OidcConfig::from_environment(&origin, &persistent_key)?,
trusted_proxies: Self::trusted_proxies()?,
})
}

/// Derives a service key from the persistent PEM bytes under its own `context`,
/// so each key is stable across restarts and replicas but independent of the others.
fn derive_key(
persistent_key: &SecretBytes,
context: &[u8],
) -> Result<Secret, ConfigurationError> {
Secret::derive(persistent_key.expose_secret(), context)
.map_err(|source| KEY_PROVIDER.error("could not derive a key from the PEM key", source))
}

/// Uses the operator override, then piqueld's ingress ranges, then no trusted peers.
fn trusted_proxies() -> Result<Vec<IpNet>, ConfigurationError> {
let (variable, value) = if let Some(value) = TRUSTED_PROXIES.optional()? {
Expand Down
12 changes: 9 additions & 3 deletions apps/auth-service/src/passkey/ceremonies.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,9 @@ pub(super) enum Ceremony {
Register(RegistrationCeremony),
/// Username-based authentication.
Login(LoginCeremony),
/// Username-based authentication for a username without an active account or
/// passkey. It holds no `WebAuthn` state, so its finish can never succeed.
Decoy,
/// Discoverable account-picker authentication.
Discover(DiscoverCeremony),
/// Settings authorization for the initiating session.
Expand All @@ -97,7 +100,7 @@ impl Ceremony {
pub(super) const fn kind(&self) -> CeremonyKind {
match self {
Self::Register(_) => CeremonyKind::Registration,
Self::Login(_) | Self::Discover(_) => CeremonyKind::Authentication,
Self::Login(_) | Self::Decoy | Self::Discover(_) => CeremonyKind::Authentication,
Self::Manage(_) => CeremonyKind::PurposeAuthentication,
Self::Enroll(_) => CeremonyKind::Enrollment,
}
Expand All @@ -106,7 +109,7 @@ impl Ceremony {
/// Derives the existing-account binding; signup has no account row yet.
const fn user_id(&self) -> Option<UserId> {
match self {
Self::Register(_) | Self::Discover(_) => None,
Self::Register(_) | Self::Decoy | Self::Discover(_) => None,
Self::Login(state) => Some(state.user_id),
Self::Manage(state) => Some(state.user_id),
Self::Enroll(state) => Some(state.user_id),
Expand All @@ -116,7 +119,7 @@ impl Ceremony {
/// Derives the initiating-session binding for settings operations.
const fn session_id(&self) -> Option<SessionId> {
match self {
Self::Register(_) | Self::Login(_) | Self::Discover(_) => None,
Self::Register(_) | Self::Login(_) | Self::Decoy | Self::Discover(_) => None,
Self::Manage(state) => Some(state.session_id),
Self::Enroll(state) => Some(state.session_id),
}
Expand Down Expand Up @@ -164,6 +167,8 @@ ceremony_state!(EnrollmentCeremony, Enroll, Enrollment);
pub(super) enum AuthenticationCeremony {
/// Account identified by username before the challenge.
Login(LoginCeremony),
/// Username without an active account or passkey; always rejected.
Decoy,
/// Account identified by the authenticator's response.
Discover(DiscoverCeremony),
}
Expand All @@ -174,6 +179,7 @@ impl CeremonyState for AuthenticationCeremony {
fn extract(ceremony: Ceremony) -> Option<Self> {
match ceremony {
Ceremony::Login(state) => Some(Self::Login(state)),
Ceremony::Decoy => Some(Self::Decoy),
Ceremony::Discover(state) => Some(Self::Discover(state)),
Ceremony::Register(_) | Ceremony::Manage(_) | Ceremony::Enroll(_) => None,
}
Expand Down
111 changes: 111 additions & 0 deletions apps/auth-service/src/passkey/decoy.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
//! Stable decoy credentials, so username sign-in does not reveal which accounts exist.
//!
//! A username without an active account or passkey still receives a challenge listing
//! credentials. They are derived from the username with a server key, so they stay the
//! same across requests, restarts and replicas, as a real account's credentials do.
//! Nobody holds their private keys, and their ceremony fails at finish regardless.

use piquel_crypto::{CryptoError, Digest, Secret};
use webauthn_rs_proto::AllowCredentials;

/// Credential type of every `WebAuthn` descriptor, as webauthn-rs writes it.
const PUBLIC_KEY_CREDENTIAL_TYPE: &str = "public-key";
/// Decoy credential counts, each equally likely: most accounts hold one passkey.
const DECOY_COUNTS: [u8; 4] = [1, 1, 1, 2];
/// Decoy credential ID lengths, each equally likely. Common synced passkeys use 16
/// (such as Google Password Manager) or 20 bytes (iCloud Keychain); others use 32.
/// Decoys hide accounts whose credentials match these shapes, so keep them close to
/// the real mix. No decoy lists transports: webauthn-rs keeps them only from packed or
/// TPM attestation, and browsers replace both with `none`, which passkey registration requests.
const DECOY_ID_LENGTHS: [usize; 3] = [16, 20, 32];
/// Input under a username's key that selects its decoy count and ID lengths. Credential
/// IDs use one-byte inputs instead, so ID bytes are independent of the chosen shape.
const DECOY_SHAPE_INPUT: &[u8] = b"shape";

// Each ID is a prefix of one digest, and the shape digest holds the count byte followed
// by one length byte per credential, so the indexing in `DecoyKey::credentials` is in bounds.
const _: () = {
let mut index = 0;
while index < DECOY_ID_LENGTHS.len() {
assert!(DECOY_ID_LENGTHS[index] <= Digest::LENGTH);
index += 1;
}
index = 0;
while index < DECOY_COUNTS.len() {
assert!((DECOY_COUNTS[index] as usize) < Digest::LENGTH);
index += 1;
}
};

/// HMAC key deriving the decoy credentials of usernames without an active account or
/// passkey. It must be derived from persistent key material, so decoys stay stable.
#[derive(Clone)]
pub(crate) struct DecoyKey(Secret);

impl DecoyKey {
/// Wraps a key reserved for decoy credentials.
pub(crate) const fn new(key: Secret) -> Self {
Self(key)
}

/// Returns the stable `allowCredentials` for `username`.
///
/// # Errors
///
/// Returns [`CryptoError`] if the HMAC provider fails.
pub(crate) fn credentials(&self, username: &str) -> Result<Vec<AllowCredentials>, CryptoError> {
let key = Secret::derive(self.0.as_bytes(), username.as_bytes())?;
let shape = Digest::hmac(key.as_bytes(), DECOY_SHAPE_INPUT)?;
let [count, lengths @ ..] = shape.as_bytes();
(0..DECOY_COUNTS[usize::from(*count) % DECOY_COUNTS.len()])
.map(|index| {
let length = DECOY_ID_LENGTHS
[usize::from(lengths[usize::from(index)]) % DECOY_ID_LENGTHS.len()];
Ok(AllowCredentials {
type_: PUBLIC_KEY_CREDENTIAL_TYPE.into(),
id: Digest::hmac(key.as_bytes(), &[index])?.as_bytes()[..length]
.to_vec()
.into(),
transports: None,
})
})
.collect()
}
}

/// Decoy shapes without a database.
#[cfg(test)]
mod tests {
use super::{DECOY_COUNTS, DECOY_ID_LENGTHS, DecoyKey, PUBLIC_KEY_CREDENTIAL_TYPE};
use piquel_crypto::Secret;
use std::collections::HashSet;
use webauthn_rs_proto::AllowCredentials;

/// Across many usernames, decoys use every configured count and ID length and
/// nothing else, and a username always gets the same decoys.
#[test]
fn decoys_use_exactly_the_configured_shapes() {
let key = DecoyKey::new(Secret::generate().expect("key"));
let (mut counts, mut lengths) = (HashSet::new(), HashSet::new());
for index in 0..256 {
let username = format!("user_{index}");
let ids = |decoys: &[AllowCredentials]| {
decoys
.iter()
.map(|decoy| decoy.id.clone())
.collect::<Vec<_>>()
};
let decoys = key.credentials(&username).expect("decoys");
let repeated = key.credentials(&username).expect("decoys");
assert_eq!(ids(&decoys), ids(&repeated));
counts.insert(u8::try_from(decoys.len()).expect("count"));
for decoy in decoys {
assert_eq!(decoy.type_, PUBLIC_KEY_CREDENTIAL_TYPE);
assert!(decoy.transports.is_none());
lengths.insert(decoy.id.len());
}
}
assert_eq!(counts, DECOY_COUNTS.into_iter().collect());
assert_eq!(lengths, DECOY_ID_LENGTHS.into_iter().collect());
}
}
15 changes: 6 additions & 9 deletions apps/auth-service/src/passkey/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ pub(super) enum PasskeyError {
/// A discoverable credential returned an invalid account handle.
#[error("invalid discoverable account handle")]
InvalidUserHandle(#[source] InvalidValue),
/// Username-based authentication must not reveal account availability.
/// A decoy ceremony finished: the username has no active account or passkey.
#[error("account unavailable for passkey authentication")]
AccountUnavailable,
/// The account, or the credential it signed with, was disabled or removed.
Expand Down Expand Up @@ -104,7 +104,7 @@ pub(super) enum PasskeyError {
/// Creating a browser session failed.
#[error(transparent)]
Session(#[from] SessionError),
/// Generating a browser-binding secret failed.
/// Generating a browser-binding secret or deriving decoy credentials failed.
#[error(transparent)]
Crypto(#[from] CryptoError),
}
Expand Down Expand Up @@ -158,18 +158,15 @@ impl From<PasskeyError> for ApiError {
error @ PasskeyError::SessionChanged => error
.rejected("Your session changed during this passkey request. Please start again."),
// WebAuthn's reasons stay in the logs: some fail before possession is proven,
// so showing them would reveal which credentials an account has.
error @ PasskeyError::Webauthn(_) => {
// so showing them would reveal which credentials an account has. A decoy
// ceremony gets the same answer as an unregistered passkey, so finishing
// one reveals no more than starting it.
error @ (PasskeyError::Webauthn(_) | PasskeyError::AccountUnavailable) => {
error.rejected("This passkey could not be verified. Please try again.")
}
error @ PasskeyError::InvalidUserHandle(_) => {
error.rejected("This passkey does not belong to a Piquel account.")
}
// The same answer whether the account is missing or has no passkey: the
// username field reveals no more than it must.
error @ PasskeyError::AccountUnavailable => {
error.rejected("No passkey is available for this username.")
}
error @ PasskeyError::UserVerificationRequired => error
.rejected("Your authenticator must verify you with a PIN, fingerprint or face."),
error @ PasskeyError::CounterRegression => error.rejected(
Expand Down
Loading
Loading