1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::fmt;
use url::Url;
use utoipa::ToSchema;
use uuid::Uuid;

use webauthn_rs_proto::CreationChallengeResponse;
use webauthn_rs_proto::RegisterPublicKeyCredential;

pub use sshkey_attest::proto::PublicKey as SshPublicKey;

#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
#[serde(rename_all = "lowercase")]
pub enum TotpAlgo {
    Sha1,
    Sha256,
    Sha512,
}

impl fmt::Display for TotpAlgo {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            TotpAlgo::Sha1 => write!(f, "SHA1"),
            TotpAlgo::Sha256 => write!(f, "SHA256"),
            TotpAlgo::Sha512 => write!(f, "SHA512"),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct TotpSecret {
    pub accountname: String,
    /// User-facing name of the system, issuer of the TOTP
    pub issuer: String,
    pub secret: Vec<u8>,
    pub algo: TotpAlgo,
    pub step: u64,
    pub digits: u8,
}

impl TotpSecret {
    /// <https://github.com/google/google-authenticator/wiki/Key-Uri-Format>
    pub fn to_uri(&self) -> String {
        let accountname = urlencoding::Encoded(&self.accountname);
        let issuer = urlencoding::Encoded(&self.issuer);
        let label = format!("{}:{}", issuer, accountname);
        let algo = self.algo.to_string();
        let secret = self.get_secret();
        let period = self.step;
        let digits = self.digits;

        format!(
            "otpauth://totp/{}?secret={}&issuer={}&algorithm={}&digits={}&period={}",
            label, secret, issuer, algo, digits, period
        )
    }

    pub fn get_secret(&self) -> String {
        base32::encode(base32::Alphabet::Rfc4648 { padding: false }, &self.secret)
    }
}

#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct CUIntentToken {
    pub token: String,
    #[serde(with = "time::serde::timestamp")]
    pub expiry_time: time::OffsetDateTime,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
pub struct CUSessionToken {
    pub token: String,
}

#[derive(Clone, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CURequest {
    PrimaryRemove,
    Password(String),
    CancelMFAReg,
    TotpGenerate,
    TotpVerify(u32, String),
    TotpAcceptSha1,
    TotpRemove(String),
    BackupCodeGenerate,
    BackupCodeRemove,
    PasskeyInit,
    PasskeyFinish(String, RegisterPublicKeyCredential),
    PasskeyRemove(Uuid),
    AttestedPasskeyInit,
    AttestedPasskeyFinish(String, RegisterPublicKeyCredential),
    AttestedPasskeyRemove(Uuid),
    UnixPasswordRemove,
    UnixPassword(String),
    SshPublicKey(String, SshPublicKey),
    SshPublicKeyRemove(String),
}

impl fmt::Debug for CURequest {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let t = match self {
            CURequest::PrimaryRemove => "CURequest::PrimaryRemove",
            CURequest::Password(_) => "CURequest::Password",
            CURequest::CancelMFAReg => "CURequest::CancelMFAReg",
            CURequest::TotpGenerate => "CURequest::TotpGenerate",
            CURequest::TotpVerify(_, _) => "CURequest::TotpVerify",
            CURequest::TotpAcceptSha1 => "CURequest::TotpAcceptSha1",
            CURequest::TotpRemove(_) => "CURequest::TotpRemove",
            CURequest::BackupCodeGenerate => "CURequest::BackupCodeGenerate",
            CURequest::BackupCodeRemove => "CURequest::BackupCodeRemove",
            CURequest::PasskeyInit => "CURequest::PasskeyInit",
            CURequest::PasskeyFinish(_, _) => "CURequest::PasskeyFinish",
            CURequest::PasskeyRemove(_) => "CURequest::PasskeyRemove",
            CURequest::AttestedPasskeyInit => "CURequest::AttestedPasskeyInit",
            CURequest::AttestedPasskeyFinish(_, _) => "CURequest::AttestedPasskeyFinish",
            CURequest::AttestedPasskeyRemove(_) => "CURequest::AttestedPasskeyRemove",
            CURequest::UnixPassword(_) => "CURequest::UnixPassword",
            CURequest::UnixPasswordRemove => "CURequest::UnixPasswordRemove",
            CURequest::SshPublicKey(_, _) => "CURequest::SSHKeySubmit",
            CURequest::SshPublicKeyRemove(_) => "CURequest::SSHKeyRemove",
        };
        writeln!(f, "{}", t)
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub enum CURegState {
    // Nothing in progress.
    None,
    TotpCheck(TotpSecret),
    TotpTryAgain,
    TotpInvalidSha1,
    BackupCodes(Vec<String>),
    Passkey(CreationChallengeResponse),
    AttestedPasskey(CreationChallengeResponse),
}

#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub enum CUExtPortal {
    None,
    Hidden,
    Some(Url),
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, ToSchema, PartialEq)]
pub enum CUCredState {
    Modifiable,
    DeleteOnly,
    AccessDeny,
    PolicyDeny,
    // Disabled,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
pub enum CURegWarning {
    MfaRequired,
    PasskeyRequired,
    AttestedPasskeyRequired,
    AttestedResidentKeyRequired,
    Unsatisfiable,
    WebauthnAttestationUnsatisfiable,
}

#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct CUStatus {
    // Display values
    pub spn: String,
    pub displayname: String,
    pub ext_cred_portal: CUExtPortal,
    // Internal State Tracking
    pub mfaregstate: CURegState,
    // Display hints + The credential details.
    pub can_commit: bool,
    pub warnings: Vec<CURegWarning>,
    pub primary: Option<CredentialDetail>,
    pub primary_state: CUCredState,
    pub passkeys: Vec<PasskeyDetail>,
    pub passkeys_state: CUCredState,
    pub attested_passkeys: Vec<PasskeyDetail>,
    pub attested_passkeys_state: CUCredState,
    pub attested_passkeys_allowed_devices: Vec<String>,

    pub unixcred: Option<CredentialDetail>,
    pub unixcred_state: CUCredState,

    pub sshkeys: BTreeMap<String, SshPublicKey>,
    pub sshkeys_state: CUCredState,
}

#[derive(Debug, Serialize, Deserialize, Clone, ToSchema)]
pub struct CredentialStatus {
    pub creds: Vec<CredentialDetail>,
}

impl fmt::Display for CredentialStatus {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for cred in &self.creds {
            writeln!(f, "---")?;
            cred.fmt(f)?;
        }
        writeln!(f, "---")
    }
}

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, ToSchema)]
pub enum CredentialDetailType {
    Password,
    GeneratedPassword,
    Passkey(Vec<String>),
    /// totp, webauthn
    PasswordMfa(Vec<String>, Vec<String>, usize),
}

#[derive(Debug, Serialize, Deserialize, Clone, ToSchema)]
pub struct CredentialDetail {
    pub uuid: Uuid,
    pub type_: CredentialDetailType,
}

impl fmt::Display for CredentialDetail {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        writeln!(f, "uuid: {}", self.uuid)?;
        /*
        writeln!(f, "claims:")?;
        for claim in &self.claims {
            writeln!(f, " * {}", claim)?;
        }
        */
        match &self.type_ {
            CredentialDetailType::Password => writeln!(f, "password: set"),
            CredentialDetailType::GeneratedPassword => writeln!(f, "generated password: set"),
            CredentialDetailType::Passkey(labels) => {
                if labels.is_empty() {
                    writeln!(f, "passkeys: none registered")
                } else {
                    writeln!(f, "passkeys:")?;
                    for label in labels {
                        writeln!(f, " * {}", label)?;
                    }
                    write!(f, "")
                }
            }
            CredentialDetailType::PasswordMfa(totp_labels, wan_labels, backup_code) => {
                writeln!(f, "password: set")?;

                if !totp_labels.is_empty() {
                    writeln!(f, "totp:")?;
                    for label in totp_labels {
                        writeln!(f, " * {}", label)?;
                    }
                } else {
                    writeln!(f, "totp: disabled")?;
                }

                if *backup_code > 0 {
                    writeln!(f, "backup_code: enabled")?;
                } else {
                    writeln!(f, "backup_code: disabled")?;
                }

                if !wan_labels.is_empty() {
                    // We no longer show the deprecated security key case by default.
                    writeln!(f, " ⚠️  warning - security keys are deprecated.")?;
                    writeln!(f, " ⚠️  you should re-enroll these to passkeys.")?;
                    writeln!(f, "security keys:")?;
                    for label in wan_labels {
                        writeln!(f, " * {}", label)?;
                    }
                    write!(f, "")
                } else {
                    write!(f, "")
                }
            }
        }
    }
}

#[derive(Debug, Serialize, Deserialize, Clone, ToSchema)]
pub struct PasskeyDetail {
    pub uuid: Uuid,
    pub tag: String,
}

#[derive(Debug, Serialize, Deserialize, Clone, ToSchema)]
pub struct BackupCodesView {
    pub backup_codes: Vec<String>,
}

#[derive(Serialize, Deserialize, Debug, ToSchema, PartialEq, Eq, PartialOrd, Ord)]
#[serde(rename_all = "lowercase")]
pub enum PasswordFeedback {
    // https://docs.rs/zxcvbn/latest/zxcvbn/feedback/enum.Suggestion.html
    UseAFewWordsAvoidCommonPhrases,
    NoNeedForSymbolsDigitsOrUppercaseLetters,
    AddAnotherWordOrTwo,
    CapitalizationDoesntHelpVeryMuch,
    AllUppercaseIsAlmostAsEasyToGuessAsAllLowercase,
    ReversedWordsArentMuchHarderToGuess,
    PredictableSubstitutionsDontHelpVeryMuch,
    UseALongerKeyboardPatternWithMoreTurns,
    AvoidRepeatedWordsAndCharacters,
    AvoidSequences,
    AvoidRecentYears,
    AvoidYearsThatAreAssociatedWithYou,
    AvoidDatesAndYearsThatAreAssociatedWithYou,
    // https://docs.rs/zxcvbn/latest/zxcvbn/feedback/enum.Warning.html
    StraightRowsOfKeysAreEasyToGuess,
    ShortKeyboardPatternsAreEasyToGuess,
    RepeatsLikeAaaAreEasyToGuess,
    RepeatsLikeAbcAbcAreOnlySlightlyHarderToGuess,
    ThisIsATop10Password,
    ThisIsATop100Password,
    ThisIsACommonPassword,
    ThisIsSimilarToACommonlyUsedPassword,
    SequencesLikeAbcAreEasyToGuess,
    RecentYearsAreEasyToGuess,
    AWordByItselfIsEasyToGuess,
    DatesAreOftenEasyToGuess,
    NamesAndSurnamesByThemselvesAreEasyToGuess,
    CommonNamesAndSurnamesAreEasyToGuess,
    // Custom
    TooShort(u32),
    BadListed,
    DontReusePasswords,
}

/// Human-readable PasswordFeedback result.
impl fmt::Display for PasswordFeedback {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            PasswordFeedback::AddAnotherWordOrTwo => write!(f, "Add another word or two."),
            PasswordFeedback::AllUppercaseIsAlmostAsEasyToGuessAsAllLowercase => write!(
                f,
                "All uppercase is almost as easy to guess as all lowercase."
            ),
            PasswordFeedback::AvoidDatesAndYearsThatAreAssociatedWithYou => write!(
                f,
                "Avoid dates and years that are associated with you or your account."
            ),
            PasswordFeedback::AvoidRecentYears => write!(f, "Avoid recent years."),
            PasswordFeedback::AvoidRepeatedWordsAndCharacters => {
                write!(f, "Avoid repeated words and characters.")
            }
            PasswordFeedback::AvoidSequences => write!(f, "Avoid sequences of characters."),
            PasswordFeedback::AvoidYearsThatAreAssociatedWithYou => {
                write!(f, "Avoid years that are associated with you.")
            }
            PasswordFeedback::AWordByItselfIsEasyToGuess => {
                write!(f, "A word by itself is easy to guess.")
            }
            PasswordFeedback::BadListed => write!(
                f,
                "This password has been compromised or otherwise blocked and can not be used."
            ),
            PasswordFeedback::CapitalizationDoesntHelpVeryMuch => {
                write!(f, "Capitalization doesn't help very much.")
            }
            PasswordFeedback::CommonNamesAndSurnamesAreEasyToGuess => {
                write!(f, "Common names and surnames are easy to guess.")
            }
            PasswordFeedback::DatesAreOftenEasyToGuess => {
                write!(f, "Dates are often easy to guess.")
            }
            PasswordFeedback::DontReusePasswords => {
                write!(
                    f,
                    "Don't reuse passwords that already exist on your account"
                )
            }
            PasswordFeedback::NamesAndSurnamesByThemselvesAreEasyToGuess => {
                write!(f, "Names and surnames by themselves are easy to guess.")
            }
            PasswordFeedback::NoNeedForSymbolsDigitsOrUppercaseLetters => {
                write!(f, "No need for symbols, digits or upper-case letters.")
            }
            PasswordFeedback::PredictableSubstitutionsDontHelpVeryMuch => {
                write!(f, "Predictable substitutions don't help very much.")
            }
            PasswordFeedback::RecentYearsAreEasyToGuess => {
                write!(f, "Recent years are easy to guess.")
            }
            PasswordFeedback::RepeatsLikeAaaAreEasyToGuess => {
                write!(f, "Repeats like 'aaa' are easy to guess.")
            }
            PasswordFeedback::RepeatsLikeAbcAbcAreOnlySlightlyHarderToGuess => write!(
                f,
                "Repeats like abcabcabc are only slightly harder to guess."
            ),
            PasswordFeedback::ReversedWordsArentMuchHarderToGuess => {
                write!(f, "Reversed words aren't much harder to guess.")
            }
            PasswordFeedback::SequencesLikeAbcAreEasyToGuess => {
                write!(f, "Sequences like 'abc' are easy to guess.")
            }
            PasswordFeedback::ShortKeyboardPatternsAreEasyToGuess => {
                write!(f, "Short keyboard patterns are easy to guess.")
            }
            PasswordFeedback::StraightRowsOfKeysAreEasyToGuess => {
                write!(f, "Straight rows of keys are easy to guess.")
            }
            PasswordFeedback::ThisIsACommonPassword => write!(f, "This is a common password."),
            PasswordFeedback::ThisIsATop100Password => write!(f, "This is a top 100 password."),
            PasswordFeedback::ThisIsATop10Password => write!(f, "This is a top 10 password."),
            PasswordFeedback::ThisIsSimilarToACommonlyUsedPassword => {
                write!(f, "This is similar to a commonly used password.")
            }
            PasswordFeedback::TooShort(minlength) => write!(
                f,
                "Password was too short, needs to be at least {} characters long.",
                minlength
            ),
            PasswordFeedback::UseAFewWordsAvoidCommonPhrases => {
                write!(f, "Use a few words and avoid common phrases.")
            }
            PasswordFeedback::UseALongerKeyboardPatternWithMoreTurns => {
                write!(
                    f,
                    "The password included keyboard patterns across too much of a single row."
                )
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{TotpAlgo, TotpSecret};

    #[test]
    fn totp_to_string() {
        let totp = TotpSecret {
            accountname: "william".to_string(),
            issuer: "blackhats".to_string(),
            secret: vec![0xaa, 0xbb, 0xcc, 0xdd],
            step: 30,
            algo: TotpAlgo::Sha256,
            digits: 6,
        };
        let s = totp.to_uri();
        assert_eq!(s,"otpauth://totp/blackhats:william?secret=VK54ZXI&issuer=blackhats&algorithm=SHA256&digits=6&period=30");

        // check that invalid issuer/accounts are cleaned up.
        let totp = TotpSecret {
            accountname: "william:%3A".to_string(),
            issuer: "blackhats australia".to_string(),
            secret: vec![0xaa, 0xbb, 0xcc, 0xdd],
            step: 30,
            algo: TotpAlgo::Sha256,
            digits: 6,
        };
        let s = totp.to_uri();
        println!("{}", s);
        assert_eq!(s,"otpauth://totp/blackhats%20australia:william%3A%253A?secret=VK54ZXI&issuer=blackhats%20australia&algorithm=SHA256&digits=6&period=30");
    }
}