diff --git a/conduwuit-example.toml b/conduwuit-example.toml index 28e7012b..96578da3 100644 --- a/conduwuit-example.toml +++ b/conduwuit-example.toml @@ -645,6 +645,22 @@ # #openid_token_ttl = 3600 +# Allow an existing session to mint a login token for another client. +# This requires interactive authentication, but has security ramifications +# as a malicious client could use the mechanism to spawn more than one +# session. +# Enabled by default. +# +#login_via_existing_session = true + +# Login token expiration/TTL in milliseconds. +# +# These are short-lived tokens for the m.login.token endpoint. +# This is used to allow existing sessions to create new sessions. +# see login_via_existing_session. +# +#login_token_ttl = 120000 + # Static TURN username to provide the client if not using a shared secret # ("turn_secret"), It is recommended to use a shared secret over static # credentials. diff --git a/src/api/client/capabilities.rs b/src/api/client/capabilities.rs index e122611f..87cdb43d 100644 --- a/src/api/client/capabilities.rs +++ b/src/api/client/capabilities.rs @@ -32,8 +32,9 @@ pub(crate) async fn get_capabilities_route( // we do not implement 3PID stuff capabilities.thirdparty_id_changes = ThirdPartyIdChangesCapability { enabled: false }; - // we dont support generating tokens yet - capabilities.get_login_token = GetLoginTokenCapability { enabled: false }; + capabilities.get_login_token = GetLoginTokenCapability { + enabled: services.server.config.login_via_existing_session, + }; // MSC4133 capability capabilities diff --git a/src/api/client/session.rs b/src/api/client/session.rs index 21b8786c..4881ade7 100644 --- a/src/api/client/session.rs +++ b/src/api/client/session.rs @@ -1,3 +1,5 @@ +use std::time::Duration; + use axum::extract::State; use axum_client_ip::InsecureClientIp; use conduwuit::{debug, err, info, utils::ReadyExt, warn, Err}; @@ -6,9 +8,10 @@ use ruma::{ api::client::{ error::ErrorKind, session::{ + get_login_token, get_login_types::{ self, - v3::{ApplicationServiceLoginType, PasswordLoginType}, + v3::{ApplicationServiceLoginType, PasswordLoginType, TokenLoginType}, }, login::{ self, @@ -16,10 +19,11 @@ use ruma::{ }, logout, logout_all, }, - uiaa::UserIdentifier, + uiaa, }, OwnedUserId, UserId, }; +use service::uiaa::SESSION_ID_LENGTH; use super::{DEVICE_ID_LENGTH, TOKEN_LENGTH}; use crate::{utils, utils::hash, Error, Result, Ruma}; @@ -30,12 +34,16 @@ use crate::{utils, utils::hash, Error, Result, Ruma}; /// the `type` field when logging in. #[tracing::instrument(skip_all, fields(%client), name = "login")] pub(crate) async fn get_login_types_route( + State(services): State, InsecureClientIp(client): InsecureClientIp, _body: Ruma, ) -> Result { Ok(get_login_types::v3::Response::new(vec![ get_login_types::v3::LoginType::Password(PasswordLoginType::default()), get_login_types::v3::LoginType::ApplicationService(ApplicationServiceLoginType::default()), + get_login_types::v3::LoginType::Token(TokenLoginType { + get_login_token: services.server.config.login_via_existing_session, + }), ])) } @@ -70,7 +78,9 @@ pub(crate) async fn login_route( .. }) => { debug!("Got password login type"); - let user_id = if let Some(UserIdentifier::UserIdOrLocalpart(user_id)) = identifier { + let user_id = if let Some(uiaa::UserIdentifier::UserIdOrLocalpart(user_id)) = + identifier + { UserId::parse_with_server_name( user_id.to_lowercase(), services.globals.server_name(), @@ -99,11 +109,12 @@ pub(crate) async fn login_route( user_id }, - | login::v3::LoginInfo::Token(login::v3::Token { token: _ }) => { + | login::v3::LoginInfo::Token(login::v3::Token { token }) => { debug!("Got token login type"); - return Err!(Request(Unknown( - "Token login is not supported." - ))); + if !services.server.config.login_via_existing_session { + return Err!(Request(Unknown("Token login is not enabled."))); + } + services.users.find_from_login_token(token).await? }, #[allow(deprecated)] | login::v3::LoginInfo::ApplicationService(login::v3::ApplicationService { @@ -111,21 +122,22 @@ pub(crate) async fn login_route( user, }) => { debug!("Got appservice login type"); - let user_id = if let Some(UserIdentifier::UserIdOrLocalpart(user_id)) = identifier { - UserId::parse_with_server_name( - user_id.to_lowercase(), - services.globals.server_name(), - ) - } else if let Some(user) = user { - OwnedUserId::parse(user) - } else { - warn!("Bad login type: {:?}", &body.login_info); - return Err(Error::BadRequest(ErrorKind::forbidden(), "Bad login type.")); - } - .map_err(|e| { - warn!("Failed to parse username from appservice logging in: {e}"); - Error::BadRequest(ErrorKind::InvalidUsername, "Username is invalid.") - })?; + let user_id = + if let Some(uiaa::UserIdentifier::UserIdOrLocalpart(user_id)) = identifier { + UserId::parse_with_server_name( + user_id.to_lowercase(), + services.globals.server_name(), + ) + } else if let Some(user) = user { + OwnedUserId::parse(user) + } else { + warn!("Bad login type: {:?}", &body.login_info); + return Err(Error::BadRequest(ErrorKind::forbidden(), "Bad login type.")); + } + .map_err(|e| { + warn!("Failed to parse username from appservice logging in: {e}"); + Error::BadRequest(ErrorKind::InvalidUsername, "Username is invalid.") + })?; if let Some(ref info) = body.appservice_info { if !info.is_user_match(&user_id) { @@ -217,6 +229,74 @@ pub(crate) async fn login_route( }) } +/// # `POST /_matrix/client/v1/login/get_token` +/// +/// Allows a logged-in user to get a short-lived token which can be used +/// to log in with the m.login.token flow. +/// +/// +#[tracing::instrument(skip_all, fields(%client), name = "login_token")] +pub(crate) async fn login_token_route( + State(services): State, + InsecureClientIp(client): InsecureClientIp, + body: Ruma, +) -> Result { + if !services.server.config.login_via_existing_session { + return Err!(Request(Unknown("Login via an existing session is not enabled"))); + } + // Authentication for this endpoint was made optional, but we need + // authentication. + let sender_user = body + .sender_user + .as_ref() + .ok_or_else(|| Error::BadRequest(ErrorKind::MissingToken, "Missing access token."))?; + let sender_device = body.sender_device.as_ref().expect("user is authenticated"); + + // This route SHOULD have UIA + // TODO: How do we make only UIA sessions that have not been used before valid? + + let mut uiaainfo = uiaa::UiaaInfo { + flows: vec![uiaa::AuthFlow { stages: vec![uiaa::AuthType::Password] }], + completed: Vec::new(), + params: Box::default(), + session: None, + auth_error: None, + }; + + if let Some(auth) = &body.auth { + let (worked, uiaainfo) = services + .uiaa + .try_auth(sender_user, sender_device, auth, &uiaainfo) + .await?; + + if !worked { + return Err(Error::Uiaa(uiaainfo)); + } + + // Success! + } else if let Some(json) = body.json_body { + uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH)); + services + .uiaa + .create(sender_user, sender_device, &uiaainfo, &json); + + return Err(Error::Uiaa(uiaainfo)); + } else { + return Err(Error::BadRequest(ErrorKind::NotJson, "Not json.")); + } + + let login_token = utils::random_string(TOKEN_LENGTH); + + let expires_in = services + .users + .create_login_token(sender_user, &login_token)?; + + Ok(get_login_token::v1::Response { + expires_in: Duration::from_millis(expires_in), + login_token, + }) +} + /// # `POST /_matrix/client/v3/logout` /// /// Log out the current device. diff --git a/src/api/router.rs b/src/api/router.rs index e7cd368d..7855ddfa 100644 --- a/src/api/router.rs +++ b/src/api/router.rs @@ -34,6 +34,7 @@ pub fn build(router: Router, server: &Server) -> Router { .ruma_route(&client::register_route) .ruma_route(&client::get_login_types_route) .ruma_route(&client::login_route) + .ruma_route(&client::login_token_route) .ruma_route(&client::whoami_route) .ruma_route(&client::logout_route) .ruma_route(&client::logout_all_route) diff --git a/src/core/config/mod.rs b/src/core/config/mod.rs index d65d3812..84b88c7c 100644 --- a/src/core/config/mod.rs +++ b/src/core/config/mod.rs @@ -767,6 +767,24 @@ pub struct Config { #[serde(default = "default_openid_token_ttl")] pub openid_token_ttl: u64, + /// Allow an existing session to mint a login token for another client. + /// This requires interactive authentication, but has security ramifications + /// as a malicious client could use the mechanism to spawn more than one + /// session. + /// Enabled by default. + #[serde(default = "true_fn")] + pub login_via_existing_session: bool, + + /// Login token expiration/TTL in milliseconds. + /// + /// These are short-lived tokens for the m.login.token endpoint. + /// This is used to allow existing sessions to create new sessions. + /// see login_via_existing_session. + /// + /// default: 120000 + #[serde(default = "default_login_token_ttl")] + pub login_token_ttl: u64, + /// Static TURN username to provide the client if not using a shared secret /// ("turn_secret"), It is recommended to use a shared secret over static /// credentials. @@ -2373,6 +2391,8 @@ fn default_notification_push_path() -> String { "/_matrix/push/v1/notify".to_own fn default_openid_token_ttl() -> u64 { 60 * 60 } +fn default_login_token_ttl() -> u64 { 2 * 60 * 1000 } + fn default_turn_ttl() -> u64 { 60 * 60 * 24 } fn default_presence_idle_timeout_s() -> u64 { 5 * 60 } diff --git a/src/database/maps.rs b/src/database/maps.rs index bc409919..19e19955 100644 --- a/src/database/maps.rs +++ b/src/database/maps.rs @@ -365,6 +365,10 @@ pub(super) static MAPS: &[Descriptor] = &[ name: "openidtoken_expiresatuserid", ..descriptor::RANDOM_SMALL }, + Descriptor { + name: "logintoken_expiresatuserid", + ..descriptor::RANDOM_SMALL + }, Descriptor { name: "userroomid_highlightcount", ..descriptor::RANDOM diff --git a/src/service/users/mod.rs b/src/service/users/mod.rs index fe064d9c..971cea7c 100644 --- a/src/service/users/mod.rs +++ b/src/service/users/mod.rs @@ -41,6 +41,7 @@ struct Data { keyid_key: Arc, onetimekeyid_onetimekeys: Arc, openidtoken_expiresatuserid: Arc, + logintoken_expiresatuserid: Arc, todeviceid_events: Arc, token_userdeviceid: Arc, userdeviceid_metadata: Arc, @@ -76,6 +77,7 @@ impl crate::Service for Service { keyid_key: args.db["keyid_key"].clone(), onetimekeyid_onetimekeys: args.db["onetimekeyid_onetimekeys"].clone(), openidtoken_expiresatuserid: args.db["openidtoken_expiresatuserid"].clone(), + logintoken_expiresatuserid: args.db["logintoken_expiresatuserid"].clone(), todeviceid_events: args.db["todeviceid_events"].clone(), token_userdeviceid: args.db["token_userdeviceid"].clone(), userdeviceid_metadata: args.db["userdeviceid_metadata"].clone(), @@ -941,6 +943,54 @@ impl Service { .map_err(|e| err!(Database("User ID in openid_userid is invalid. {e}"))) } + /// Creates a short-lived login token, which can be used to log in using the + /// `m.login.token` mechanism. + pub fn create_login_token(&self, user_id: &UserId, token: &str) -> Result { + use std::num::Saturating as Sat; + + let expires_in = self.services.server.config.login_token_ttl; + let expires_at = Sat(utils::millis_since_unix_epoch()) + Sat(expires_in); + + let mut value = expires_at.0.to_be_bytes().to_vec(); + value.extend_from_slice(user_id.as_bytes()); + + self.db + .logintoken_expiresatuserid + .insert(token.as_bytes(), value.as_slice()); + + Ok(expires_in) + } + + /// Find out which user a login token belongs to. + /// Removes the token to prevent double-use attacks. + pub async fn find_from_login_token(&self, token: &str) -> Result { + let Ok(value) = self.db.logintoken_expiresatuserid.get(token).await else { + return Err!(Request(Unauthorized("Login token is unrecognised"))); + }; + + let (expires_at_bytes, user_bytes) = value.split_at(0_u64.to_be_bytes().len()); + let expires_at = u64::from_be_bytes( + expires_at_bytes + .try_into() + .map_err(|e| err!(Database("expires_at in login_userid is invalid u64. {e}")))?, + ); + + if expires_at < utils::millis_since_unix_epoch() { + debug_warn!("Login token is expired, removing"); + self.db.openidtoken_expiresatuserid.remove(token.as_bytes()); + + return Err!(Request(Unauthorized("Login token is expired"))); + } + + self.db.openidtoken_expiresatuserid.remove(token.as_bytes()); + + let user_string = utils::string_from_bytes(user_bytes) + .map_err(|e| err!(Database("User ID in login_userid is invalid unicode. {e}")))?; + + OwnedUserId::try_from(user_string) + .map_err(|e| err!(Database("User ID in login_userid is invalid. {e}"))) + } + /// Gets a specific user profile key pub async fn profile_key( &self,