Skip to main content

kanidm_proto/internal/
credupdate.rs

1use serde::{Deserialize, Serialize};
2use std::{collections::BTreeMap, fmt};
3use url::Url;
4use utoipa::ToSchema;
5use uuid::Uuid;
6
7use webauthn_rs_proto::{CreationChallengeResponse, RegisterPublicKeyCredential};
8
9pub use sshkey_attest::proto::PublicKey as SshPublicKey;
10
11#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
12#[serde(rename_all = "lowercase")]
13pub enum TotpAlgo {
14    Sha1,
15    Sha256,
16    Sha512,
17}
18
19impl fmt::Display for TotpAlgo {
20    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
21        match self {
22            TotpAlgo::Sha1 => write!(f, "SHA1"),
23            TotpAlgo::Sha256 => write!(f, "SHA256"),
24            TotpAlgo::Sha512 => write!(f, "SHA512"),
25        }
26    }
27}
28
29#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
30pub struct TotpSecret {
31    pub accountname: String,
32    /// User-facing name of the system, issuer of the TOTP
33    pub issuer: String,
34    pub secret: Vec<u8>,
35    pub algo: TotpAlgo,
36    pub step: u64,
37    pub digits: u8,
38}
39
40impl TotpSecret {
41    /// <https://github.com/google/google-authenticator/wiki/Key-Uri-Format>
42    pub fn to_uri(&self) -> String {
43        let accountname = urlencoding::Encoded(&self.accountname);
44        let issuer = urlencoding::Encoded(&self.issuer);
45        let label = format!("{issuer}:{accountname}");
46        let algo = self.algo.to_string();
47        let secret = self.get_secret();
48        let period = self.step;
49        let digits = self.digits;
50
51        format!(
52            "otpauth://totp/{label}?secret={secret}&issuer={issuer}&algorithm={algo}&digits={digits}&period={period}"
53        )
54    }
55
56    pub fn get_secret(&self) -> String {
57        base32::encode(base32::Alphabet::Rfc4648 { padding: false }, &self.secret)
58    }
59}
60
61/// Structure denoting the parameters for triggering a credential update intent
62/// token to be send to the account.
63#[derive(Debug, Serialize, Deserialize, ToSchema)]
64pub struct CUIntentSend {
65    pub ttl: Option<u64>,
66    pub email: Option<String>,
67}
68
69#[derive(Debug, Serialize, Deserialize, ToSchema)]
70pub struct CUIntentToken {
71    pub token: String,
72    #[serde(with = "time::serde::timestamp")]
73    pub expiry_time: time::OffsetDateTime,
74}
75
76#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
77pub struct CUSessionToken {
78    pub token: String,
79}
80
81#[derive(Clone, Serialize, Deserialize)]
82#[serde(rename_all = "lowercase")]
83pub enum CURequest {
84    PrimaryRemove,
85    PasswordQualityCheck(String),
86    Password(String),
87    CancelMFAReg,
88    TotpGenerate,
89    TotpVerify(u32, String),
90    TotpAcceptSha1,
91    TotpRemove(String),
92    BackupCodeGenerate,
93    BackupCodeRemove,
94    PasskeyInit,
95    PasskeyFinish(String, RegisterPublicKeyCredential),
96    PasskeyRemove(Uuid),
97    AttestedPasskeyInit,
98    AttestedPasskeyFinish(String, RegisterPublicKeyCredential),
99    AttestedPasskeyRemove(Uuid),
100    UnixPasswordRemove,
101    UnixPassword(String),
102    SshPublicKey(String, SshPublicKey),
103    SshPublicKeyRemove(String),
104}
105
106impl fmt::Debug for CURequest {
107    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
108        let t = match self {
109            CURequest::PrimaryRemove => "CURequest::PrimaryRemove",
110            CURequest::PasswordQualityCheck(_) => "CURequest::PasswordQualityCheck",
111            CURequest::Password(_) => "CURequest::Password",
112            CURequest::CancelMFAReg => "CURequest::CancelMFAReg",
113            CURequest::TotpGenerate => "CURequest::TotpGenerate",
114            CURequest::TotpVerify(_, _) => "CURequest::TotpVerify",
115            CURequest::TotpAcceptSha1 => "CURequest::TotpAcceptSha1",
116            CURequest::TotpRemove(_) => "CURequest::TotpRemove",
117            CURequest::BackupCodeGenerate => "CURequest::BackupCodeGenerate",
118            CURequest::BackupCodeRemove => "CURequest::BackupCodeRemove",
119            CURequest::PasskeyInit => "CURequest::PasskeyInit",
120            CURequest::PasskeyFinish(_, _) => "CURequest::PasskeyFinish",
121            CURequest::PasskeyRemove(_) => "CURequest::PasskeyRemove",
122            CURequest::AttestedPasskeyInit => "CURequest::AttestedPasskeyInit",
123            CURequest::AttestedPasskeyFinish(_, _) => "CURequest::AttestedPasskeyFinish",
124            CURequest::AttestedPasskeyRemove(_) => "CURequest::AttestedPasskeyRemove",
125            CURequest::UnixPassword(_) => "CURequest::UnixPassword",
126            CURequest::UnixPasswordRemove => "CURequest::UnixPasswordRemove",
127            CURequest::SshPublicKey(_, _) => "CURequest::SSHKeySubmit",
128            CURequest::SshPublicKeyRemove(_) => "CURequest::SSHKeyRemove",
129        };
130        writeln!(f, "{t}")
131    }
132}
133
134#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
135pub enum CURegState {
136    // Nothing in progress.
137    None,
138    TotpCheck(TotpSecret),
139    TotpTryAgain,
140    TotpNameTryAgain(String),
141    TotpInvalidSha1,
142    BackupCodes(Vec<String>),
143    #[schema(value_type = HashMap<String, Value>)]
144    Passkey(CreationChallengeResponse),
145    #[schema(value_type = HashMap<String, Value>)]
146    AttestedPasskey(CreationChallengeResponse),
147}
148
149#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
150pub enum CUExtPortal {
151    None,
152    Hidden,
153    Some(Url),
154}
155
156#[derive(Debug, Clone, Copy, Serialize, Deserialize, ToSchema, PartialEq)]
157pub enum CUCredState {
158    Modifiable,
159    DeleteOnly,
160    AccessDeny,
161    PolicyDeny,
162    // Disabled,
163}
164
165#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
166pub enum CURegWarning {
167    MfaRequired,
168    PasskeyRequired,
169    AttestedPasskeyRequired,
170    AttestedResidentKeyRequired,
171    Unsatisfiable,
172    WebauthnAttestationUnsatisfiable,
173    WebauthnUserVerificationRequired,
174    NoValidCredentials,
175}
176
177#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
178pub struct CUStatus {
179    // Display values
180    pub spn: String,
181    pub displayname: String,
182    pub ext_cred_portal: CUExtPortal,
183    // Internal State Tracking
184    pub mfaregstate: CURegState,
185    // Display hints + The credential details.
186    pub can_commit: bool,
187    pub warnings: Vec<CURegWarning>,
188    pub dirty: bool,
189    pub primary: Option<CredentialDetail>,
190    pub primary_state: CUCredState,
191    pub passkeys: Vec<PasskeyDetail>,
192    pub passkeys_state: CUCredState,
193    pub attested_passkeys: Vec<PasskeyDetail>,
194    pub attested_passkeys_state: CUCredState,
195    pub attested_passkeys_allowed_devices: Vec<String>,
196
197    pub unixcred: Option<CredentialDetail>,
198    pub unixcred_state: CUCredState,
199
200    #[schema(value_type = BTreeMap<String, Value>)]
201    pub sshkeys: BTreeMap<String, SshPublicKey>,
202    pub sshkeys_state: CUCredState,
203}
204
205#[derive(Debug, Serialize, Deserialize, Clone, ToSchema)]
206pub struct CredentialStatus {
207    pub creds: Vec<CredentialDetail>,
208}
209
210impl fmt::Display for CredentialStatus {
211    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
212        for cred in &self.creds {
213            writeln!(f, "---")?;
214            cred.fmt(f)?;
215        }
216        writeln!(f, "---")
217    }
218}
219
220#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, ToSchema)]
221pub enum CredentialDetailType {
222    Password,
223    GeneratedPassword,
224    Passkey(Vec<String>),
225    /// totp, webauthn
226    PasswordMfa(Vec<String>, Vec<String>, usize),
227}
228
229#[derive(Debug, Serialize, Deserialize, Clone, ToSchema)]
230pub struct CredentialDetail {
231    pub uuid: Uuid,
232    pub type_: CredentialDetailType,
233}
234
235impl fmt::Display for CredentialDetail {
236    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
237        writeln!(f, "uuid: {}", self.uuid)?;
238        /*
239        writeln!(f, "claims:")?;
240        for claim in &self.claims {
241            writeln!(f, " * {}", claim)?;
242        }
243        */
244        match &self.type_ {
245            CredentialDetailType::Password => writeln!(f, "password: set"),
246            CredentialDetailType::GeneratedPassword => writeln!(f, "generated password: set"),
247            CredentialDetailType::Passkey(labels) => {
248                if labels.is_empty() {
249                    writeln!(f, "passkeys: none registered")
250                } else {
251                    writeln!(f, "passkeys:")?;
252                    for label in labels {
253                        writeln!(f, " * {label}")?;
254                    }
255                    write!(f, "")
256                }
257            }
258            CredentialDetailType::PasswordMfa(totp_labels, wan_labels, backup_code) => {
259                writeln!(f, "password: set")?;
260
261                if !totp_labels.is_empty() {
262                    writeln!(f, "totp:")?;
263                    for label in totp_labels {
264                        writeln!(f, " * {label}")?;
265                    }
266                } else {
267                    writeln!(f, "totp: disabled")?;
268                }
269
270                if *backup_code > 0 {
271                    writeln!(f, "backup_code: enabled")?;
272                } else {
273                    writeln!(f, "backup_code: disabled")?;
274                }
275
276                if !wan_labels.is_empty() {
277                    // We no longer show the deprecated security key case by default.
278                    writeln!(f, " ⚠️  warning - security keys are deprecated.")?;
279                    writeln!(f, " ⚠️  you should re-enroll these to passkeys.")?;
280                    writeln!(f, "security keys:")?;
281                    for label in wan_labels {
282                        writeln!(f, " * {label}")?;
283                    }
284                    write!(f, "")
285                } else {
286                    write!(f, "")
287                }
288            }
289        }
290    }
291}
292
293#[derive(Debug, Serialize, Deserialize, Clone, ToSchema)]
294pub struct PasskeyDetail {
295    pub uuid: Uuid,
296    pub tag: String,
297}
298
299#[derive(Debug, Serialize, Deserialize, Clone, ToSchema)]
300pub struct BackupCodesView {
301    pub backup_codes: Vec<String>,
302}
303
304#[derive(Clone, Serialize, Deserialize, Debug, ToSchema, PartialEq, Eq, PartialOrd, Ord)]
305#[serde(rename_all = "lowercase")]
306pub enum PasswordFeedback {
307    // https://docs.rs/zxcvbn/latest/zxcvbn/feedback/enum.Suggestion.html
308    UseAFewWordsAvoidCommonPhrases,
309    NoNeedForSymbolsDigitsOrUppercaseLetters,
310    AddAnotherWordOrTwo,
311    CapitalizationDoesntHelpVeryMuch,
312    AllUppercaseIsAlmostAsEasyToGuessAsAllLowercase,
313    ReversedWordsArentMuchHarderToGuess,
314    PredictableSubstitutionsDontHelpVeryMuch,
315    UseALongerKeyboardPatternWithMoreTurns,
316    AvoidRepeatedWordsAndCharacters,
317    AvoidSequences,
318    AvoidRecentYears,
319    AvoidYearsThatAreAssociatedWithYou,
320    AvoidDatesAndYearsThatAreAssociatedWithYou,
321    // https://docs.rs/zxcvbn/latest/zxcvbn/feedback/enum.Warning.html
322    StraightRowsOfKeysAreEasyToGuess,
323    ShortKeyboardPatternsAreEasyToGuess,
324    RepeatsLikeAaaAreEasyToGuess,
325    RepeatsLikeAbcAbcAreOnlySlightlyHarderToGuess,
326    ThisIsATop10Password,
327    ThisIsATop100Password,
328    ThisIsACommonPassword,
329    ThisIsSimilarToACommonlyUsedPassword,
330    SequencesLikeAbcAreEasyToGuess,
331    RecentYearsAreEasyToGuess,
332    AWordByItselfIsEasyToGuess,
333    DatesAreOftenEasyToGuess,
334    NamesAndSurnamesByThemselvesAreEasyToGuess,
335    CommonNamesAndSurnamesAreEasyToGuess,
336    // Custom
337    TooShort(u32),
338    TooLong(u32),
339    BadListed,
340    DontReusePasswords,
341}
342
343/// Human-readable PasswordFeedback result.
344impl fmt::Display for PasswordFeedback {
345    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
346        match self {
347            PasswordFeedback::AddAnotherWordOrTwo => write!(f, "Add another word or two."),
348            PasswordFeedback::AllUppercaseIsAlmostAsEasyToGuessAsAllLowercase => write!(
349                f,
350                "All uppercase is almost as easy to guess as all lowercase."
351            ),
352            PasswordFeedback::AvoidDatesAndYearsThatAreAssociatedWithYou => write!(
353                f,
354                "Avoid dates and years that are associated with you or your account."
355            ),
356            PasswordFeedback::AvoidRecentYears => write!(f, "Avoid recent years."),
357            PasswordFeedback::AvoidRepeatedWordsAndCharacters => {
358                write!(f, "Avoid repeated words and characters.")
359            }
360            PasswordFeedback::AvoidSequences => write!(f, "Avoid sequences of characters."),
361            PasswordFeedback::AvoidYearsThatAreAssociatedWithYou => {
362                write!(f, "Avoid years that are associated with you.")
363            }
364            PasswordFeedback::AWordByItselfIsEasyToGuess => {
365                write!(f, "A word by itself is easy to guess.")
366            }
367            PasswordFeedback::BadListed => write!(
368                f,
369                "This password has been compromised or otherwise blocked and can not be used."
370            ),
371            PasswordFeedback::CapitalizationDoesntHelpVeryMuch => {
372                write!(f, "Capitalization doesn't help very much.")
373            }
374            PasswordFeedback::CommonNamesAndSurnamesAreEasyToGuess => {
375                write!(f, "Common names and surnames are easy to guess.")
376            }
377            PasswordFeedback::DatesAreOftenEasyToGuess => {
378                write!(f, "Dates are often easy to guess.")
379            }
380            PasswordFeedback::DontReusePasswords => {
381                write!(
382                    f,
383                    "Don't reuse passwords that already exist on your account"
384                )
385            }
386            PasswordFeedback::NamesAndSurnamesByThemselvesAreEasyToGuess => {
387                write!(f, "Names and surnames by themselves are easy to guess.")
388            }
389            PasswordFeedback::NoNeedForSymbolsDigitsOrUppercaseLetters => {
390                write!(f, "No need for symbols, digits or upper-case letters.")
391            }
392            PasswordFeedback::PredictableSubstitutionsDontHelpVeryMuch => {
393                write!(f, "Predictable substitutions don't help very much.")
394            }
395            PasswordFeedback::RecentYearsAreEasyToGuess => {
396                write!(f, "Recent years are easy to guess.")
397            }
398            PasswordFeedback::RepeatsLikeAaaAreEasyToGuess => {
399                write!(f, "Repeats like 'aaa' are easy to guess.")
400            }
401            PasswordFeedback::RepeatsLikeAbcAbcAreOnlySlightlyHarderToGuess => write!(
402                f,
403                "Repeats like abcabcabc are only slightly harder to guess."
404            ),
405            PasswordFeedback::ReversedWordsArentMuchHarderToGuess => {
406                write!(f, "Reversed words aren't much harder to guess.")
407            }
408            PasswordFeedback::SequencesLikeAbcAreEasyToGuess => {
409                write!(f, "Sequences like 'abc' are easy to guess.")
410            }
411            PasswordFeedback::ShortKeyboardPatternsAreEasyToGuess => {
412                write!(f, "Short keyboard patterns are easy to guess.")
413            }
414            PasswordFeedback::StraightRowsOfKeysAreEasyToGuess => {
415                write!(f, "Straight rows of keys are easy to guess.")
416            }
417            PasswordFeedback::ThisIsACommonPassword => write!(f, "This is a common password."),
418            PasswordFeedback::ThisIsATop100Password => write!(f, "This is a top 100 password."),
419            PasswordFeedback::ThisIsATop10Password => write!(f, "This is a top 10 password."),
420            PasswordFeedback::ThisIsSimilarToACommonlyUsedPassword => {
421                write!(f, "This is similar to a commonly used password.")
422            }
423            PasswordFeedback::TooShort(minlength) => write!(
424                f,
425                "Password was too short, needs to be at least {minlength} characters long."
426            ),
427            PasswordFeedback::TooLong(maxlength) => write!(
428                f,
429                "Password was too long, must not be greater than {maxlength} characters long."
430            ),
431            PasswordFeedback::UseAFewWordsAvoidCommonPhrases => {
432                write!(f, "Use a few words and avoid common phrases.")
433            }
434            PasswordFeedback::UseALongerKeyboardPatternWithMoreTurns => {
435                write!(
436                    f,
437                    "The password included keyboard patterns across too much of a single row."
438                )
439            }
440        }
441    }
442}
443
444#[cfg(test)]
445mod tests {
446    use super::{TotpAlgo, TotpSecret};
447
448    #[test]
449    fn totp_to_string() {
450        let totp = TotpSecret {
451            accountname: "william".to_string(),
452            issuer: "blackhats".to_string(),
453            secret: vec![0xaa, 0xbb, 0xcc, 0xdd],
454            step: 30,
455            algo: TotpAlgo::Sha256,
456            digits: 6,
457        };
458        let s = totp.to_uri();
459        assert_eq!(s,"otpauth://totp/blackhats:william?secret=VK54ZXI&issuer=blackhats&algorithm=SHA256&digits=6&period=30");
460
461        // check that invalid issuer/accounts are cleaned up.
462        let totp = TotpSecret {
463            accountname: "william:%3A".to_string(),
464            issuer: "blackhats australia".to_string(),
465            secret: vec![0xaa, 0xbb, 0xcc, 0xdd],
466            step: 30,
467            algo: TotpAlgo::Sha256,
468            digits: 6,
469        };
470        let s = totp.to_uri();
471        println!("{s}");
472        assert_eq!(s,"otpauth://totp/blackhats%20australia:william%3A%253A?secret=VK54ZXI&issuer=blackhats%20australia&algorithm=SHA256&digits=6&period=30");
473    }
474}