2024-09-12 15:18:39 +02:00
|
|
|
use chrono::{NaiveDateTime, Utc};
|
2019-08-03 18:47:52 +02:00
|
|
|
use num_traits::FromPrimitive;
|
2020-07-14 18:00:09 +02:00
|
|
|
use rocket::{
|
2021-11-07 18:53:39 +01:00
|
|
|
form::{Form, FromForm},
|
2024-09-12 15:18:39 +02:00
|
|
|
http::Status,
|
|
|
|
response::Redirect,
|
|
|
|
serde::json::Json,
|
2020-07-14 18:00:09 +02:00
|
|
|
Route,
|
|
|
|
};
|
2018-10-10 20:40:39 +02:00
|
|
|
use serde_json::Value;
|
2018-02-10 01:00:55 +01:00
|
|
|
|
2020-07-14 18:00:09 +02:00
|
|
|
use crate::{
|
|
|
|
api::{
|
2024-01-01 19:41:40 +01:00
|
|
|
core::{
|
2024-09-12 15:18:39 +02:00
|
|
|
accounts::{PreloginData, RegisterData, _prelogin, _register, kdf_upgrade},
|
2024-01-01 19:41:40 +01:00
|
|
|
log_user_event,
|
2024-07-24 09:50:35 -05:00
|
|
|
two_factor::{authenticator, duo, duo_oidc, email, enforce_2fa_policy, webauthn, yubikey},
|
2024-01-01 19:41:40 +01:00
|
|
|
},
|
2024-01-30 19:14:25 +01:00
|
|
|
push::register_push_device,
|
2024-06-23 21:31:02 +02:00
|
|
|
ApiResult, EmptyResult, JsonResult,
|
2020-07-14 18:00:09 +02:00
|
|
|
},
|
2024-09-12 15:18:39 +02:00
|
|
|
auth,
|
|
|
|
auth::{AuthMethod, AuthMethodScope, ClientHeaders, ClientIp},
|
2020-07-14 18:00:09 +02:00
|
|
|
db::{models::*, DbConn},
|
|
|
|
error::MapResult,
|
2024-09-12 15:18:39 +02:00
|
|
|
mail, sso, util, CONFIG,
|
2020-07-14 18:00:09 +02:00
|
|
|
};
|
2018-07-13 15:58:50 +02:00
|
|
|
|
2018-02-10 01:00:55 +01:00
|
|
|
pub fn routes() -> Vec<Route> {
|
2024-09-12 15:18:39 +02:00
|
|
|
routes![login, prelogin, identity_register, _prevalidate, prevalidate, authorize, oidcsignin, oidcsignin_error]
|
2018-02-10 01:00:55 +01:00
|
|
|
}
|
|
|
|
|
2018-10-10 20:40:39 +02:00
|
|
|
#[post("/connect/token", data = "<data>")]
|
2023-03-09 16:31:28 +01:00
|
|
|
async fn login(data: Form<ConnectData>, client_header: ClientHeaders, mut conn: DbConn) -> JsonResult {
|
2018-10-10 20:40:39 +02:00
|
|
|
let data: ConnectData = data.into_inner();
|
2018-02-10 01:00:55 +01:00
|
|
|
|
2022-11-20 19:15:45 +01:00
|
|
|
let mut user_uuid: Option<String> = None;
|
|
|
|
|
|
|
|
let login_result = match data.grant_type.as_ref() {
|
2018-12-16 20:00:16 +01:00
|
|
|
"refresh_token" => {
|
|
|
|
_check_is_some(&data.refresh_token, "refresh_token cannot be blank")?;
|
2022-11-20 19:15:45 +01:00
|
|
|
_refresh_login(data, &mut conn).await
|
2018-12-16 20:00:16 +01:00
|
|
|
}
|
2024-09-12 15:18:39 +02:00
|
|
|
"password" if CONFIG.sso_enabled() && CONFIG.sso_only() => err!("SSO sign-in is required"),
|
2018-12-16 20:00:16 +01:00
|
|
|
"password" => {
|
|
|
|
_check_is_some(&data.client_id, "client_id cannot be blank")?;
|
|
|
|
_check_is_some(&data.password, "password cannot be blank")?;
|
|
|
|
_check_is_some(&data.scope, "scope cannot be blank")?;
|
|
|
|
_check_is_some(&data.username, "username cannot be blank")?;
|
|
|
|
|
|
|
|
_check_is_some(&data.device_identifier, "device_identifier cannot be blank")?;
|
|
|
|
_check_is_some(&data.device_name, "device_name cannot be blank")?;
|
|
|
|
_check_is_some(&data.device_type, "device_type cannot be blank")?;
|
|
|
|
|
2023-03-09 16:31:28 +01:00
|
|
|
_password_login(data, &mut user_uuid, &mut conn, &client_header.ip).await
|
2018-12-16 20:00:16 +01:00
|
|
|
}
|
2022-01-19 02:51:26 -08:00
|
|
|
"client_credentials" => {
|
|
|
|
_check_is_some(&data.client_id, "client_id cannot be blank")?;
|
|
|
|
_check_is_some(&data.client_secret, "client_secret cannot be blank")?;
|
|
|
|
_check_is_some(&data.scope, "scope cannot be blank")?;
|
|
|
|
|
2023-02-16 16:29:24 +01:00
|
|
|
_check_is_some(&data.device_identifier, "device_identifier cannot be blank")?;
|
|
|
|
_check_is_some(&data.device_name, "device_name cannot be blank")?;
|
|
|
|
_check_is_some(&data.device_type, "device_type cannot be blank")?;
|
|
|
|
|
2023-03-09 16:31:28 +01:00
|
|
|
_api_key_login(data, &mut user_uuid, &mut conn, &client_header.ip).await
|
2022-01-19 02:51:26 -08:00
|
|
|
}
|
2024-09-12 15:18:39 +02:00
|
|
|
"authorization_code" if CONFIG.sso_enabled() => {
|
2023-08-30 16:13:09 +02:00
|
|
|
_check_is_some(&data.client_id, "client_id cannot be blank")?;
|
|
|
|
_check_is_some(&data.code, "code cannot be blank")?;
|
|
|
|
|
|
|
|
_check_is_some(&data.device_identifier, "device_identifier cannot be blank")?;
|
|
|
|
_check_is_some(&data.device_name, "device_name cannot be blank")?;
|
|
|
|
_check_is_some(&data.device_type, "device_type cannot be blank")?;
|
2024-09-12 15:18:39 +02:00
|
|
|
|
|
|
|
_sso_login(data, &mut user_uuid, &mut conn, &client_header.ip).await
|
2023-08-30 16:13:09 +02:00
|
|
|
}
|
2024-09-12 15:18:39 +02:00
|
|
|
"authorization_code" => err!("SSO sign-in is not available"),
|
2018-12-16 20:00:16 +01:00
|
|
|
t => err!("Invalid type", t),
|
2022-11-20 19:15:45 +01:00
|
|
|
};
|
|
|
|
|
|
|
|
if let Some(user_uuid) = user_uuid {
|
|
|
|
match &login_result {
|
|
|
|
Ok(_) => {
|
2022-12-15 15:57:30 +01:00
|
|
|
log_user_event(
|
|
|
|
EventType::UserLoggedIn as i32,
|
|
|
|
&user_uuid,
|
|
|
|
client_header.device_type,
|
2023-03-09 16:31:28 +01:00
|
|
|
&client_header.ip.ip,
|
2022-12-15 15:57:30 +01:00
|
|
|
&mut conn,
|
|
|
|
)
|
|
|
|
.await;
|
2022-11-20 19:15:45 +01:00
|
|
|
}
|
|
|
|
Err(e) => {
|
|
|
|
if let Some(ev) = e.get_event() {
|
2023-03-09 16:31:28 +01:00
|
|
|
log_user_event(
|
|
|
|
ev.event as i32,
|
|
|
|
&user_uuid,
|
|
|
|
client_header.device_type,
|
|
|
|
&client_header.ip.ip,
|
|
|
|
&mut conn,
|
|
|
|
)
|
|
|
|
.await
|
2022-11-20 19:15:45 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2018-06-01 15:08:03 +02:00
|
|
|
}
|
2022-11-20 19:15:45 +01:00
|
|
|
|
|
|
|
login_result
|
2018-06-01 15:08:03 +02:00
|
|
|
}
|
2018-02-10 01:00:55 +01:00
|
|
|
|
2024-09-12 15:18:39 +02:00
|
|
|
// Return Status::Unauthorized to trigger logout
|
2022-11-20 19:15:45 +01:00
|
|
|
async fn _refresh_login(data: ConnectData, conn: &mut DbConn) -> JsonResult {
|
2018-06-01 15:08:03 +02:00
|
|
|
// Extract token
|
2024-09-12 15:18:39 +02:00
|
|
|
let refresh_token = match data.refresh_token {
|
|
|
|
Some(token) => token,
|
|
|
|
None => err_code!("Missing refresh_token", Status::Unauthorized.code),
|
|
|
|
};
|
2022-01-20 21:50:58 -08:00
|
|
|
|
2023-12-13 17:49:35 +01:00
|
|
|
// ---
|
|
|
|
// Disabled this variable, it was used to generate the JWT
|
|
|
|
// Because this might get used in the future, and is add by the Bitwarden Server, lets keep it, but then commented out
|
|
|
|
// See: https://github.com/dani-garcia/vaultwarden/issues/4156
|
|
|
|
// ---
|
|
|
|
// let orgs = UserOrganization::find_confirmed_by_user(&user.uuid, conn).await;
|
2024-09-12 15:18:39 +02:00
|
|
|
match auth::refresh_tokens(&refresh_token, conn).await {
|
|
|
|
Err(err) => {
|
|
|
|
err_code!(format!("Unable to refresh login credentials: {}", err.message()), Status::Unauthorized.code)
|
|
|
|
}
|
|
|
|
Ok((mut device, auth_tokens)) => {
|
|
|
|
// Save to update `device.updated_at` to track usage
|
|
|
|
device.save(conn).await?;
|
|
|
|
|
|
|
|
let result = json!({
|
|
|
|
"refresh_token": auth_tokens.refresh_token(),
|
|
|
|
"access_token": auth_tokens.access_token(),
|
|
|
|
"expires_in": auth_tokens.expires_in(),
|
|
|
|
"token_type": "Bearer",
|
|
|
|
"scope": auth_tokens.scope(),
|
|
|
|
});
|
|
|
|
|
|
|
|
Ok(Json(result))
|
|
|
|
}
|
|
|
|
}
|
2018-06-01 15:08:03 +02:00
|
|
|
}
|
|
|
|
|
2024-09-12 15:18:39 +02:00
|
|
|
// After exchanging the code we need to check first if 2FA is needed before continuing
|
|
|
|
async fn _sso_login(data: ConnectData, user_uuid: &mut Option<String>, conn: &mut DbConn, ip: &ClientIp) -> JsonResult {
|
|
|
|
AuthMethod::Sso.check_scope(data.scope.as_ref())?;
|
2023-08-30 16:13:09 +02:00
|
|
|
|
2024-09-12 15:18:39 +02:00
|
|
|
// Ratelimit the login
|
|
|
|
crate::ratelimit::check_limit_login(&ip.ip)?;
|
2023-08-30 16:13:09 +02:00
|
|
|
|
|
|
|
let code = match data.code.as_ref() {
|
|
|
|
None => err!("Got no code in OIDC data"),
|
|
|
|
Some(code) => code,
|
|
|
|
};
|
|
|
|
|
2024-09-12 15:18:39 +02:00
|
|
|
let user_infos = sso::exchange_code(code, conn).await?;
|
|
|
|
|
|
|
|
// Will trigger 2FA flow if needed
|
|
|
|
let user_data = match SsoUser::find_by_identifier_or_email(&user_infos.identifier, &user_infos.email, conn).await {
|
|
|
|
None => None,
|
|
|
|
Some((user, None)) if user.private_key.is_some() && !CONFIG.sso_signups_match_email() => {
|
|
|
|
error!(
|
|
|
|
"Login failure ({}), existing non SSO user ({}) with same email ({}) and association is disabled",
|
|
|
|
user_infos.identifier, user.uuid, user.email
|
|
|
|
);
|
|
|
|
err_silent!("Existing non SSO user with same email")
|
|
|
|
}
|
|
|
|
Some((user, Some(sso_user))) if sso_user.identifier != user_infos.identifier => {
|
|
|
|
error!(
|
|
|
|
"Login failure ({}), existing SSO user ({}) with same email ({})",
|
|
|
|
user_infos.identifier, user.uuid, user.email
|
|
|
|
);
|
|
|
|
err_silent!("Existing SSO user with same email")
|
|
|
|
}
|
|
|
|
Some((user, sso_user)) => {
|
|
|
|
let (mut device, new_device) = get_device(&data, conn, &user).await?;
|
|
|
|
let twofactor_token = twofactor_auth(&user, &data, &mut device, ip, conn).await?;
|
2023-08-30 16:13:09 +02:00
|
|
|
|
2024-09-12 15:18:39 +02:00
|
|
|
Some((user, device, new_device, twofactor_token, sso_user))
|
|
|
|
}
|
|
|
|
};
|
2023-08-30 16:13:09 +02:00
|
|
|
|
2024-09-12 15:18:39 +02:00
|
|
|
// We passed 2FA get full user informations
|
|
|
|
let auth_user = sso::redeem(&user_infos.state, conn).await?;
|
2023-08-30 16:13:09 +02:00
|
|
|
|
2024-09-12 15:18:39 +02:00
|
|
|
let now = Utc::now().naive_utc();
|
|
|
|
let (user, mut device, new_device, twofactor_token, sso_user) = match user_data {
|
|
|
|
None => {
|
|
|
|
if !CONFIG.is_email_domain_allowed(&user_infos.email) {
|
|
|
|
err!("Email domain not allowed");
|
|
|
|
}
|
2023-08-30 16:13:09 +02:00
|
|
|
|
2024-10-07 17:23:42 +02:00
|
|
|
match user_infos.email_verified {
|
|
|
|
None if !CONFIG.sso_allow_unknown_email_verification() => err!(
|
|
|
|
"Your provider does not send email verification status.\n\
|
|
|
|
You will need to change the server configuration (check `SSO_ALLOW_UNKNOWN_EMAIL_VERIFICATION`) to log in."
|
|
|
|
),
|
|
|
|
Some(false) => err!("You need to verify your email with your provider before you can log in"),
|
|
|
|
_ => (),
|
2024-09-12 15:18:39 +02:00
|
|
|
}
|
2023-08-30 16:13:09 +02:00
|
|
|
|
2024-09-12 15:18:39 +02:00
|
|
|
let mut user = User::new(user_infos.email, user_infos.user_name);
|
|
|
|
user.verified_at = Some(now);
|
|
|
|
user.save(conn).await?;
|
2023-08-30 16:13:09 +02:00
|
|
|
|
2024-09-12 15:18:39 +02:00
|
|
|
let (device, new_device) = get_device(&data, conn, &user).await?;
|
2023-08-30 16:13:09 +02:00
|
|
|
|
2024-09-12 15:18:39 +02:00
|
|
|
(user, device, new_device, None, None)
|
|
|
|
}
|
|
|
|
Some((mut user, device, new_device, twofactor_token, sso_user)) if user.private_key.is_none() => {
|
|
|
|
// User was invited a stub was created
|
|
|
|
user.verified_at = Some(now);
|
|
|
|
if let Some(user_name) = user_infos.user_name {
|
|
|
|
user.name = user_name;
|
|
|
|
}
|
2023-08-30 16:13:09 +02:00
|
|
|
|
2024-09-12 15:18:39 +02:00
|
|
|
if !CONFIG.mail_enabled() {
|
|
|
|
UserOrganization::confirm_user_invitations(&user.uuid, conn).await?;
|
|
|
|
}
|
2023-08-30 16:13:09 +02:00
|
|
|
|
2024-09-12 15:18:39 +02:00
|
|
|
user.save(conn).await?;
|
|
|
|
(user, device, new_device, twofactor_token, sso_user)
|
|
|
|
}
|
|
|
|
Some((user, device, new_device, twofactor_token, sso_user)) => {
|
|
|
|
if user.email != user_infos.email {
|
|
|
|
if CONFIG.mail_enabled() {
|
|
|
|
mail::send_sso_change_email(&user_infos.email).await?;
|
2023-08-30 16:13:09 +02:00
|
|
|
}
|
2024-09-12 15:18:39 +02:00
|
|
|
info!("User {} email changed in SSO provider from {} to {}", user.uuid, user.email, user_infos.email);
|
2023-08-30 16:13:09 +02:00
|
|
|
}
|
2024-09-12 15:18:39 +02:00
|
|
|
(user, device, new_device, twofactor_token, sso_user)
|
2023-08-30 16:13:09 +02:00
|
|
|
}
|
2024-09-12 15:18:39 +02:00
|
|
|
};
|
|
|
|
|
|
|
|
if sso_user.is_none() {
|
|
|
|
let user_sso = SsoUser {
|
|
|
|
user_uuid: user.uuid.clone(),
|
|
|
|
identifier: user_infos.identifier,
|
|
|
|
};
|
|
|
|
user_sso.save(conn).await?;
|
2023-08-30 16:13:09 +02:00
|
|
|
}
|
2024-09-12 15:18:39 +02:00
|
|
|
|
|
|
|
// Set the user_uuid here to be passed back used for event logging.
|
|
|
|
*user_uuid = Some(user.uuid.clone());
|
|
|
|
|
|
|
|
let auth_tokens = sso::create_auth_tokens(
|
|
|
|
&device,
|
|
|
|
&user,
|
|
|
|
auth_user.refresh_token,
|
|
|
|
&auth_user.access_token,
|
|
|
|
auth_user.expires_in,
|
|
|
|
)?;
|
|
|
|
|
|
|
|
authenticated_response(&user, &mut device, new_device, auth_tokens, twofactor_token, &now, conn, ip).await
|
2023-08-30 16:13:09 +02:00
|
|
|
}
|
|
|
|
|
2024-08-27 19:37:51 +02:00
|
|
|
#[derive(Default, Deserialize, Serialize)]
|
|
|
|
#[serde(rename_all = "camelCase")]
|
|
|
|
struct MasterPasswordPolicy {
|
|
|
|
min_complexity: u8,
|
|
|
|
min_length: u32,
|
|
|
|
require_lower: bool,
|
|
|
|
require_upper: bool,
|
|
|
|
require_numbers: bool,
|
|
|
|
require_special: bool,
|
|
|
|
enforce_on_login: bool,
|
|
|
|
}
|
|
|
|
|
2022-11-20 19:15:45 +01:00
|
|
|
async fn _password_login(
|
|
|
|
data: ConnectData,
|
|
|
|
user_uuid: &mut Option<String>,
|
|
|
|
conn: &mut DbConn,
|
|
|
|
ip: &ClientIp,
|
|
|
|
) -> JsonResult {
|
2018-06-01 15:08:03 +02:00
|
|
|
// Validate scope
|
2024-09-12 15:18:39 +02:00
|
|
|
AuthMethod::Password.check_scope(data.scope.as_ref())?;
|
2018-06-01 15:08:03 +02:00
|
|
|
|
2021-12-22 21:48:49 +01:00
|
|
|
// Ratelimit the login
|
|
|
|
crate::ratelimit::check_limit_login(&ip.ip)?;
|
|
|
|
|
2018-06-01 15:08:03 +02:00
|
|
|
// Get the user
|
2022-03-03 21:00:10 +01:00
|
|
|
let username = data.username.as_ref().unwrap().trim();
|
2024-12-14 00:55:34 +01:00
|
|
|
let Some(mut user) = User::find_by_mail(username, conn).await else {
|
|
|
|
err!("Username or password is incorrect. Try again", format!("IP: {}. Username: {}.", ip.ip, username))
|
2018-06-01 15:08:03 +02:00
|
|
|
};
|
2018-02-10 01:00:55 +01:00
|
|
|
|
2022-11-20 19:15:45 +01:00
|
|
|
// Set the user_uuid here to be passed back used for event logging.
|
|
|
|
*user_uuid = Some(user.uuid.clone());
|
|
|
|
|
2024-11-11 20:13:02 +01:00
|
|
|
// Check if the user is disabled
|
|
|
|
if !user.enabled {
|
|
|
|
err!(
|
|
|
|
"This user has been disabled",
|
|
|
|
format!("IP: {}. Username: {}.", ip.ip, username),
|
|
|
|
ErrorEvent {
|
|
|
|
event: EventType::UserFailedLogIn
|
2023-08-04 21:12:23 +02:00
|
|
|
}
|
2024-11-11 20:13:02 +01:00
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
let password = data.password.as_ref().unwrap();
|
|
|
|
|
|
|
|
// If we get an auth request, we don't check the user's password, but the access code of the auth request
|
|
|
|
if let Some(ref auth_request_uuid) = data.auth_request {
|
2024-12-14 00:55:34 +01:00
|
|
|
let Some(auth_request) = AuthRequest::find_by_uuid_and_user(auth_request_uuid.as_str(), &user.uuid, conn).await
|
|
|
|
else {
|
2023-08-04 21:12:23 +02:00
|
|
|
err!(
|
|
|
|
"Auth request not found. Try again.",
|
|
|
|
format!("IP: {}. Username: {}.", ip.ip, username),
|
|
|
|
ErrorEvent {
|
|
|
|
event: EventType::UserFailedLogIn,
|
|
|
|
}
|
|
|
|
)
|
2024-11-11 20:13:02 +01:00
|
|
|
};
|
|
|
|
|
2024-11-15 11:25:51 +01:00
|
|
|
let expiration_time = auth_request.creation_date + chrono::Duration::minutes(5);
|
|
|
|
let request_expired = Utc::now().naive_utc() >= expiration_time;
|
|
|
|
|
2024-11-11 20:13:02 +01:00
|
|
|
if auth_request.user_uuid != user.uuid
|
|
|
|
|| !auth_request.approved.unwrap_or(false)
|
2024-11-15 11:25:51 +01:00
|
|
|
|| request_expired
|
2024-11-11 20:13:02 +01:00
|
|
|
|| ip.ip.to_string() != auth_request.request_ip
|
|
|
|
|| !auth_request.check_access_code(password)
|
|
|
|
{
|
|
|
|
err!(
|
|
|
|
"Username or access code is incorrect. Try again",
|
|
|
|
format!("IP: {}. Username: {}.", ip.ip, username),
|
|
|
|
ErrorEvent {
|
|
|
|
event: EventType::UserFailedLogIn,
|
|
|
|
}
|
|
|
|
)
|
2023-08-04 21:12:23 +02:00
|
|
|
}
|
|
|
|
} else if !user.check_valid_password(password) {
|
2022-11-20 19:15:45 +01:00
|
|
|
err!(
|
|
|
|
"Username or password is incorrect. Try again",
|
|
|
|
format!("IP: {}. Username: {}.", ip.ip, username),
|
|
|
|
ErrorEvent {
|
|
|
|
event: EventType::UserFailedLogIn,
|
|
|
|
}
|
|
|
|
)
|
2018-06-01 15:08:03 +02:00
|
|
|
}
|
2018-07-12 21:46:50 +02:00
|
|
|
|
2024-11-11 20:13:02 +01:00
|
|
|
// Change the KDF Iterations (only when not logging in with an auth request)
|
2024-09-12 15:18:39 +02:00
|
|
|
if data.auth_request.is_none() {
|
|
|
|
kdf_upgrade(&mut user, password, conn).await?;
|
2023-01-24 13:06:31 +01:00
|
|
|
}
|
|
|
|
|
2021-10-25 01:36:05 -07:00
|
|
|
let now = Utc::now().naive_utc();
|
2020-07-07 21:30:18 -07:00
|
|
|
|
2019-12-06 22:12:41 +01:00
|
|
|
if user.verified_at.is_none() && CONFIG.mail_enabled() && CONFIG.signups_verify() {
|
2021-03-31 21:18:35 +01:00
|
|
|
if user.last_verifying_at.is_none()
|
|
|
|
|| now.signed_duration_since(user.last_verifying_at.unwrap()).num_seconds()
|
|
|
|
> CONFIG.signups_verify_resend_time() as i64
|
|
|
|
{
|
2019-11-24 22:28:49 -07:00
|
|
|
let resend_limit = CONFIG.signups_verify_resend_limit() as i32;
|
|
|
|
if resend_limit == 0 || user.login_verify_count < resend_limit {
|
|
|
|
// We want to send another email verification if we require signups to verify
|
|
|
|
// their email address, and we haven't sent them a reminder in a while...
|
|
|
|
user.last_verifying_at = Some(now);
|
2019-12-06 22:12:41 +01:00
|
|
|
user.login_verify_count += 1;
|
2019-11-24 22:28:49 -07:00
|
|
|
|
2022-11-20 19:15:45 +01:00
|
|
|
if let Err(e) = user.save(conn).await {
|
2019-11-24 22:28:49 -07:00
|
|
|
error!("Error updating user: {:#?}", e);
|
|
|
|
}
|
|
|
|
|
2022-07-06 23:57:37 +02:00
|
|
|
if let Err(e) = mail::send_verify_email(&user.email, &user.uuid).await {
|
2019-11-24 22:28:49 -07:00
|
|
|
error!("Error auto-sending email verification email: {:#?}", e);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// We still want the login to fail until they actually verified the email address
|
2022-11-20 19:15:45 +01:00
|
|
|
err!(
|
|
|
|
"Please verify your email before trying again.",
|
|
|
|
format!("IP: {}. Username: {}.", ip.ip, username),
|
|
|
|
ErrorEvent {
|
|
|
|
event: EventType::UserFailedLogIn
|
|
|
|
}
|
|
|
|
)
|
2019-11-24 22:28:49 -07:00
|
|
|
}
|
|
|
|
|
2024-09-12 15:18:39 +02:00
|
|
|
let (mut device, new_device) = get_device(&data, conn, &user).await?;
|
2019-07-22 08:26:24 +02:00
|
|
|
|
2024-09-12 15:18:39 +02:00
|
|
|
let twofactor_token = twofactor_auth(&user, &data, &mut device, ip, conn).await?;
|
2018-02-10 01:00:55 +01:00
|
|
|
|
2024-09-12 15:18:39 +02:00
|
|
|
let auth_tokens = auth::AuthTokens::new(&device, &user, AuthMethod::Password);
|
|
|
|
|
|
|
|
authenticated_response(&user, &mut device, new_device, auth_tokens, twofactor_token, &now, conn, ip).await
|
|
|
|
}
|
|
|
|
|
|
|
|
#[allow(clippy::too_many_arguments)]
|
|
|
|
async fn authenticated_response(
|
|
|
|
user: &User,
|
|
|
|
device: &mut Device,
|
|
|
|
new_device: bool,
|
|
|
|
auth_tokens: auth::AuthTokens,
|
|
|
|
twofactor_token: Option<String>,
|
|
|
|
now: &NaiveDateTime,
|
|
|
|
conn: &mut DbConn,
|
|
|
|
ip: &ClientIp,
|
|
|
|
) -> JsonResult {
|
2019-07-25 20:47:58 +02:00
|
|
|
if CONFIG.mail_enabled() && new_device {
|
2024-09-12 15:18:39 +02:00
|
|
|
if let Err(e) = mail::send_new_device_logged_in(&user.email, &ip.ip.to_string(), now, device).await {
|
2019-08-18 19:32:26 +02:00
|
|
|
error!("Error sending new device email: {:#?}", e);
|
2019-08-19 22:14:00 +02:00
|
|
|
|
|
|
|
if CONFIG.require_device_email() {
|
2022-11-20 19:15:45 +01:00
|
|
|
err!(
|
|
|
|
"Could not send login notification email. Please contact your administrator.",
|
|
|
|
ErrorEvent {
|
|
|
|
event: EventType::UserFailedLogIn
|
|
|
|
}
|
|
|
|
)
|
2019-08-19 22:14:00 +02:00
|
|
|
}
|
2019-08-18 19:32:26 +02:00
|
|
|
}
|
2019-07-25 20:47:58 +02:00
|
|
|
}
|
|
|
|
|
2024-01-30 19:14:25 +01:00
|
|
|
// register push device
|
2024-01-31 22:31:22 +01:00
|
|
|
if !new_device {
|
2024-09-12 15:18:39 +02:00
|
|
|
register_push_device(device, conn).await?;
|
2024-01-31 22:31:22 +01:00
|
|
|
}
|
2024-01-30 19:14:25 +01:00
|
|
|
|
2024-09-12 15:18:39 +02:00
|
|
|
// Save to update `device.updated_at` to track usage
|
2022-11-20 19:15:45 +01:00
|
|
|
device.save(conn).await?;
|
2018-02-10 01:00:55 +01:00
|
|
|
|
2024-08-27 19:37:51 +02:00
|
|
|
// Fetch all valid Master Password Policies and merge them into one with all true's and larges numbers as one policy
|
|
|
|
let master_password_policies: Vec<MasterPasswordPolicy> =
|
|
|
|
OrgPolicy::find_accepted_and_confirmed_by_user_and_active_policy(
|
|
|
|
&user.uuid,
|
|
|
|
OrgPolicyType::MasterPassword,
|
|
|
|
conn,
|
|
|
|
)
|
|
|
|
.await
|
|
|
|
.into_iter()
|
|
|
|
.filter_map(|p| serde_json::from_str(&p.data).ok())
|
|
|
|
.collect();
|
|
|
|
|
|
|
|
let master_password_policy = if !master_password_policies.is_empty() {
|
|
|
|
let mut mpp_json = json!(master_password_policies.into_iter().reduce(|acc, policy| {
|
|
|
|
MasterPasswordPolicy {
|
|
|
|
min_complexity: acc.min_complexity.max(policy.min_complexity),
|
|
|
|
min_length: acc.min_length.max(policy.min_length),
|
|
|
|
require_lower: acc.require_lower || policy.require_lower,
|
|
|
|
require_upper: acc.require_upper || policy.require_upper,
|
|
|
|
require_numbers: acc.require_numbers || policy.require_numbers,
|
|
|
|
require_special: acc.require_special || policy.require_special,
|
|
|
|
enforce_on_login: acc.enforce_on_login || policy.enforce_on_login,
|
|
|
|
}
|
|
|
|
}));
|
|
|
|
mpp_json["object"] = json!("masterPasswordPolicy");
|
|
|
|
mpp_json
|
|
|
|
} else {
|
|
|
|
json!({"object": "masterPasswordPolicy"})
|
|
|
|
};
|
|
|
|
|
2018-06-01 15:08:03 +02:00
|
|
|
let mut result = json!({
|
2024-09-12 15:18:39 +02:00
|
|
|
"access_token": auth_tokens.access_token(),
|
|
|
|
"expires_in": auth_tokens.expires_in(),
|
2018-02-10 01:00:55 +01:00
|
|
|
"token_type": "Bearer",
|
2024-09-12 15:18:39 +02:00
|
|
|
"refresh_token": auth_tokens.refresh_token(),
|
2018-06-01 15:08:03 +02:00
|
|
|
"PrivateKey": user.private_key,
|
2020-08-04 15:12:04 +02:00
|
|
|
"Kdf": user.client_kdf_type,
|
|
|
|
"KdfIterations": user.client_kdf_iter,
|
2023-03-30 23:52:10 +02:00
|
|
|
"KdfMemory": user.client_kdf_memory,
|
|
|
|
"KdfParallelism": user.client_kdf_parallelism,
|
2024-04-27 23:24:04 +02:00
|
|
|
"ResetMasterPassword": false, // TODO: Same as above
|
|
|
|
"ForcePasswordReset": false,
|
2024-08-27 19:37:51 +02:00
|
|
|
"MasterPasswordPolicy": master_password_policy,
|
2024-09-12 15:18:39 +02:00
|
|
|
"scope": auth_tokens.scope(),
|
2023-08-31 11:02:36 +02:00
|
|
|
"UserDecryptionOptions": {
|
|
|
|
"HasMasterPassword": !user.password_hash.is_empty(),
|
|
|
|
"Object": "userDecryptionOptions"
|
|
|
|
},
|
2018-06-01 15:08:03 +02:00
|
|
|
});
|
|
|
|
|
2024-09-12 15:18:39 +02:00
|
|
|
if !user.akey.is_empty() {
|
|
|
|
result["Key"] = Value::String(user.akey.clone());
|
|
|
|
}
|
|
|
|
|
2018-06-01 15:08:03 +02:00
|
|
|
if let Some(token) = twofactor_token {
|
|
|
|
result["TwoFactorToken"] = Value::String(token);
|
|
|
|
}
|
|
|
|
|
2024-09-12 15:18:39 +02:00
|
|
|
info!("User {} logged in successfully. IP: {}", user.email, ip.ip);
|
2018-06-01 15:08:03 +02:00
|
|
|
Ok(Json(result))
|
|
|
|
}
|
|
|
|
|
2022-11-20 19:15:45 +01:00
|
|
|
async fn _api_key_login(
|
|
|
|
data: ConnectData,
|
|
|
|
user_uuid: &mut Option<String>,
|
|
|
|
conn: &mut DbConn,
|
|
|
|
ip: &ClientIp,
|
|
|
|
) -> JsonResult {
|
2022-01-19 02:51:26 -08:00
|
|
|
// Ratelimit the login
|
|
|
|
crate::ratelimit::check_limit_login(&ip.ip)?;
|
|
|
|
|
2023-06-02 21:36:15 +02:00
|
|
|
// Validate scope
|
2024-09-12 15:18:39 +02:00
|
|
|
match data.scope.as_ref() {
|
|
|
|
Some(scope) if scope == &AuthMethod::UserApiKey.scope() => _user_api_key_login(data, user_uuid, conn, ip).await,
|
|
|
|
Some(scope) if scope == &AuthMethod::OrgApiKey.scope() => _organization_api_key_login(data, conn, ip).await,
|
2023-06-02 21:36:15 +02:00
|
|
|
_ => err!("Scope not supported"),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
async fn _user_api_key_login(
|
|
|
|
data: ConnectData,
|
|
|
|
user_uuid: &mut Option<String>,
|
|
|
|
conn: &mut DbConn,
|
|
|
|
ip: &ClientIp,
|
|
|
|
) -> JsonResult {
|
2022-01-19 02:51:26 -08:00
|
|
|
// Get the user via the client_id
|
|
|
|
let client_id = data.client_id.as_ref().unwrap();
|
2024-12-14 00:55:34 +01:00
|
|
|
let Some(client_user_uuid) = client_id.strip_prefix("user.") else {
|
|
|
|
err!("Malformed client_id", format!("IP: {}.", ip.ip))
|
2022-01-19 02:51:26 -08:00
|
|
|
};
|
2024-12-14 00:55:34 +01:00
|
|
|
let Some(user) = User::find_by_uuid(client_user_uuid, conn).await else {
|
|
|
|
err!("Invalid client_id", format!("IP: {}.", ip.ip))
|
2022-01-19 02:51:26 -08:00
|
|
|
};
|
|
|
|
|
2022-11-20 19:15:45 +01:00
|
|
|
// Set the user_uuid here to be passed back used for event logging.
|
|
|
|
*user_uuid = Some(user.uuid.clone());
|
|
|
|
|
2022-01-19 02:51:26 -08:00
|
|
|
// Check if the user is disabled
|
|
|
|
if !user.enabled {
|
2022-11-20 19:15:45 +01:00
|
|
|
err!(
|
|
|
|
"This user has been disabled (API key login)",
|
|
|
|
format!("IP: {}. Username: {}.", ip.ip, user.email),
|
|
|
|
ErrorEvent {
|
|
|
|
event: EventType::UserFailedLogIn
|
|
|
|
}
|
|
|
|
)
|
2022-01-19 02:51:26 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
// Check API key. Note that API key logins bypass 2FA.
|
|
|
|
let client_secret = data.client_secret.as_ref().unwrap();
|
|
|
|
if !user.check_valid_api_key(client_secret) {
|
2022-11-20 19:15:45 +01:00
|
|
|
err!(
|
|
|
|
"Incorrect client_secret",
|
|
|
|
format!("IP: {}. Username: {}.", ip.ip, user.email),
|
|
|
|
ErrorEvent {
|
|
|
|
event: EventType::UserFailedLogIn
|
|
|
|
}
|
|
|
|
)
|
2022-01-19 02:51:26 -08:00
|
|
|
}
|
|
|
|
|
2024-09-12 15:18:39 +02:00
|
|
|
let (mut device, new_device) = get_device(&data, conn, &user).await?;
|
2022-01-19 02:51:26 -08:00
|
|
|
|
|
|
|
if CONFIG.mail_enabled() && new_device {
|
|
|
|
let now = Utc::now().naive_utc();
|
2024-09-18 20:03:15 +03:00
|
|
|
if let Err(e) = mail::send_new_device_logged_in(&user.email, &ip.ip.to_string(), &now, &device).await {
|
2022-01-19 02:51:26 -08:00
|
|
|
error!("Error sending new device email: {:#?}", e);
|
|
|
|
|
|
|
|
if CONFIG.require_device_email() {
|
2022-11-20 19:15:45 +01:00
|
|
|
err!(
|
|
|
|
"Could not send login notification email. Please contact your administrator.",
|
|
|
|
ErrorEvent {
|
|
|
|
event: EventType::UserFailedLogIn
|
|
|
|
}
|
|
|
|
)
|
2022-01-19 02:51:26 -08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-12-13 17:49:35 +01:00
|
|
|
// ---
|
|
|
|
// Disabled this variable, it was used to generate the JWT
|
|
|
|
// Because this might get used in the future, and is add by the Bitwarden Server, lets keep it, but then commented out
|
|
|
|
// See: https://github.com/dani-garcia/vaultwarden/issues/4156
|
|
|
|
// ---
|
|
|
|
// let orgs = UserOrganization::find_confirmed_by_user(&user.uuid, conn).await;
|
2024-09-12 15:18:39 +02:00
|
|
|
let access_claims = auth::LoginJwtClaims::default(&device, &user, &AuthMethod::UserApiKey);
|
|
|
|
|
|
|
|
// Save to update `device.updated_at` to track usage
|
2022-11-20 19:15:45 +01:00
|
|
|
device.save(conn).await?;
|
2022-01-19 02:51:26 -08:00
|
|
|
|
|
|
|
info!("User {} logged in successfully via API key. IP: {}", user.email, ip.ip);
|
|
|
|
|
2022-01-20 21:50:58 -08:00
|
|
|
// Note: No refresh_token is returned. The CLI just repeats the
|
|
|
|
// client_credentials login flow when the existing token expires.
|
2023-03-30 23:52:10 +02:00
|
|
|
let result = json!({
|
2024-09-12 15:18:39 +02:00
|
|
|
"access_token": access_claims.token(),
|
|
|
|
"expires_in": access_claims.expires_in(),
|
2022-01-19 02:51:26 -08:00
|
|
|
"token_type": "Bearer",
|
|
|
|
"Key": user.akey,
|
|
|
|
"PrivateKey": user.private_key,
|
|
|
|
|
|
|
|
"Kdf": user.client_kdf_type,
|
|
|
|
"KdfIterations": user.client_kdf_iter,
|
2023-03-30 23:52:10 +02:00
|
|
|
"KdfMemory": user.client_kdf_memory,
|
|
|
|
"KdfParallelism": user.client_kdf_parallelism,
|
2024-10-18 20:37:32 +02:00
|
|
|
"ResetMasterPassword": false, // TODO: according to official server seems something like: user.password_hash.is_empty(), but would need testing
|
2024-09-12 15:18:39 +02:00
|
|
|
"scope": AuthMethod::UserApiKey.scope(),
|
2023-01-31 21:26:23 -05:00
|
|
|
});
|
|
|
|
|
|
|
|
Ok(Json(result))
|
2022-01-19 02:51:26 -08:00
|
|
|
}
|
|
|
|
|
2023-06-02 21:36:15 +02:00
|
|
|
async fn _organization_api_key_login(data: ConnectData, conn: &mut DbConn, ip: &ClientIp) -> JsonResult {
|
|
|
|
// Get the org via the client_id
|
|
|
|
let client_id = data.client_id.as_ref().unwrap();
|
2024-12-14 00:55:34 +01:00
|
|
|
let Some(org_uuid) = client_id.strip_prefix("organization.") else {
|
|
|
|
err!("Malformed client_id", format!("IP: {}.", ip.ip))
|
2023-06-02 21:36:15 +02:00
|
|
|
};
|
2024-12-14 00:55:34 +01:00
|
|
|
let Some(org_api_key) = OrganizationApiKey::find_by_org_uuid(org_uuid, conn).await else {
|
|
|
|
err!("Invalid client_id", format!("IP: {}.", ip.ip))
|
2023-06-02 21:36:15 +02:00
|
|
|
};
|
|
|
|
|
|
|
|
// Check API key.
|
|
|
|
let client_secret = data.client_secret.as_ref().unwrap();
|
|
|
|
if !org_api_key.check_valid_api_key(client_secret) {
|
|
|
|
err!("Incorrect client_secret", format!("IP: {}. Organization: {}.", ip.ip, org_api_key.org_uuid))
|
|
|
|
}
|
|
|
|
|
2024-09-12 15:18:39 +02:00
|
|
|
let claim = auth::generate_organization_api_key_login_claims(org_api_key.uuid, org_api_key.org_uuid);
|
|
|
|
let access_token = auth::encode_jwt(&claim);
|
2023-06-02 21:36:15 +02:00
|
|
|
|
|
|
|
Ok(Json(json!({
|
|
|
|
"access_token": access_token,
|
|
|
|
"expires_in": 3600,
|
|
|
|
"token_type": "Bearer",
|
2024-09-12 15:18:39 +02:00
|
|
|
"scope": AuthMethod::OrgApiKey.scope(),
|
2023-06-02 21:36:15 +02:00
|
|
|
})))
|
|
|
|
}
|
|
|
|
|
2019-07-25 20:47:58 +02:00
|
|
|
/// Retrieves an existing device or creates a new device from ConnectData and the User
|
2024-09-12 15:18:39 +02:00
|
|
|
async fn get_device(data: &ConnectData, conn: &mut DbConn, user: &User) -> ApiResult<(Device, bool)> {
|
2019-07-22 08:24:19 +02:00
|
|
|
// On iOS, device_type sends "iOS", on others it sends a number
|
2022-11-20 19:15:45 +01:00
|
|
|
// When unknown or unable to parse, return 14, which is 'Unknown Browser'
|
|
|
|
let device_type = util::try_parse_string(data.device_type.as_ref()).unwrap_or(14);
|
2019-07-22 08:24:19 +02:00
|
|
|
let device_id = data.device_identifier.clone().expect("No device id provided");
|
|
|
|
let device_name = data.device_name.clone().expect("No device name provided");
|
|
|
|
|
|
|
|
let mut new_device = false;
|
|
|
|
// Find device or create new
|
2022-03-03 21:00:10 +01:00
|
|
|
let device = match Device::find_by_uuid_and_user(&device_id, &user.uuid, conn).await {
|
|
|
|
Some(device) => device,
|
2019-07-22 08:24:19 +02:00
|
|
|
None => {
|
2024-09-12 15:18:39 +02:00
|
|
|
let device = Device::new(device_id, user.uuid.clone(), device_name, device_type);
|
2019-07-22 08:24:19 +02:00
|
|
|
new_device = true;
|
2024-09-12 15:18:39 +02:00
|
|
|
device
|
2019-07-22 08:24:19 +02:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2024-09-12 15:18:39 +02:00
|
|
|
Ok((device, new_device))
|
2019-07-22 08:24:19 +02:00
|
|
|
}
|
|
|
|
|
2021-11-16 17:07:55 +01:00
|
|
|
async fn twofactor_auth(
|
2024-01-01 19:41:40 +01:00
|
|
|
user: &User,
|
2018-12-30 23:34:31 +01:00
|
|
|
data: &ConnectData,
|
|
|
|
device: &mut Device,
|
2020-05-14 00:19:50 +02:00
|
|
|
ip: &ClientIp,
|
2022-05-20 23:39:47 +02:00
|
|
|
conn: &mut DbConn,
|
2018-12-30 23:34:31 +01:00
|
|
|
) -> ApiResult<Option<String>> {
|
2024-01-01 19:41:40 +01:00
|
|
|
let twofactors = TwoFactor::find_by_user(&user.uuid, conn).await;
|
2018-07-12 21:46:50 +02:00
|
|
|
|
|
|
|
// No twofactor token if twofactor is disabled
|
2018-09-13 21:55:23 +02:00
|
|
|
if twofactors.is_empty() {
|
2024-01-01 19:41:40 +01:00
|
|
|
enforce_2fa_policy(user, &user.uuid, device.atype, &ip.ip, conn).await?;
|
2018-07-12 21:46:50 +02:00
|
|
|
return Ok(None);
|
|
|
|
}
|
|
|
|
|
2024-09-18 20:03:15 +03:00
|
|
|
TwoFactorIncomplete::mark_incomplete(&user.uuid, &device.uuid, &device.name, device.atype, ip, conn).await?;
|
2021-10-25 01:36:05 -07:00
|
|
|
|
2019-05-20 21:24:29 +02:00
|
|
|
let twofactor_ids: Vec<_> = twofactors.iter().map(|tf| tf.atype).collect();
|
2023-10-05 20:08:26 +03:00
|
|
|
let selected_id = data.two_factor_provider.unwrap_or(twofactor_ids[0]); // If we aren't given a two factor provider, assume the first one
|
2018-07-12 21:46:50 +02:00
|
|
|
|
2018-10-17 22:25:28 +02:00
|
|
|
let twofactor_code = match data.two_factor_token {
|
|
|
|
Some(ref code) => code,
|
2024-09-12 15:18:39 +02:00
|
|
|
None => err_json!(_json_err_twofactor(&twofactor_ids, &user.uuid, data, conn).await?, "2FA token not provided"),
|
2018-07-12 21:46:50 +02:00
|
|
|
};
|
|
|
|
|
2021-03-31 21:18:35 +01:00
|
|
|
let selected_twofactor = twofactors.into_iter().find(|tf| tf.atype == selected_id && tf.enabled);
|
2018-07-12 21:46:50 +02:00
|
|
|
|
2019-03-03 16:09:15 +01:00
|
|
|
use crate::crypto::ct_eq;
|
2018-07-12 21:46:50 +02:00
|
|
|
|
2019-03-03 16:09:15 +01:00
|
|
|
let selected_data = _selected_data(selected_twofactor);
|
|
|
|
let mut remember = data.two_factor_remember.unwrap_or(0);
|
2018-07-12 21:46:50 +02:00
|
|
|
|
2019-03-03 16:09:15 +01:00
|
|
|
match TwoFactorType::from_i32(selected_id) {
|
2021-03-31 21:18:35 +01:00
|
|
|
Some(TwoFactorType::Authenticator) => {
|
2024-01-01 19:41:40 +01:00
|
|
|
authenticator::validate_totp_code_str(&user.uuid, twofactor_code, &selected_data?, ip, conn).await?
|
2021-03-31 21:18:35 +01:00
|
|
|
}
|
2024-01-01 19:41:40 +01:00
|
|
|
Some(TwoFactorType::Webauthn) => webauthn::validate_webauthn_login(&user.uuid, twofactor_code, conn).await?,
|
|
|
|
Some(TwoFactorType::YubiKey) => yubikey::validate_yubikey_login(twofactor_code, &selected_data?).await?,
|
2021-03-31 21:18:35 +01:00
|
|
|
Some(TwoFactorType::Duo) => {
|
2024-07-24 09:50:35 -05:00
|
|
|
match CONFIG.duo_use_iframe() {
|
|
|
|
true => {
|
|
|
|
// Legacy iframe prompt flow
|
2024-07-25 20:25:44 +02:00
|
|
|
duo::validate_duo_login(&user.email, twofactor_code, conn).await?
|
2024-07-24 09:50:35 -05:00
|
|
|
}
|
|
|
|
false => {
|
|
|
|
// OIDC based flow
|
|
|
|
duo_oidc::validate_duo_login(
|
2024-07-25 20:25:44 +02:00
|
|
|
&user.email,
|
2024-07-24 09:50:35 -05:00
|
|
|
twofactor_code,
|
|
|
|
data.client_id.as_ref().unwrap(),
|
|
|
|
data.device_identifier.as_ref().unwrap(),
|
|
|
|
conn,
|
|
|
|
)
|
|
|
|
.await?
|
|
|
|
}
|
|
|
|
}
|
2021-03-31 21:18:35 +01:00
|
|
|
}
|
|
|
|
Some(TwoFactorType::Email) => {
|
2024-01-01 19:41:40 +01:00
|
|
|
email::validate_email_code_str(&user.uuid, twofactor_code, &selected_data?, conn).await?
|
2021-03-31 21:18:35 +01:00
|
|
|
}
|
2018-07-12 21:46:50 +02:00
|
|
|
|
2019-03-03 16:09:15 +01:00
|
|
|
Some(TwoFactorType::Remember) => {
|
|
|
|
match device.twofactor_remember {
|
|
|
|
Some(ref code) if !CONFIG.disable_2fa_remember() && ct_eq(code, twofactor_code) => {
|
|
|
|
remember = 1; // Make sure we also return the token here, otherwise it will only remember the first time
|
|
|
|
}
|
2021-04-06 21:54:42 +01:00
|
|
|
_ => {
|
2021-11-16 17:07:55 +01:00
|
|
|
err_json!(
|
2024-07-24 09:50:35 -05:00
|
|
|
_json_err_twofactor(&twofactor_ids, &user.uuid, data, conn).await?,
|
2021-11-16 17:07:55 +01:00
|
|
|
"2FA Remember token not provided"
|
|
|
|
)
|
2021-04-06 21:54:42 +01:00
|
|
|
}
|
2018-07-12 21:46:50 +02:00
|
|
|
}
|
|
|
|
}
|
2022-11-20 19:15:45 +01:00
|
|
|
_ => err!(
|
|
|
|
"Invalid two factor provider",
|
|
|
|
ErrorEvent {
|
|
|
|
event: EventType::UserFailedLogIn2fa
|
|
|
|
}
|
|
|
|
),
|
2018-07-12 21:46:50 +02:00
|
|
|
}
|
|
|
|
|
2024-01-01 19:41:40 +01:00
|
|
|
TwoFactorIncomplete::mark_complete(&user.uuid, &device.uuid, conn).await?;
|
2021-10-25 01:36:05 -07:00
|
|
|
|
2024-09-12 15:18:39 +02:00
|
|
|
let two_factor = if !CONFIG.disable_2fa_remember() && remember == 1 {
|
|
|
|
Some(device.refresh_twofactor_remember())
|
2018-07-12 21:46:50 +02:00
|
|
|
} else {
|
|
|
|
device.delete_twofactor_remember();
|
2024-09-12 15:18:39 +02:00
|
|
|
None
|
|
|
|
};
|
|
|
|
Ok(two_factor)
|
2018-07-12 21:46:50 +02:00
|
|
|
}
|
|
|
|
|
2019-03-03 16:09:15 +01:00
|
|
|
fn _selected_data(tf: Option<TwoFactor>) -> ApiResult<String> {
|
2020-07-14 18:00:09 +02:00
|
|
|
tf.map(|t| t.data).map_res("Two factor doesn't exist")
|
2019-03-03 16:09:15 +01:00
|
|
|
}
|
|
|
|
|
2024-07-24 09:50:35 -05:00
|
|
|
async fn _json_err_twofactor(
|
|
|
|
providers: &[i32],
|
|
|
|
user_uuid: &str,
|
|
|
|
data: &ConnectData,
|
|
|
|
conn: &mut DbConn,
|
|
|
|
) -> ApiResult<Value> {
|
2018-07-12 21:46:50 +02:00
|
|
|
let mut result = json!({
|
2018-06-01 15:08:03 +02:00
|
|
|
"error" : "invalid_grant",
|
|
|
|
"error_description" : "Two factor required.",
|
2024-06-23 21:31:02 +02:00
|
|
|
"TwoFactorProviders" : providers.iter().map(ToString::to_string).collect::<Vec<String>>(),
|
|
|
|
"TwoFactorProviders2" : {}, // { "0" : null }
|
|
|
|
"MasterPasswordPolicy": {
|
|
|
|
"Object": "masterPasswordPolicy"
|
|
|
|
}
|
2018-07-12 21:46:50 +02:00
|
|
|
});
|
|
|
|
|
|
|
|
for provider in providers {
|
|
|
|
result["TwoFactorProviders2"][provider.to_string()] = Value::Null;
|
|
|
|
|
|
|
|
match TwoFactorType::from_i32(*provider) {
|
|
|
|
Some(TwoFactorType::Authenticator) => { /* Nothing to do for TOTP */ }
|
|
|
|
|
2021-06-07 23:34:00 +02:00
|
|
|
Some(TwoFactorType::Webauthn) if CONFIG.domain_set() => {
|
2024-01-01 19:41:40 +01:00
|
|
|
let request = webauthn::generate_webauthn_login(user_uuid, conn).await?;
|
2021-06-07 23:34:00 +02:00
|
|
|
result["TwoFactorProviders2"][provider.to_string()] = request.0;
|
|
|
|
}
|
|
|
|
|
2019-04-07 18:58:15 +02:00
|
|
|
Some(TwoFactorType::Duo) => {
|
2021-11-16 17:07:55 +01:00
|
|
|
let email = match User::find_by_uuid(user_uuid, conn).await {
|
2019-04-05 22:09:53 +02:00
|
|
|
Some(u) => u.email,
|
2019-04-07 18:58:15 +02:00
|
|
|
None => err!("User does not exist"),
|
2019-04-05 22:09:53 +02:00
|
|
|
};
|
|
|
|
|
2024-07-24 09:50:35 -05:00
|
|
|
match CONFIG.duo_use_iframe() {
|
|
|
|
true => {
|
|
|
|
// Legacy iframe prompt flow
|
|
|
|
let (signature, host) = duo::generate_duo_signature(&email, conn).await?;
|
|
|
|
result["TwoFactorProviders2"][provider.to_string()] = json!({
|
|
|
|
"Host": host,
|
|
|
|
"Signature": signature,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
false => {
|
|
|
|
// OIDC based flow
|
|
|
|
let auth_url = duo_oidc::get_duo_auth_url(
|
|
|
|
&email,
|
|
|
|
data.client_id.as_ref().unwrap(),
|
|
|
|
data.device_identifier.as_ref().unwrap(),
|
|
|
|
conn,
|
|
|
|
)
|
|
|
|
.await?;
|
|
|
|
|
|
|
|
result["TwoFactorProviders2"][provider.to_string()] = json!({
|
|
|
|
"AuthUrl": auth_url,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
2019-04-05 22:09:53 +02:00
|
|
|
}
|
|
|
|
|
2018-12-30 23:34:31 +01:00
|
|
|
Some(tf_type @ TwoFactorType::YubiKey) => {
|
2024-12-14 00:55:34 +01:00
|
|
|
let Some(twofactor) = TwoFactor::find_by_user_and_type(user_uuid, tf_type as i32, conn).await else {
|
|
|
|
err!("No YubiKey devices registered")
|
2018-11-17 01:25:07 -07:00
|
|
|
};
|
|
|
|
|
2019-08-03 18:47:52 +02:00
|
|
|
let yubikey_metadata: yubikey::YubikeyMetadata = serde_json::from_str(&twofactor.data)?;
|
2018-11-17 01:25:07 -07:00
|
|
|
|
2019-04-07 18:58:15 +02:00
|
|
|
result["TwoFactorProviders2"][provider.to_string()] = json!({
|
2024-06-23 21:31:02 +02:00
|
|
|
"Nfc": yubikey_metadata.nfc,
|
2019-04-07 18:58:15 +02:00
|
|
|
})
|
2018-07-12 21:46:50 +02:00
|
|
|
}
|
|
|
|
|
2019-08-04 16:56:39 +02:00
|
|
|
Some(tf_type @ TwoFactorType::Email) => {
|
2024-12-14 00:55:34 +01:00
|
|
|
let Some(twofactor) = TwoFactor::find_by_user_and_type(user_uuid, tf_type as i32, conn).await else {
|
|
|
|
err!("No twofactor email registered")
|
2019-08-04 16:56:39 +02:00
|
|
|
};
|
2019-08-03 18:47:52 +02:00
|
|
|
|
2019-10-15 21:19:49 +02:00
|
|
|
// Send email immediately if email is the only 2FA option
|
|
|
|
if providers.len() == 1 {
|
2024-01-01 19:41:40 +01:00
|
|
|
email::send_token(user_uuid, conn).await?
|
2019-10-15 21:19:49 +02:00
|
|
|
}
|
2019-08-03 18:47:52 +02:00
|
|
|
|
2024-01-01 19:41:40 +01:00
|
|
|
let email_data = email::EmailTokenData::from_json(&twofactor.data)?;
|
2019-08-03 18:47:52 +02:00
|
|
|
result["TwoFactorProviders2"][provider.to_string()] = json!({
|
2019-08-03 20:09:20 +02:00
|
|
|
"Email": email::obscure_email(&email_data.email),
|
2019-08-03 18:47:52 +02:00
|
|
|
})
|
2019-08-04 16:56:39 +02:00
|
|
|
}
|
|
|
|
|
2018-07-12 21:46:50 +02:00
|
|
|
_ => {}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
Ok(result)
|
2018-06-01 15:08:03 +02:00
|
|
|
}
|
|
|
|
|
2022-03-20 18:51:24 +01:00
|
|
|
#[post("/accounts/prelogin", data = "<data>")]
|
2024-06-23 21:31:02 +02:00
|
|
|
async fn prelogin(data: Json<PreloginData>, conn: DbConn) -> Json<Value> {
|
2022-03-20 18:51:24 +01:00
|
|
|
_prelogin(data, conn).await
|
|
|
|
}
|
|
|
|
|
2022-11-14 17:22:37 +01:00
|
|
|
#[post("/accounts/register", data = "<data>")]
|
2024-06-23 21:31:02 +02:00
|
|
|
async fn identity_register(data: Json<RegisterData>, conn: DbConn) -> JsonResult {
|
2022-11-14 17:22:37 +01:00
|
|
|
_register(data, conn).await
|
|
|
|
}
|
|
|
|
|
2022-01-19 02:51:26 -08:00
|
|
|
// https://github.com/bitwarden/jslib/blob/master/common/src/models/request/tokenRequest.ts
|
2020-03-22 15:04:25 -07:00
|
|
|
// https://github.com/bitwarden/mobile/blob/master/src/Core/Models/Request/TokenRequest.cs
|
2021-11-07 18:53:39 +01:00
|
|
|
#[derive(Debug, Clone, Default, FromForm)]
|
2018-02-10 01:00:55 +01:00
|
|
|
struct ConnectData {
|
2021-11-07 18:53:39 +01:00
|
|
|
#[field(name = uncased("grant_type"))]
|
|
|
|
#[field(name = uncased("granttype"))]
|
|
|
|
grant_type: String, // refresh_token, password, client_credentials (API key)
|
2018-02-10 01:00:55 +01:00
|
|
|
|
2018-10-17 22:25:28 +02:00
|
|
|
// Needed for grant_type="refresh_token"
|
2021-11-07 18:53:39 +01:00
|
|
|
#[field(name = uncased("refresh_token"))]
|
|
|
|
#[field(name = uncased("refreshtoken"))]
|
2018-10-17 22:25:28 +02:00
|
|
|
refresh_token: Option<String>,
|
|
|
|
|
2022-01-19 02:51:26 -08:00
|
|
|
// Needed for grant_type = "password" | "client_credentials"
|
2021-11-07 18:53:39 +01:00
|
|
|
#[field(name = uncased("client_id"))]
|
|
|
|
#[field(name = uncased("clientid"))]
|
|
|
|
client_id: Option<String>, // web, cli, desktop, browser, mobile
|
|
|
|
#[field(name = uncased("client_secret"))]
|
|
|
|
#[field(name = uncased("clientsecret"))]
|
|
|
|
client_secret: Option<String>,
|
|
|
|
#[field(name = uncased("password"))]
|
2018-10-17 22:25:28 +02:00
|
|
|
password: Option<String>,
|
2021-11-07 18:53:39 +01:00
|
|
|
#[field(name = uncased("scope"))]
|
2018-10-17 22:25:28 +02:00
|
|
|
scope: Option<String>,
|
2021-11-07 18:53:39 +01:00
|
|
|
#[field(name = uncased("username"))]
|
2018-10-17 22:25:28 +02:00
|
|
|
username: Option<String>,
|
|
|
|
|
2021-11-07 18:53:39 +01:00
|
|
|
#[field(name = uncased("device_identifier"))]
|
|
|
|
#[field(name = uncased("deviceidentifier"))]
|
2018-10-17 22:25:28 +02:00
|
|
|
device_identifier: Option<String>,
|
2021-11-07 18:53:39 +01:00
|
|
|
#[field(name = uncased("device_name"))]
|
|
|
|
#[field(name = uncased("devicename"))]
|
2018-10-17 22:25:28 +02:00
|
|
|
device_name: Option<String>,
|
2021-11-07 18:53:39 +01:00
|
|
|
#[field(name = uncased("device_type"))]
|
|
|
|
#[field(name = uncased("devicetype"))]
|
2018-10-17 22:25:28 +02:00
|
|
|
device_type: Option<String>,
|
2021-12-28 00:48:33 +01:00
|
|
|
#[allow(unused)]
|
2021-11-07 18:53:39 +01:00
|
|
|
#[field(name = uncased("device_push_token"))]
|
|
|
|
#[field(name = uncased("devicepushtoken"))]
|
2021-11-16 17:07:55 +01:00
|
|
|
_device_push_token: Option<String>, // Unused; mobile device push not yet supported.
|
2018-10-17 22:25:28 +02:00
|
|
|
|
|
|
|
// Needed for two-factor auth
|
2021-11-07 18:53:39 +01:00
|
|
|
#[field(name = uncased("two_factor_provider"))]
|
|
|
|
#[field(name = uncased("twofactorprovider"))]
|
2018-10-17 22:25:28 +02:00
|
|
|
two_factor_provider: Option<i32>,
|
2021-11-07 18:53:39 +01:00
|
|
|
#[field(name = uncased("two_factor_token"))]
|
|
|
|
#[field(name = uncased("twofactortoken"))]
|
2018-10-17 22:25:28 +02:00
|
|
|
two_factor_token: Option<String>,
|
2021-11-07 18:53:39 +01:00
|
|
|
#[field(name = uncased("two_factor_remember"))]
|
|
|
|
#[field(name = uncased("twofactorremember"))]
|
2018-10-17 22:25:28 +02:00
|
|
|
two_factor_remember: Option<i32>,
|
2023-08-04 21:12:23 +02:00
|
|
|
#[field(name = uncased("authrequest"))]
|
|
|
|
auth_request: Option<String>,
|
2023-08-30 16:13:09 +02:00
|
|
|
// Needed for authorization code
|
|
|
|
#[form(field = uncased("code"))]
|
|
|
|
code: Option<String>,
|
2018-07-12 21:46:50 +02:00
|
|
|
}
|
2018-10-17 22:25:28 +02:00
|
|
|
fn _check_is_some<T>(value: &Option<T>, msg: &str) -> EmptyResult {
|
|
|
|
if value.is_none() {
|
|
|
|
err!(msg)
|
2018-02-10 01:00:55 +01:00
|
|
|
}
|
2018-10-17 22:25:28 +02:00
|
|
|
Ok(())
|
2018-02-17 20:47:13 +01:00
|
|
|
}
|
2023-08-30 16:13:09 +02:00
|
|
|
|
2024-09-12 15:18:39 +02:00
|
|
|
// Deprecated but still needed for Mobile apps
|
2023-08-30 16:13:09 +02:00
|
|
|
#[get("/account/prevalidate")]
|
2024-09-12 15:18:39 +02:00
|
|
|
fn _prevalidate() -> JsonResult {
|
|
|
|
prevalidate()
|
2023-08-30 16:13:09 +02:00
|
|
|
}
|
|
|
|
|
2024-09-12 15:18:39 +02:00
|
|
|
#[get("/sso/prevalidate")]
|
|
|
|
fn prevalidate() -> JsonResult {
|
|
|
|
if CONFIG.sso_enabled() {
|
|
|
|
let sso_token = sso::encode_ssotoken_claims();
|
|
|
|
Ok(Json(json!({
|
|
|
|
"token": sso_token,
|
|
|
|
})))
|
|
|
|
} else {
|
|
|
|
err!("SSO sign-in is not available")
|
|
|
|
}
|
|
|
|
}
|
2023-08-30 16:13:09 +02:00
|
|
|
|
2024-09-12 15:18:39 +02:00
|
|
|
#[get("/connect/oidc-signin?<code>&<state>", rank = 1)]
|
|
|
|
async fn oidcsignin(code: String, state: String, conn: DbConn) -> ApiResult<Redirect> {
|
|
|
|
oidcsignin_redirect(
|
|
|
|
state.clone(),
|
|
|
|
sso::OIDCCodeWrapper::Ok {
|
|
|
|
code,
|
|
|
|
state,
|
|
|
|
},
|
|
|
|
&conn,
|
|
|
|
)
|
|
|
|
.await
|
|
|
|
}
|
2023-08-30 16:13:09 +02:00
|
|
|
|
2024-09-12 15:18:39 +02:00
|
|
|
// Bitwarden client appear to only care for code and state so we pipe it through
|
|
|
|
// cf: https://github.com/bitwarden/clients/blob/8e46ef1ae5be8b62b0d3d0b9d1b1c62088a04638/libs/angular/src/auth/components/sso.component.ts#L68C11-L68C23)
|
|
|
|
#[get("/connect/oidc-signin?<state>&<error>&<error_description>", rank = 2)]
|
|
|
|
async fn oidcsignin_error(
|
|
|
|
state: String,
|
|
|
|
error: String,
|
|
|
|
error_description: Option<String>,
|
|
|
|
conn: DbConn,
|
|
|
|
) -> ApiResult<Redirect> {
|
|
|
|
oidcsignin_redirect(
|
|
|
|
state.clone(),
|
|
|
|
sso::OIDCCodeWrapper::Error {
|
|
|
|
state,
|
|
|
|
error,
|
|
|
|
error_description,
|
|
|
|
},
|
|
|
|
&conn,
|
|
|
|
)
|
|
|
|
.await
|
2023-08-30 16:13:09 +02:00
|
|
|
}
|
|
|
|
|
2024-09-12 15:18:39 +02:00
|
|
|
// iss and scope parameters are needed for redirection to work on IOS.
|
|
|
|
async fn oidcsignin_redirect(state: String, wrapper: sso::OIDCCodeWrapper, conn: &DbConn) -> ApiResult<Redirect> {
|
|
|
|
let code = sso::encode_code_claims(wrapper);
|
2023-08-30 16:13:09 +02:00
|
|
|
|
2024-09-12 15:18:39 +02:00
|
|
|
let nonce = match SsoNonce::find(&state, conn).await {
|
|
|
|
Some(n) => n,
|
|
|
|
None => err!(format!("Failed to retrive redirect_uri with {state}")),
|
2023-08-30 16:13:09 +02:00
|
|
|
};
|
2024-09-12 15:18:39 +02:00
|
|
|
|
|
|
|
let mut url = match url::Url::parse(&nonce.redirect_uri) {
|
|
|
|
Ok(url) => url,
|
|
|
|
Err(err) => err!(format!("Failed to parse redirect uri ({}): {err}", nonce.redirect_uri)),
|
2023-08-30 16:13:09 +02:00
|
|
|
};
|
|
|
|
|
2024-09-12 15:18:39 +02:00
|
|
|
url.query_pairs_mut()
|
|
|
|
.append_pair("code", &code)
|
|
|
|
.append_pair("state", &state)
|
|
|
|
.append_pair("scope", &AuthMethod::Sso.scope())
|
|
|
|
.append_pair("iss", &CONFIG.domain());
|
2023-08-30 16:13:09 +02:00
|
|
|
|
2024-09-12 15:18:39 +02:00
|
|
|
debug!("Redirection to {url}");
|
2023-08-30 16:13:09 +02:00
|
|
|
|
2024-09-12 15:18:39 +02:00
|
|
|
Ok(Redirect::temporary(String::from(url)))
|
2023-08-30 16:13:09 +02:00
|
|
|
}
|
|
|
|
|
2024-09-12 15:18:39 +02:00
|
|
|
#[derive(Debug, Clone, Default, FromForm)]
|
2023-08-30 16:13:09 +02:00
|
|
|
struct AuthorizeData {
|
|
|
|
#[field(name = uncased("client_id"))]
|
|
|
|
#[field(name = uncased("clientid"))]
|
2024-09-12 15:18:39 +02:00
|
|
|
client_id: String,
|
2023-08-30 16:13:09 +02:00
|
|
|
#[field(name = uncased("redirect_uri"))]
|
|
|
|
#[field(name = uncased("redirecturi"))]
|
2024-09-12 15:18:39 +02:00
|
|
|
redirect_uri: String,
|
2023-08-30 16:13:09 +02:00
|
|
|
#[allow(unused)]
|
|
|
|
response_type: Option<String>,
|
|
|
|
#[allow(unused)]
|
|
|
|
scope: Option<String>,
|
2024-09-12 15:18:39 +02:00
|
|
|
state: String,
|
2023-08-30 16:13:09 +02:00
|
|
|
#[allow(unused)]
|
|
|
|
code_challenge: Option<String>,
|
|
|
|
#[allow(unused)]
|
|
|
|
code_challenge_method: Option<String>,
|
|
|
|
#[allow(unused)]
|
|
|
|
response_mode: Option<String>,
|
|
|
|
#[allow(unused)]
|
|
|
|
domain_hint: Option<String>,
|
|
|
|
#[allow(unused)]
|
|
|
|
#[field(name = uncased("ssoToken"))]
|
2024-09-12 15:18:39 +02:00
|
|
|
sso_token: Option<String>,
|
2023-08-30 16:13:09 +02:00
|
|
|
}
|
|
|
|
|
2024-09-12 15:18:39 +02:00
|
|
|
// The `redirect_uri` will change depending of the client (web, android, ios ..)
|
2023-08-30 16:13:09 +02:00
|
|
|
#[get("/connect/authorize?<data..>")]
|
2024-09-12 15:18:39 +02:00
|
|
|
async fn authorize(data: AuthorizeData, conn: DbConn) -> ApiResult<Redirect> {
|
|
|
|
let AuthorizeData {
|
|
|
|
client_id,
|
|
|
|
redirect_uri,
|
|
|
|
state,
|
|
|
|
..
|
|
|
|
} = data;
|
2023-08-30 16:13:09 +02:00
|
|
|
|
2024-09-12 15:18:39 +02:00
|
|
|
let auth_url = sso::authorize_url(state, &client_id, &redirect_uri, conn).await?;
|
2023-08-30 16:13:09 +02:00
|
|
|
|
2024-09-12 15:18:39 +02:00
|
|
|
Ok(Redirect::temporary(String::from(auth_url)))
|
2023-08-30 16:13:09 +02:00
|
|
|
}
|