1
0
mirror of https://github.com/matrix-org/matrix-authentication-service.git synced 2025-08-07 17:03:01 +03:00

Backend work to support minimum password complexity (#2965)

* config: Add minimum password complexity option

* PasswordManager: add function for checking if complexity is sufficient

* Enforce password complexity on registration, change and recovery

* cli: Use exit code 1 for weak passwords

This seems preferable to exit code 0, but ideally we should choose one
and document it.

* Expose minimum password complexity score over GraphQL
This commit is contained in:
reivilibre
2024-07-11 10:17:39 +01:00
committed by GitHub
parent 569eb07bd6
commit fbc360d1a9
25 changed files with 317 additions and 66 deletions

75
Cargo.lock generated
View File

@@ -762,6 +762,21 @@ dependencies = [
"which", "which",
] ]
[[package]]
name = "bit-set"
version = "0.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0700ddab506f33b20a03b13996eccd309a48e5ff77d0d95926aa0210fb4e95f1"
dependencies = [
"bit-vec",
]
[[package]]
name = "bit-vec"
version = "0.6.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "349f9b6a179ed607305526ca489b34ad0a41aed5f7980fa90eb03160b69598fb"
[[package]] [[package]]
name = "bitflags" name = "bitflags"
version = "1.3.2" version = "1.3.2"
@@ -1555,6 +1570,37 @@ dependencies = [
"serde", "serde",
] ]
[[package]]
name = "derive_builder"
version = "0.20.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0350b5cb0331628a5916d6c5c0b72e97393b8b6b03b47a9284f4e7f5a405ffd7"
dependencies = [
"derive_builder_macro",
]
[[package]]
name = "derive_builder_core"
version = "0.20.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d48cda787f839151732d396ac69e3473923d54312c070ee21e9effcaa8ca0b1d"
dependencies = [
"darling 0.20.9",
"proc-macro2",
"quote",
"syn 2.0.68",
]
[[package]]
name = "derive_builder_macro"
version = "0.20.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "206868b8242f27cecce124c19fd88157fbd0dd334df2587f36417bafbc85097b"
dependencies = [
"derive_builder_core",
"syn 2.0.68",
]
[[package]] [[package]]
name = "dialoguer" name = "dialoguer"
version = "0.11.0" version = "0.11.0"
@@ -1773,6 +1819,17 @@ version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649" checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649"
[[package]]
name = "fancy-regex"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "531e46835a22af56d1e3b66f04844bed63158bc094a628bec1d321d9b4c44bf2"
dependencies = [
"bit-set",
"regex-automata 0.4.7",
"regex-syntax 0.8.4",
]
[[package]] [[package]]
name = "fast_chemail" name = "fast_chemail"
version = "0.9.6" version = "0.9.6"
@@ -3306,6 +3363,7 @@ dependencies = [
"ulid", "ulid",
"url", "url",
"zeroize", "zeroize",
"zxcvbn",
] ]
[[package]] [[package]]
@@ -7428,3 +7486,20 @@ dependencies = [
"quote", "quote",
"syn 2.0.68", "syn 2.0.68",
] ]
[[package]]
name = "zxcvbn"
version = "3.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "579b1d84df61d9d04cd250035843fee2f86a4b4bb176f102fec20779fd0bd38b"
dependencies = [
"derive_builder",
"fancy-regex",
"getrandom",
"itertools 0.13.0",
"lazy_static",
"regex",
"time",
"wasm-bindgen",
"web-sys",
]

View File

@@ -12,6 +12,8 @@
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
use std::process::ExitCode;
use anyhow::Context; use anyhow::Context;
use camino::Utf8PathBuf; use camino::Utf8PathBuf;
use clap::Parser; use clap::Parser;
@@ -68,7 +70,7 @@ enum Subcommand {
} }
impl Options { impl Options {
pub async fn run(self, figment: &Figment) -> anyhow::Result<()> { pub async fn run(self, figment: &Figment) -> anyhow::Result<ExitCode> {
use Subcommand as SC; use Subcommand as SC;
match self.subcommand { match self.subcommand {
SC::Dump { output } => { SC::Dump { output } => {
@@ -139,6 +141,6 @@ impl Options {
} }
} }
Ok(()) Ok(ExitCode::SUCCESS)
} }
} }

View File

@@ -12,6 +12,8 @@
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
use std::process::ExitCode;
use anyhow::Context; use anyhow::Context;
use clap::Parser; use clap::Parser;
use figment::Figment; use figment::Figment;
@@ -34,7 +36,7 @@ enum Subcommand {
} }
impl Options { impl Options {
pub async fn run(self, figment: &Figment) -> anyhow::Result<()> { pub async fn run(self, figment: &Figment) -> anyhow::Result<ExitCode> {
let _span = info_span!("cli.database.migrate").entered(); let _span = info_span!("cli.database.migrate").entered();
let config = DatabaseConfig::extract(figment)?; let config = DatabaseConfig::extract(figment)?;
let mut conn = database_connection_from_config(&config).await?; let mut conn = database_connection_from_config(&config).await?;
@@ -46,6 +48,6 @@ impl Options {
.await .await
.context("could not run migrations")?; .context("could not run migrations")?;
Ok(()) Ok(ExitCode::SUCCESS)
} }
} }

View File

@@ -12,6 +12,8 @@
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
use std::process::ExitCode;
use clap::Parser; use clap::Parser;
use figment::Figment; use figment::Figment;
use http_body_util::BodyExt; use http_body_util::BodyExt;
@@ -67,7 +69,7 @@ fn print_headers(parts: &hyper::http::response::Parts) {
impl Options { impl Options {
#[tracing::instrument(skip_all)] #[tracing::instrument(skip_all)]
pub async fn run(self, figment: &Figment) -> anyhow::Result<()> { pub async fn run(self, figment: &Figment) -> anyhow::Result<ExitCode> {
use Subcommand as SC; use Subcommand as SC;
let http_client_factory = HttpClientFactory::new(); let http_client_factory = HttpClientFactory::new();
match self.subcommand { match self.subcommand {
@@ -130,6 +132,6 @@ impl Options {
} }
} }
Ok(()) Ok(ExitCode::SUCCESS)
} }
} }

View File

@@ -17,6 +17,8 @@
//! The code is quite repetitive for now, but we can refactor later with a //! The code is quite repetitive for now, but we can refactor later with a
//! better check abstraction //! better check abstraction
use std::process::ExitCode;
use anyhow::Context; use anyhow::Context;
use clap::Parser; use clap::Parser;
use figment::Figment; use figment::Figment;
@@ -35,7 +37,7 @@ pub(super) struct Options {}
impl Options { impl Options {
#[allow(clippy::too_many_lines)] #[allow(clippy::too_many_lines)]
pub async fn run(self, figment: &Figment) -> anyhow::Result<()> { pub async fn run(self, figment: &Figment) -> anyhow::Result<ExitCode> {
let _span = info_span!("cli.doctor").entered(); let _span = info_span!("cli.doctor").entered();
info!("💡 Running diagnostics, make sure that both MAS and Synapse are running, and that MAS is using the same configuration files as this tool."); info!("💡 Running diagnostics, make sure that both MAS and Synapse are running, and that MAS is using the same configuration files as this tool.");
@@ -423,6 +425,6 @@ Error details: {e}"#
), ),
} }
Ok(()) Ok(ExitCode::SUCCESS)
} }
} }

View File

@@ -12,7 +12,7 @@
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
use std::collections::BTreeMap; use std::{collections::BTreeMap, process::ExitCode};
use anyhow::Context; use anyhow::Context;
use clap::{ArgAction, CommandFactory, Parser}; use clap::{ArgAction, CommandFactory, Parser};
@@ -34,7 +34,7 @@ use mas_storage::{
use mas_storage_pg::{DatabaseError, PgRepository}; use mas_storage_pg::{DatabaseError, PgRepository};
use rand::{RngCore, SeedableRng}; use rand::{RngCore, SeedableRng};
use sqlx::{types::Uuid, Acquire}; use sqlx::{types::Uuid, Acquire};
use tracing::{info, info_span, warn}; use tracing::{error, info, info_span, warn};
use crate::util::{database_connection_from_config, password_manager_from_config}; use crate::util::{database_connection_from_config, password_manager_from_config};
@@ -69,7 +69,14 @@ enum Subcommand {
VerifyEmail { username: String, email: String }, VerifyEmail { username: String, email: String },
/// Set a user password /// Set a user password
SetPassword { username: String, password: String }, SetPassword {
username: String,
password: String,
/// Don't enforce that the password provided is above the minimum
/// configured complexity.
#[clap(long)]
ignore_complexity: bool,
},
/// Issue a compatibility token /// Issue a compatibility token
IssueCompatibilityToken { IssueCompatibilityToken {
@@ -158,19 +165,27 @@ enum Subcommand {
/// Set the user's display name /// Set the user's display name
#[arg(short, long, help_heading = USER_ATTRIBUTES_HEADING)] #[arg(short, long, help_heading = USER_ATTRIBUTES_HEADING)]
display_name: Option<String>, display_name: Option<String>,
/// Don't enforce that the password provided is above the minimum
/// configured complexity.
#[clap(long)]
ignore_password_complexity: bool,
}, },
} }
impl Options { impl Options {
#[allow(clippy::too_many_lines)] #[allow(clippy::too_many_lines)]
pub async fn run(self, figment: &Figment) -> anyhow::Result<()> { pub async fn run(self, figment: &Figment) -> anyhow::Result<ExitCode> {
use Subcommand as SC; use Subcommand as SC;
let clock = SystemClock::default(); let clock = SystemClock::default();
// XXX: we should disallow SeedableRng::from_entropy // XXX: we should disallow SeedableRng::from_entropy
let mut rng = rand_chacha::ChaChaRng::from_entropy(); let mut rng = rand_chacha::ChaChaRng::from_entropy();
match self.subcommand { match self.subcommand {
SC::SetPassword { username, password } => { SC::SetPassword {
username,
password,
ignore_complexity,
} => {
let _span = let _span =
info_span!("cli.manage.set_password", user.username = %username).entered(); info_span!("cli.manage.set_password", user.username = %username).entered();
@@ -188,6 +203,11 @@ impl Options {
.await? .await?
.context("User not found")?; .context("User not found")?;
if !ignore_complexity && !password_manager.is_password_complex_enough(&password)? {
error!("That password is too weak.");
return Ok(ExitCode::from(1));
}
let password = password.into_bytes().into(); let password = password.into_bytes().into();
let (version, hashed_password) = password_manager.hash(&mut rng, password).await?; let (version, hashed_password) = password_manager.hash(&mut rng, password).await?;
@@ -199,7 +219,7 @@ impl Options {
info!(%user.id, %user.username, "Password changed"); info!(%user.id, %user.username, "Password changed");
repo.into_inner().commit().await?; repo.into_inner().commit().await?;
Ok(()) Ok(ExitCode::SUCCESS)
} }
SC::VerifyEmail { username, email } => { SC::VerifyEmail { username, email } => {
@@ -236,7 +256,7 @@ impl Options {
repo.into_inner().commit().await?; repo.into_inner().commit().await?;
info!(?email, "Email marked as verified"); info!(?email, "Email marked as verified");
Ok(()) Ok(ExitCode::SUCCESS)
} }
SC::IssueCompatibilityToken { SC::IssueCompatibilityToken {
@@ -284,7 +304,7 @@ impl Options {
"Compatibility token issued: {}", compat_access_token.token "Compatibility token issued: {}", compat_access_token.token
); );
Ok(()) Ok(ExitCode::SUCCESS)
} }
SC::ProvisionAllUsers => { SC::ProvisionAllUsers => {
@@ -309,7 +329,7 @@ impl Options {
repo.into_inner().commit().await?; repo.into_inner().commit().await?;
Ok(()) Ok(ExitCode::SUCCESS)
} }
SC::KillSessions { username, dry_run } => { SC::KillSessions { username, dry_run } => {
@@ -427,7 +447,7 @@ impl Options {
txn.commit().await?; txn.commit().await?;
} }
Ok(()) Ok(ExitCode::SUCCESS)
} }
SC::LockUser { SC::LockUser {
@@ -462,7 +482,7 @@ impl Options {
repo.into_inner().commit().await?; repo.into_inner().commit().await?;
Ok(()) Ok(ExitCode::SUCCESS)
} }
SC::UnlockUser { username } => { SC::UnlockUser { username } => {
@@ -483,7 +503,7 @@ impl Options {
repo.user().unlock(user).await?; repo.user().unlock(user).await?;
repo.into_inner().commit().await?; repo.into_inner().commit().await?;
Ok(()) Ok(ExitCode::SUCCESS)
} }
SC::RegisterUser { SC::RegisterUser {
@@ -495,6 +515,7 @@ impl Options {
no_admin, no_admin,
display_name, display_name,
yes, yes,
ignore_password_complexity,
} => { } => {
let http_client_factory = HttpClientFactory::new(); let http_client_factory = HttpClientFactory::new();
let password_config = PasswordsConfig::extract(figment)?; let password_config = PasswordsConfig::extract(figment)?;
@@ -512,6 +533,15 @@ impl Options {
let txn = conn.begin().await?; let txn = conn.begin().await?;
let mut repo = PgRepository::from_conn(txn); let mut repo = PgRepository::from_conn(txn);
if let Some(password) = &password {
if !ignore_password_complexity
&& !password_manager.is_password_complex_enough(password)?
{
error!("That password is too weak.");
return Ok(ExitCode::from(1));
}
}
// If the username is provided, check if it's available and normalize it. // If the username is provided, check if it's available and normalize it.
let localpart = if let Some(username) = username { let localpart = if let Some(username) = username {
check_and_normalize_username(&username, &mut repo, &homeserver) check_and_normalize_username(&username, &mut repo, &homeserver)
@@ -722,7 +752,7 @@ impl Options {
warn!("Aborted"); warn!("Aborted");
} }
Ok(()) Ok(ExitCode::SUCCESS)
} }
} }
} }

View File

@@ -12,6 +12,8 @@
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
use std::process::ExitCode;
use camino::Utf8PathBuf; use camino::Utf8PathBuf;
use clap::Parser; use clap::Parser;
use figment::{ use figment::{
@@ -67,7 +69,7 @@ pub struct Options {
} }
impl Options { impl Options {
pub async fn run(self, figment: &Figment) -> anyhow::Result<()> { pub async fn run(self, figment: &Figment) -> anyhow::Result<ExitCode> {
use Subcommand as S; use Subcommand as S;
// We Box the futures for each subcommand so that we avoid this function being // We Box the futures for each subcommand so that we avoid this function being
// big on the stack all the time // big on the stack all the time

View File

@@ -12,7 +12,7 @@
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
use std::{collections::BTreeSet, sync::Arc, time::Duration}; use std::{collections::BTreeSet, process::ExitCode, sync::Arc, time::Duration};
use anyhow::Context; use anyhow::Context;
use clap::Parser; use clap::Parser;
@@ -65,7 +65,7 @@ pub(super) struct Options {
impl Options { impl Options {
#[allow(clippy::too_many_lines)] #[allow(clippy::too_many_lines)]
pub async fn run(self, figment: &Figment) -> anyhow::Result<()> { pub async fn run(self, figment: &Figment) -> anyhow::Result<ExitCode> {
let span = info_span!("cli.run.init").entered(); let span = info_span!("cli.run.init").entered();
let config = AppConfig::extract(figment)?; let config = AppConfig::extract(figment)?;
@@ -309,6 +309,6 @@ impl Options {
state.activity_tracker.shutdown().await; state.activity_tracker.shutdown().await;
Ok(()) Ok(ExitCode::SUCCESS)
} }
} }

View File

@@ -12,6 +12,8 @@
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
use std::process::ExitCode;
use clap::Parser; use clap::Parser;
use figment::Figment; use figment::Figment;
use mas_config::{ use mas_config::{
@@ -37,7 +39,7 @@ enum Subcommand {
} }
impl Options { impl Options {
pub async fn run(self, figment: &Figment) -> anyhow::Result<()> { pub async fn run(self, figment: &Figment) -> anyhow::Result<ExitCode> {
use Subcommand as SC; use Subcommand as SC;
match self.subcommand { match self.subcommand {
SC::Check => { SC::Check => {
@@ -66,7 +68,7 @@ impl Options {
templates_from_config(&template_config, &site_config, &url_builder).await?; templates_from_config(&template_config, &site_config, &url_builder).await?;
templates.check_render(clock.now(), &mut rng)?; templates.check_render(clock.now(), &mut rng)?;
Ok(()) Ok(ExitCode::SUCCESS)
} }
} }
} }

View File

@@ -12,6 +12,8 @@
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
use std::process::ExitCode;
use clap::Parser; use clap::Parser;
use figment::Figment; use figment::Figment;
use mas_config::{AppConfig, ConfigurationSection}; use mas_config::{AppConfig, ConfigurationSection};
@@ -32,7 +34,7 @@ use crate::util::{
pub(super) struct Options {} pub(super) struct Options {}
impl Options { impl Options {
pub async fn run(self, figment: &Figment) -> anyhow::Result<()> { pub async fn run(self, figment: &Figment) -> anyhow::Result<ExitCode> {
let span = info_span!("cli.worker.init").entered(); let span = info_span!("cli.worker.init").entered();
let config = AppConfig::extract(figment)?; let config = AppConfig::extract(figment)?;
@@ -82,6 +84,6 @@ impl Options {
span.exit(); span.exit();
monitor.run().await?; monitor.run().await?;
Ok(()) Ok(ExitCode::SUCCESS)
} }
} }

View File

@@ -14,7 +14,7 @@
#![allow(clippy::module_name_repetitions)] #![allow(clippy::module_name_repetitions)]
use std::{io::IsTerminal, sync::Arc}; use std::{io::IsTerminal, process::ExitCode, sync::Arc};
use anyhow::Context; use anyhow::Context;
use clap::Parser; use clap::Parser;
@@ -35,7 +35,7 @@ mod telemetry;
mod util; mod util;
#[tokio::main] #[tokio::main]
async fn main() -> anyhow::Result<()> { async fn main() -> anyhow::Result<ExitCode> {
// We're splitting the "fallible" part of main in another function to have a // We're splitting the "fallible" part of main in another function to have a
// chance to shutdown the telemetry exporters regardless of if there was an // chance to shutdown the telemetry exporters regardless of if there was an
// error or not // error or not
@@ -44,7 +44,7 @@ async fn main() -> anyhow::Result<()> {
res res
} }
async fn try_main() -> anyhow::Result<()> { async fn try_main() -> anyhow::Result<ExitCode> {
// Load environment variables from .env files // Load environment variables from .env files
// We keep the path to log it afterwards // We keep the path to log it afterwards
let dotenv_path: Result<Option<_>, _> = dotenvy::dotenv() let dotenv_path: Result<Option<_>, _> = dotenvy::dotenv()
@@ -136,7 +136,5 @@ async fn try_main() -> anyhow::Result<()> {
// And run the command // And run the command
tracing::trace!(?opts, "Running command"); tracing::trace!(?opts, "Running command");
opts.run(&figment).await?; opts.run(&figment).await
Ok(())
} }

View File

@@ -53,7 +53,7 @@ pub async fn password_manager_from_config(
(version, hasher) (version, hasher)
}); });
PasswordManager::new(schemes) PasswordManager::new(config.minimum_complexity(), schemes)
} }
pub fn mailer_from_config( pub fn mailer_from_config(
@@ -173,6 +173,7 @@ pub fn site_config_from_config(
account_recovery_allowed: password_config.enabled() account_recovery_allowed: password_config.enabled()
&& experimental_config.account_recovery_enabled, && experimental_config.account_recovery_enabled,
captcha, captcha,
minimum_password_complexity: password_config.minimum_complexity(),
}) })
} }

View File

@@ -35,6 +35,10 @@ fn default_enabled() -> bool {
true true
} }
fn default_minimum_complexity() -> u8 {
3
}
/// User password hashing config /// User password hashing config
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] #[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct PasswordsConfig { pub struct PasswordsConfig {
@@ -44,6 +48,18 @@ pub struct PasswordsConfig {
#[serde(default = "default_schemes")] #[serde(default = "default_schemes")]
schemes: Vec<HashingScheme>, schemes: Vec<HashingScheme>,
/// Score between 0 and 4 determining the minimum allowed password
/// complexity. Scores are based on the ESTIMATED number of guesses
/// needed to guess the password.
///
/// - 0: less than 10^2 (100)
/// - 1: less than 10^4 (10'000)
/// - 2: less than 10^6 (1'000'000)
/// - 3: less than 10^8 (100'000'000)
/// - 4: any more than that
#[serde(default = "default_minimum_complexity")]
minimum_complexity: u8,
} }
impl Default for PasswordsConfig { impl Default for PasswordsConfig {
@@ -51,6 +67,7 @@ impl Default for PasswordsConfig {
Self { Self {
enabled: default_enabled(), enabled: default_enabled(),
schemes: default_schemes(), schemes: default_schemes(),
minimum_complexity: default_minimum_complexity(),
} }
} }
} }
@@ -96,6 +113,13 @@ impl PasswordsConfig {
self.enabled self.enabled
} }
/// Minimum complexity of passwords, from 0 to 4, according to the zxcvbn
/// scorer.
#[must_use]
pub fn minimum_complexity(&self) -> u8 {
self.minimum_complexity
}
/// Load the password hashing schemes defined by the config /// Load the password hashing schemes defined by the config
/// ///
/// # Errors /// # Errors

View File

@@ -78,4 +78,8 @@ pub struct SiteConfig {
/// Captcha configuration /// Captcha configuration
pub captcha: Option<CaptchaConfig>, pub captcha: Option<CaptchaConfig>,
/// Minimum password complexity, between 0 and 4.
/// This is a score from zxcvbn.
pub minimum_password_complexity: u8,
} }

View File

@@ -91,6 +91,7 @@ mas-storage.workspace = true
mas-storage-pg.workspace = true mas-storage-pg.workspace = true
mas-templates.workspace = true mas-templates.workspace = true
oauth2-types.workspace = true oauth2-types.workspace = true
zxcvbn = "3.0.1"
[dev-dependencies] [dev-dependencies]
insta = "1.39.0" insta = "1.39.0"

View File

@@ -46,6 +46,11 @@ pub struct SiteConfig {
/// Whether passwords are enabled and users can change their own passwords. /// Whether passwords are enabled and users can change their own passwords.
password_change_allowed: bool, password_change_allowed: bool,
/// Minimum password complexity, from 0 to 4, in terms of a zxcvbn score.
/// The exact scorer (including dictionaries and other data tables)
/// in use is <https://crates.io/crates/zxcvbn>.
minimum_password_complexity: u8,
} }
#[ComplexObject] #[ComplexObject]
@@ -69,6 +74,7 @@ impl SiteConfig {
display_name_change_allowed: data_model.displayname_change_allowed, display_name_change_allowed: data_model.displayname_change_allowed,
password_login_enabled: data_model.password_login_enabled, password_login_enabled: data_model.password_login_enabled,
password_change_allowed: data_model.password_change_allowed, password_change_allowed: data_model.password_change_allowed,
minimum_password_complexity: data_model.minimum_password_complexity,
} }
} }
} }

View File

@@ -480,6 +480,20 @@ impl UserMutations {
}); });
} }
let password_manager = state.password_manager();
if !password_manager.is_enabled() {
return Ok(SetPasswordPayload {
status: SetPasswordStatus::PasswordChangesDisabled,
});
}
if !password_manager.is_password_complex_enough(&input.new_password)? {
return Ok(SetPasswordPayload {
status: SetPasswordStatus::InvalidNewPassword,
});
}
let mut repo = state.repository().await?; let mut repo = state.repository().await?;
let Some(user) = repo.user().lookup(user_id).await? else { let Some(user) = repo.user().lookup(user_id).await? else {
return Ok(SetPasswordPayload { return Ok(SetPasswordPayload {
@@ -487,13 +501,12 @@ impl UserMutations {
}); });
}; };
let password_manager = state.password_manager();
if !requester.is_admin() { if !requester.is_admin() {
// If the user isn't an admin, we: // If the user isn't an admin, we:
// - check that password changes are enabled // - check that password changes are enabled
// - check that they know their current password // - check that they know their current password
if !state.site_config().password_change_allowed || !password_manager.is_enabled() { if !state.site_config().password_change_allowed {
return Ok(SetPasswordPayload { return Ok(SetPasswordPayload {
status: SetPasswordStatus::PasswordChangesDisabled, status: SetPasswordStatus::PasswordChangesDisabled,
}); });

View File

@@ -21,6 +21,7 @@ use pbkdf2::Pbkdf2;
use rand::{CryptoRng, Rng, RngCore, SeedableRng}; use rand::{CryptoRng, Rng, RngCore, SeedableRng};
use thiserror::Error; use thiserror::Error;
use zeroize::Zeroizing; use zeroize::Zeroizing;
use zxcvbn::zxcvbn;
pub type SchemeVersion = u16; pub type SchemeVersion = u16;
@@ -34,6 +35,9 @@ pub struct PasswordManager {
} }
struct InnerPasswordManager { struct InnerPasswordManager {
/// Minimum complexity score of new passwords (between 0 and 4) as evaluated
/// by zxcvbn.
minimum_complexity: u8,
current_hasher: Hasher, current_hasher: Hasher,
current_version: SchemeVersion, current_version: SchemeVersion,
@@ -42,7 +46,8 @@ struct InnerPasswordManager {
} }
impl PasswordManager { impl PasswordManager {
/// Creates a new [`PasswordManager`] from an iterator. The first item in /// Creates a new [`PasswordManager`] from an iterator and a minimum allowed
/// complexity score between 0 and 4. The first item in
/// the iterator will be the default hashing scheme. /// the iterator will be the default hashing scheme.
/// ///
/// # Example /// # Example
@@ -50,7 +55,7 @@ impl PasswordManager {
/// ```rust /// ```rust
/// pub use mas_handlers::passwords::{PasswordManager, Hasher}; /// pub use mas_handlers::passwords::{PasswordManager, Hasher};
/// ///
/// PasswordManager::new([ /// PasswordManager::new(3, [
/// (3, Hasher::argon2id(Some(b"a-secret-pepper".to_vec()))), /// (3, Hasher::argon2id(Some(b"a-secret-pepper".to_vec()))),
/// (2, Hasher::argon2id(None)), /// (2, Hasher::argon2id(None)),
/// (1, Hasher::bcrypt(Some(10), None)), /// (1, Hasher::bcrypt(Some(10), None)),
@@ -61,6 +66,7 @@ impl PasswordManager {
/// ///
/// Returns an error if the iterator was empty /// Returns an error if the iterator was empty
pub fn new<I: IntoIterator<Item = (SchemeVersion, Hasher)>>( pub fn new<I: IntoIterator<Item = (SchemeVersion, Hasher)>>(
minimum_complexity: u8,
iter: I, iter: I,
) -> Result<Self, anyhow::Error> { ) -> Result<Self, anyhow::Error> {
let mut iter = iter.into_iter(); let mut iter = iter.into_iter();
@@ -75,6 +81,7 @@ impl PasswordManager {
Ok(Self { Ok(Self {
inner: Some(Arc::new(InnerPasswordManager { inner: Some(Arc::new(InnerPasswordManager {
minimum_complexity,
current_hasher, current_hasher,
current_version, current_version,
other_hashers, other_hashers,
@@ -103,6 +110,18 @@ impl PasswordManager {
self.inner.clone().ok_or(PasswordManagerDisabledError) self.inner.clone().ok_or(PasswordManagerDisabledError)
} }
/// Returns true if and only if the given password satisfies the minimum
/// complexity requirements.
///
/// # Errors
///
/// Returns an error if the password manager is disabled
pub fn is_password_complex_enough(&self, password: &str) -> Result<bool, anyhow::Error> {
let inner = self.get_inner()?;
let score = zxcvbn(password, &[]);
Ok(u8::from(score.score()) >= inner.minimum_complexity)
}
/// Hash a password with the default hashing scheme. /// Hash a password with the default hashing scheme.
/// Returns the version of the hashing scheme used and the hashed password. /// Returns the version of the hashing scheme used and the hashed password.
/// ///
@@ -461,13 +480,16 @@ mod tests {
let password = Zeroizing::new(b"hunter2".to_vec()); let password = Zeroizing::new(b"hunter2".to_vec());
let wrong_password = Zeroizing::new(b"wrong-password".to_vec()); let wrong_password = Zeroizing::new(b"wrong-password".to_vec());
let manager = PasswordManager::new([ let manager = PasswordManager::new(
0,
[
// Start with one hashing scheme: the one used by synapse, bcrypt + pepper // Start with one hashing scheme: the one used by synapse, bcrypt + pepper
( (
1, 1,
Hasher::bcrypt(Some(10), Some(b"a-secret-pepper".to_vec())), Hasher::bcrypt(Some(10), Some(b"a-secret-pepper".to_vec())),
), ),
]) ],
)
.unwrap(); .unwrap();
let (version, hash) = manager let (version, hash) = manager
@@ -510,13 +532,16 @@ mod tests {
.await .await
.expect_err("Verification should have failed"); .expect_err("Verification should have failed");
let manager = PasswordManager::new([ let manager = PasswordManager::new(
0,
[
(2, Hasher::argon2id(None)), (2, Hasher::argon2id(None)),
( (
1, 1,
Hasher::bcrypt(Some(10), Some(b"a-secret-pepper".to_vec())), Hasher::bcrypt(Some(10), Some(b"a-secret-pepper".to_vec())),
), ),
]) ],
)
.unwrap(); .unwrap();
// Verifying still works // Verifying still works
@@ -563,14 +588,17 @@ mod tests {
.await .await
.expect_err("Verification should have failed"); .expect_err("Verification should have failed");
let manager = PasswordManager::new([ let manager = PasswordManager::new(
0,
[
(3, Hasher::argon2id(Some(b"a-secret-pepper".to_vec()))), (3, Hasher::argon2id(Some(b"a-secret-pepper".to_vec()))),
(2, Hasher::argon2id(None)), (2, Hasher::argon2id(None)),
( (
1, 1,
Hasher::bcrypt(Some(10), Some(b"a-secret-pepper".to_vec())), Hasher::bcrypt(Some(10), Some(b"a-secret-pepper".to_vec())),
), ),
]) ],
)
.unwrap(); .unwrap();
// Verifying still works // Verifying still works

View File

@@ -136,6 +136,7 @@ pub fn test_site_config() -> SiteConfig {
password_change_allowed: true, password_change_allowed: true,
account_recovery_allowed: true, account_recovery_allowed: true,
captcha: None, captcha: None,
minimum_password_complexity: 1,
} }
} }
@@ -178,7 +179,10 @@ impl TestState {
let metadata_cache = MetadataCache::new(); let metadata_cache = MetadataCache::new();
let password_manager = if site_config.password_login_enabled { let password_manager = if site_config.password_login_enabled {
PasswordManager::new([(1, Hasher::argon2id(None))])? PasswordManager::new(
site_config.minimum_password_complexity,
[(1, Hasher::argon2id(None))],
)?
} else { } else {
PasswordManager::disabled() PasswordManager::disabled()
}; };

View File

@@ -226,6 +226,18 @@ pub(crate) async fn post(
); );
} }
if !password_manager.is_password_complex_enough(&form.new_password)? {
// TODO This error should be localised,
// but actually this entire form should be pushed down into the
// React frontend so user gets real-time feedback.
form_state = form_state.with_error_on_field(
RecoveryFinishFormField::NewPassword,
FieldError::Policy {
message: "Password is too weak".to_owned(),
},
);
}
let res = policy.evaluate_password(&form.new_password).await?; let res = policy.evaluate_password(&form.new_password).await?;
if !res.valid() { if !res.valid() {

View File

@@ -198,6 +198,16 @@ pub(crate) async fn post(
); );
} }
if !password_manager.is_password_complex_enough(&form.password)? {
// TODO localise this error
state.add_error_on_field(
RegisterFormField::Password,
FieldError::Policy {
message: "Password is too weak".to_owned(),
},
);
}
// If the site has terms of service, the user must accept them // If the site has terms of service, the user must accept them
if site_config.tos_uri.is_some() && form.accept_terms != "on" { if site_config.tos_uri.is_some() && form.accept_terms != "on" {
state.add_error_on_field(RegisterFormField::AcceptTerms, FieldError::Required); state.add_error_on_field(RegisterFormField::AcceptTerms, FieldError::Required);
@@ -402,8 +412,8 @@ mod tests {
"csrf": csrf_token, "csrf": csrf_token,
"username": "john", "username": "john",
"email": "john@example.com", "email": "john@example.com",
"password": "hunter2", "password": "correcthorsebatterystaple",
"password_confirm": "hunter2", "password_confirm": "correcthorsebatterystaple",
"accept_terms": "on", "accept_terms": "on",
}), }),
); );

View File

@@ -144,7 +144,8 @@
"version": 1, "version": 1,
"algorithm": "argon2id" "algorithm": "argon2id"
} }
] ],
"minimum_complexity": 3
}, },
"allOf": [ "allOf": [
{ {
@@ -1507,6 +1508,13 @@
"items": { "items": {
"$ref": "#/definitions/HashingScheme" "$ref": "#/definitions/HashingScheme"
} }
},
"minimum_complexity": {
"description": "Score between 0 and 4 determining the minimum allowed password complexity. Scores are based on the ESTIMATED number of guesses needed to guess the password.\n\n- 0: less than 10^2 (100) - 1: less than 10^4 (10'000) - 2: less than 10^6 (1'000'000) - 3: less than 10^8 (100'000'000) - 4: any more than that",
"default": 3,
"type": "integer",
"format": "uint8",
"minimum": 0.0
} }
} }
}, },

View File

@@ -1388,6 +1388,12 @@ type SiteConfig implements Node {
""" """
passwordChangeAllowed: Boolean! passwordChangeAllowed: Boolean!
""" """
Minimum password complexity, from 0 to 4, in terms of a zxcvbn score.
The exact scorer (including dictionaries and other data tables)
in use is <https://crates.io/crates/zxcvbn>.
"""
minimumPasswordComplexity: Int!
"""
The ID of the site configuration. The ID of the site configuration.
""" """
id: ID! id: ID!

View File

@@ -1022,6 +1022,12 @@ export type SiteConfig = Node & {
id: Scalars['ID']['output']; id: Scalars['ID']['output'];
/** Imprint to show in the footer. */ /** Imprint to show in the footer. */
imprint?: Maybe<Scalars['String']['output']>; imprint?: Maybe<Scalars['String']['output']>;
/**
* Minimum password complexity, from 0 to 4, in terms of a zxcvbn score.
* The exact scorer (including dictionaries and other data tables)
* in use is <https://crates.io/crates/zxcvbn>.
*/
minimumPasswordComplexity: Scalars['Int']['output'];
/** Whether passwords are enabled and users can change their own passwords. */ /** Whether passwords are enabled and users can change their own passwords. */
passwordChangeAllowed: Scalars['Boolean']['output']; passwordChangeAllowed: Scalars['Boolean']['output'];
/** Whether passwords are enabled for login. */ /** Whether passwords are enabled for login. */

View File

@@ -2554,6 +2554,17 @@ export default {
}, },
"args": [] "args": []
}, },
{
"name": "minimumPasswordComplexity",
"type": {
"kind": "NON_NULL",
"ofType": {
"kind": "SCALAR",
"name": "Any"
}
},
"args": []
},
{ {
"name": "passwordChangeAllowed", "name": "passwordChangeAllowed",
"type": { "type": {