]> git.proxmox.com Git - proxmox-backup.git/blobdiff - src/config/tfa.rs
typo fixes all over the place
[proxmox-backup.git] / src / config / tfa.rs
index 0abd4b0ebb0b677347ad88407cc304e7e7965b6d..6b65f6a555b354188178ce1fe65399fff475322a 100644 (file)
@@ -1,6 +1,7 @@
 use std::collections::HashMap;
 use std::fs::File;
 use std::io::{self, Read, Seek, SeekFrom};
+use std::os::unix::fs::OpenOptionsExt;
 use std::os::unix::io::AsRawFd;
 use std::path::PathBuf;
 use std::time::Duration;
@@ -12,11 +13,12 @@ use openssl::pkey::PKey;
 use openssl::sign::Signer;
 use serde::{de::Deserializer, Deserialize, Serialize};
 use serde_json::Value;
-use webauthn_rs::Webauthn;
+use webauthn_rs::{proto::UserVerificationPolicy, Webauthn};
 
 use webauthn_rs::proto::Credential as WebauthnCredential;
 
 use proxmox::api::api;
+use proxmox::api::schema::{Updatable, Updater};
 use proxmox::sys::error::SysError;
 use proxmox::tools::fs::CreateOptions;
 use proxmox::tools::tfa::totp::Totp;
@@ -57,6 +59,21 @@ pub fn read() -> Result<TfaConfig, Error> {
     Ok(serde_json::from_reader(file)?)
 }
 
+/// Get the webauthn config with a digest.
+///
+/// This is meant only for configuration updates, which currently only means webauthn updates.
+/// Since this is meant to be done only once (since changes will lock out users), this should be
+/// used rarely, since the digest calculation is currently a bit more involved.
+pub fn webauthn_config() -> Result<Option<(WebauthnConfig, [u8; 32])>, Error>{
+    Ok(match read()?.webauthn {
+        Some(wa) => {
+            let digest = wa.digest()?;
+            Some((wa, digest))
+        }
+        None => None,
+    })
+}
+
 /// Requires the write lock to be held.
 pub fn write(data: &TfaConfig) -> Result<(), Error> {
     let options = CreateOptions::new().perm(Mode::from_bits_truncate(0o0600));
@@ -70,7 +87,10 @@ pub struct U2fConfig {
     appid: String,
 }
 
-#[derive(Clone, Deserialize, Serialize)]
+#[api]
+#[derive(Clone, Deserialize, Serialize, Updater)]
+#[serde(deny_unknown_fields)]
+/// Server side webauthn server configuration.
 pub struct WebauthnConfig {
     /// Relying party name. Any text identifier.
     ///
@@ -89,6 +109,13 @@ pub struct WebauthnConfig {
     id: String,
 }
 
+impl WebauthnConfig {
+    pub fn digest(&self) -> Result<[u8; 32], Error> {
+        let digest_data = crate::tools::json::to_canonical_json(&serde_json::to_value(self)?)?;
+        Ok(openssl::sha::sha256(&digest_data))
+    }
+}
+
 /// For now we just implement this on the configuration this way.
 ///
 /// Note that we may consider changing this so `get_origin` returns the `Host:` header provided by
@@ -247,6 +274,18 @@ impl TfaConfig {
             None => bail!("no 2nd factor available for user '{}'", userid),
         }
     }
+
+    /// Remove non-existent users.
+    pub fn cleanup_users(&mut self, config: &proxmox::api::section_config::SectionConfigData) {
+        use crate::config::user::User;
+        self.users
+            .retain(|user, _| config.lookup::<User>("user", user.as_str()).is_ok());
+    }
+
+    /// Remove a user. Returns `true` if the user actually existed.
+    pub fn remove_user(&mut self, user: &Userid) -> bool {
+        self.users.remove(user).is_some()
+    }
 }
 
 #[api]
@@ -258,8 +297,12 @@ pub struct TfaInfo {
     pub id: String,
 
     /// User chosen description for this entry.
+    #[serde(skip_serializing_if = "String::is_empty")]
     pub description: String,
 
+    /// Creation time of this entry as unix epoch.
+    pub created: i64,
+
     /// Whether this TFA entry is currently enabled.
     #[serde(skip_serializing_if = "is_default_tfa_enable")]
     #[serde(default = "default_tfa_enable")]
@@ -268,11 +311,12 @@ pub struct TfaInfo {
 
 impl TfaInfo {
     /// For recovery keys we have a fixed entry.
-    pub(crate) fn recovery() -> Self {
+    pub(crate) fn recovery(created: i64) -> Self {
         Self {
             id: "recovery".to_string(),
-            description: "recovery keys".to_string(),
+            description: String::new(),
             enable: true,
+            created,
         }
     }
 }
@@ -298,6 +342,7 @@ impl<T> TfaEntry<T> {
                 id: Uuid::generate().to_string(),
                 enable: true,
                 description,
+                created: proxmox::tools::time::epoch_i64(),
             },
             entry,
         }
@@ -451,8 +496,6 @@ impl TfaUserChallengeData {
     /// Load the user's current challenges with the intent to create a challenge (create the file
     /// if it does not exist), and keep a lock on the file.
     fn open(userid: &Userid) -> Result<Self, Error> {
-        use std::os::unix::fs::OpenOptionsExt;
-
         crate::tools::create_run_dir()?;
         let options = CreateOptions::new().perm(Mode::from_bits_truncate(0o0600));
         proxmox::tools::fs::create_path(CHALLENGE_DATA_PATH, Some(options.clone()), Some(options))
@@ -506,7 +549,13 @@ impl TfaUserChallengeData {
     /// `open` without creating the file if it doesn't exist, to finish WA authentications.
     fn open_no_create(userid: &Userid) -> Result<Option<Self>, Error> {
         let path = Self::challenge_data_path(userid);
-        let mut file = match File::open(&path) {
+        let mut file = match std::fs::OpenOptions::new()
+            .read(true)
+            .write(true)
+            .truncate(false)
+            .mode(0o600)
+            .open(&path)
+        {
             Ok(file) => file,
             Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(None),
             Err(err) => return Err(err.into()),
@@ -541,7 +590,7 @@ impl TfaUserChallengeData {
     }
 
     /// Save the current data. Note that we do not replace the file here since we lock the file
-    /// itself, as it is in `/run`, and the typicall error case for this particular situation
+    /// itself, as it is in `/run`, and the typical error case for this particular situation
     /// (machine loses power) simply prevents some login, but that'll probably fail anyway for
     /// other reasons then...
     ///
@@ -659,9 +708,13 @@ pub struct TfaUserData {
 }
 
 impl TfaUserData {
-    /// Shortcut for the option type.
-    pub fn has_recovery(&self) -> bool {
-        !Recovery::option_is_empty(&self.recovery)
+    /// Shortcut to get the recovery entry only if it is not empty!
+    pub fn recovery(&self) -> Option<&Recovery> {
+        if Recovery::option_is_empty(&self.recovery) {
+            None
+        } else {
+            self.recovery.as_ref()
+        }
     }
 
     /// `true` if no second factors exist
@@ -669,7 +722,7 @@ impl TfaUserData {
         self.totp.is_empty()
             && self.u2f.is_empty()
             && self.webauthn.is_empty()
-            && !self.has_recovery()
+            && self.recovery().is_none()
     }
 
     /// Find an entry by id, except for the "recovery" entry which we're currently treating
@@ -750,8 +803,20 @@ impl TfaUserData {
         userid: &Userid,
         description: String,
     ) -> Result<String, Error> {
+        let cred_ids: Vec<_> = self
+            .enabled_webauthn_entries()
+            .map(|cred| cred.cred_id.clone())
+            .collect();
+
         let userid_str = userid.to_string();
-        let (challenge, state) = webauthn.generate_challenge_register(&userid_str, None)?;
+        let (challenge, state) = webauthn.generate_challenge_register_options(
+            userid_str.as_bytes().to_vec(),
+            userid_str.clone(),
+            userid_str.clone(),
+            Some(cred_ids),
+            Some(UserVerificationPolicy::Discouraged),
+        )?;
+
         let challenge_string = challenge.public_key.challenge.to_string();
         let challenge = serde_json::to_string(&challenge)?;
 
@@ -870,7 +935,8 @@ impl TfaUserData {
             return Ok(None);
         }
 
-        let (challenge, state) = webauthn.generate_challenge_authenticate(creds, None)?;
+        let (challenge, state) = webauthn
+            .generate_challenge_authenticate(creds, Some(UserVerificationPolicy::Discouraged))?;
         let challenge_string = challenge.public_key.challenge.to_string();
         let mut data = TfaUserChallengeData::open(userid)?;
         data.inner
@@ -959,7 +1025,8 @@ impl TfaUserData {
         }
 
         // we don't allow re-trying the challenge, so make the removal persistent now:
-        data.save()?;
+        data.save()
+            .map_err(|err| format_err!("failed to save challenge file: {}", err))?;
 
         match webauthn.authenticate_credential(response, challenge.state)? {
             Some((_cred, _counter)) => Ok(()),
@@ -997,8 +1064,16 @@ impl TfaUserData {
 /// Recovery entries. We use HMAC-SHA256 with a random secret as a salted hash replacement.
 #[derive(Deserialize, Serialize)]
 pub struct Recovery {
+    /// "Salt" used for the key HMAC.
     secret: String,
-    entries: Vec<String>,
+
+    /// Recovery key entries are HMACs of the original data. When used up they will become `None`
+    /// since the user is presented an enumerated list of codes, so we know the indices of used and
+    /// unused codes.
+    entries: Vec<Option<String>>,
+
+    /// Creation timestamp as a unix epoch.
+    pub created: i64,
 }
 
 impl Recovery {
@@ -1011,6 +1086,7 @@ impl Recovery {
         let mut this = Self {
             secret: AsHex(&secret).to_string(),
             entries: Vec::with_capacity(10),
+            created: proxmox::tools::time::epoch_i64(),
         };
 
         let mut original = Vec::new();
@@ -1026,7 +1102,7 @@ impl Recovery {
                 AsHex(&b[6..8]),
             );
 
-            this.entries.push(this.hash(entry.as_bytes())?);
+            this.entries.push(Some(this.hash(entry.as_bytes())?));
             original.push(entry);
         }
 
@@ -1048,31 +1124,32 @@ impl Recovery {
         Ok(AsHex(&hmac).to_string())
     }
 
-    /// Shortcut to get the count.
-    fn len(&self) -> usize {
-        self.entries.len()
+    /// Iterator over available keys.
+    fn available(&self) -> impl Iterator<Item = &str> {
+        self.entries.iter().filter_map(Option::as_deref)
     }
 
-    /// Check if this entry is empty.
-    fn is_empty(&self) -> bool {
-        self.entries.is_empty()
+    /// Count the available keys.
+    fn count_available(&self) -> usize {
+        self.available().count()
     }
 
     /// Convenience serde method to check if either the option is `None` or the content `is_empty`.
     fn option_is_empty(this: &Option<Self>) -> bool {
-        this.as_ref().map_or(true, Self::is_empty)
+        this.as_ref()
+            .map_or(true, |this| this.count_available() == 0)
     }
 
     /// Verify a key and remove it. Returns whether the key was valid. Errors on openssl errors.
     fn verify(&mut self, key: &str) -> Result<bool, Error> {
         let hash = self.hash(key.as_bytes())?;
-        Ok(match self.entries.iter().position(|entry| *entry == hash) {
-            Some(index) => {
-                self.entries.remove(index);
-                true
+        for entry in &mut self.entries {
+            if entry.as_ref() == Some(&hash) {
+                *entry = None;
+                return Ok(true);
             }
-            None => false,
-        })
+        }
+        Ok(false)
     }
 }
 
@@ -1193,45 +1270,38 @@ pub fn verify_challenge(
 }
 
 /// Used to inform the user about the recovery code status.
-#[derive(Clone, Copy, Eq, PartialEq, Deserialize, Serialize)]
-#[serde(rename_all = "kebab-case")]
-pub enum RecoveryState {
-    Unavailable,
-    Low,
-    Available,
-}
+///
+/// This contains the available key indices.
+#[derive(Clone, Default, Eq, PartialEq, Deserialize, Serialize)]
+pub struct RecoveryState(Vec<usize>);
 
 impl RecoveryState {
-    fn from_count(count: usize) -> Self {
-        match count {
-            0 => RecoveryState::Unavailable,
-            1..=3 => RecoveryState::Low,
-            _ => RecoveryState::Available,
-        }
-    }
-
-    // serde needs `&self` but this is a tiny Copy type, so we mark this as inline
-    #[inline]
     fn is_unavailable(&self) -> bool {
-        *self == RecoveryState::Unavailable
-    }
-}
-
-impl Default for RecoveryState {
-    fn default() -> Self {
-        RecoveryState::Unavailable
+        self.0.is_empty()
     }
 }
 
 impl From<&Option<Recovery>> for RecoveryState {
     fn from(r: &Option<Recovery>) -> Self {
         match r {
-            Some(r) => Self::from_count(r.len()),
-            None => RecoveryState::Unavailable,
+            Some(r) => Self::from(r),
+            None => Self::default(),
         }
     }
 }
 
+impl From<&Recovery> for RecoveryState {
+    fn from(r: &Recovery) -> Self {
+        Self(
+            r.entries
+                .iter()
+                .enumerate()
+                .filter_map(|(idx, key)| if key.is_some() { Some(idx) } else { None })
+                .collect(),
+        )
+    }
+}
+
 /// When sending a TFA challenge to the user, we include information about what kind of challenge
 /// the user may perform. If webauthn credentials are available, a webauthn challenge will be
 /// included.
@@ -1277,14 +1347,14 @@ impl std::str::FromStr for TfaResponse {
     type Err = Error;
 
     fn from_str(s: &str) -> Result<Self, Error> {
-        Ok(if s.starts_with("totp:") {
-            TfaResponse::Totp(s[5..].to_string())
-        } else if s.starts_with("u2f:") {
-            TfaResponse::U2f(serde_json::from_str(&s[4..])?)
-        } else if s.starts_with("webauthn:") {
-            TfaResponse::Webauthn(serde_json::from_str(&s[9..])?)
-        } else if s.starts_with("recovery:") {
-            TfaResponse::Recovery(s[9..].to_string())
+        Ok(if let Some(totp) = s.strip_prefix("totp:") {
+            TfaResponse::Totp(totp.to_string())
+        } else if let Some(u2f) = s.strip_prefix("u2f:") {
+            TfaResponse::U2f(serde_json::from_str(u2f)?)
+        } else if let Some(webauthn) = s.strip_prefix("webauthn:") {
+            TfaResponse::Webauthn(serde_json::from_str(webauthn)?)
+        } else if let Some(recovery) = s.strip_prefix("recovery:") {
+            TfaResponse::Recovery(recovery.to_string())
         } else {
             bail!("invalid tfa response");
         })