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
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
use crate::password_prompt;
use crate::{
    AccountCredential, AccountOpt, AccountPerson, AccountPosix, AccountRadius, AccountSsh,
    AccountValidity,
};
use qrcode::render::unicode;
use qrcode::QrCode;
use std::io;
use time::OffsetDateTime;

use webauthn_authenticator_rs::{u2fhid::U2FHid, WebauthnAuthenticator};

use kanidm_client::ClientError;
use kanidm_client::ClientError::Http as ClientErrorHttp;
use kanidm_proto::v1::OperationError::PasswordQuality;

impl AccountOpt {
    pub fn debug(&self) -> bool {
        match self {
            AccountOpt::Credential(acopt) => match acopt {
                AccountCredential::SetPassword(acs) => acs.copt.debug,
                AccountCredential::GeneratePassword(acs) => acs.copt.debug,
                AccountCredential::RegisterWebauthn(acs) => acs.copt.debug,
                AccountCredential::RemoveWebauthn(acs) => acs.copt.debug,
                AccountCredential::RegisterTotp(acs) => acs.copt.debug,
                AccountCredential::RemoveTotp(acs) => acs.copt.debug,
                AccountCredential::BackupCodeGenerate(acs) => acs.copt.debug,
                AccountCredential::BackupCodeRemove(acs) => acs.copt.debug,
                AccountCredential::Status(acs) => acs.copt.debug,
            },
            AccountOpt::Radius(acopt) => match acopt {
                AccountRadius::Show(aro) => aro.copt.debug,
                AccountRadius::Generate(aro) => aro.copt.debug,
                AccountRadius::Delete(aro) => aro.copt.debug,
            },
            AccountOpt::Posix(apopt) => match apopt {
                AccountPosix::Show(apo) => apo.copt.debug,
                AccountPosix::Set(apo) => apo.copt.debug,
                AccountPosix::SetPassword(apo) => apo.copt.debug,
            },
            AccountOpt::Person(apopt) => match apopt {
                AccountPerson::Extend(apo) => apo.copt.debug,
                AccountPerson::Set(apo) => apo.copt.debug,
            },
            AccountOpt::Ssh(asopt) => match asopt {
                AccountSsh::List(ano) => ano.copt.debug,
                AccountSsh::Add(ano) => ano.copt.debug,
                AccountSsh::Delete(ano) => ano.copt.debug,
            },
            AccountOpt::List(copt) => copt.debug,
            AccountOpt::Get(aopt) => aopt.copt.debug,
            AccountOpt::Delete(aopt) => aopt.copt.debug,
            AccountOpt::Create(aopt) => aopt.copt.debug,
            AccountOpt::Validity(avopt) => match avopt {
                AccountValidity::Show(ano) => ano.copt.debug,
                AccountValidity::ExpireAt(ano) => ano.copt.debug,
                AccountValidity::BeginFrom(ano) => ano.copt.debug,
            },
        }
    }

    pub fn exec(&self) {
        match self {
            // id/cred/primary/set
            AccountOpt::Credential(acopt) => match acopt {
                AccountCredential::SetPassword(acsopt) => {
                    let client = acsopt.copt.to_client();
                    let password = match password_prompt(
                        format!("Enter new password for {}: ", acsopt.aopts.account_id).as_str(),
                    ) {
                        Some(v) => v,
                        None => {
                            println!("Passwords do not match");
                            return;
                        }
                    };

                    if let Err(e) = client.idm_account_primary_credential_set_password(
                        acsopt.aopts.account_id.as_str(),
                        password.as_str(),
                    ) {
                        match e {
                            // TODO: once the password length is configurable at a system level (#498), pull from the configuration.
                            ClientErrorHttp(_, Some(PasswordQuality(feedback)), _) => {
                                error!("{:?}", feedback)
                            }
                            _ => error!("Error setting password -> {:?}", e),
                        }
                    }
                }
                AccountCredential::GeneratePassword(acsopt) => {
                    let client = acsopt.copt.to_client();

                    match client.idm_account_primary_credential_set_generated(
                        acsopt.aopts.account_id.as_str(),
                    ) {
                        Ok(npw) => {
                            println!(
                                "Generated password for {}: {}",
                                acsopt.aopts.account_id, npw
                            );
                        }
                        Err(e) => {
                            error!("Error -> {:?}", e);
                        }
                    }
                }
                AccountCredential::RegisterWebauthn(acsopt) => {
                    let client = acsopt.copt.to_client();

                    let (session, chal) = match client
                        .idm_account_primary_credential_register_webauthn(
                            acsopt.aopts.account_id.as_str(),
                            acsopt.tag.as_str(),
                        ) {
                        Ok(v) => v,
                        Err(e) => {
                            error!("Error Starting Registration -> {:?}", e);
                            return;
                        }
                    };

                    let mut wa = WebauthnAuthenticator::new(U2FHid::new());

                    eprintln!("Your authenticator will now flash for you to interact with.");

                    let rego = match wa.do_registration(client.get_origin(), chal) {
                        Ok(rego) => rego,
                        Err(e) => {
                            error!("Error Signing -> {:?}", e);
                            return;
                        }
                    };

                    match client.idm_account_primary_credential_complete_webuthn_registration(
                        acsopt.aopts.account_id.as_str(),
                        rego,
                        session,
                    ) {
                        Ok(()) => {
                            println!("Webauthn token registration success.");
                        }
                        Err(e) => {
                            error!("Error Completing -> {:?}", e);
                        }
                    }
                }
                AccountCredential::RemoveWebauthn(acsopt) => {
                    let client = acsopt.copt.to_client();
                    match client.idm_account_primary_credential_remove_webauthn(
                        acsopt.aopts.account_id.as_str(),
                        acsopt.tag.as_str(),
                    ) {
                        Ok(_) => {
                            println!("Webauthn removal success.");
                        }
                        Err(e) => {
                            error!("Error Removing Webauthn from account -> {:?}", e);
                        }
                    }
                }
                AccountCredential::RegisterTotp(acsopt) => {
                    let client = acsopt.copt.to_client();
                    let (session, tok) = match client.idm_account_primary_credential_generate_totp(
                        acsopt.aopts.account_id.as_str(),
                    ) {
                        Ok(v) => v,
                        Err(e) => {
                            error!("Error Starting Registration -> {:?}", e);
                            return;
                        }
                    };

                    // display the token.
                    eprintln!("Scan the following QR code with your OTP app.");

                    let code = match QrCode::new(tok.to_uri().as_str()) {
                        Ok(c) => c,
                        Err(e) => {
                            error!("Failed to generate QR code -> {:?}", e);
                            return;
                        }
                    };
                    let image = code
                        .render::<unicode::Dense1x2>()
                        .dark_color(unicode::Dense1x2::Light)
                        .light_color(unicode::Dense1x2::Dark)
                        .build();
                    eprintln!("{}", image);

                    eprintln!("Alternatively, you can manually enter the following OTP details:");
                    println!("Account Name: {}", tok.accountname);
                    println!("Issuer: {}", tok.issuer);
                    println!("Algorithm: {}", tok.algo);
                    println!("Period/Step: {}", tok.step);
                    println!("Secret: {}", tok.get_secret());

                    // prompt for the totp.
                    eprintln!("--------------------------------------------------------------");
                    eprintln!("Enter a TOTP from your authenticator to complete registration:");

                    let mut attempts = 3;
                    while attempts > 0 {
                        eprint!("TOTP: ");
                        let mut totp_input = String::new();
                        let input_result = io::stdin().read_line(&mut totp_input);
                        // Finish the line?
                        eprintln!();
                        if let Err(e) = input_result {
                            error!("Failed to read from stdin -> {:?}", e);
                            break;
                        };

                        // Convert to a u32.
                        let totp = match totp_input.trim().parse::<u32>() {
                            Ok(v) => v,
                            Err(e) => {
                                error!("Invalid TOTP -> {:?}", e);
                                // Try again.
                                continue;
                            }
                        };

                        match client.idm_account_primary_credential_verify_totp(
                            acsopt.aopts.account_id.as_str(),
                            totp,
                            session,
                        ) {
                            Ok(_) => {
                                println!("TOTP registration success.");
                                break;
                            }
                            Err(ClientError::TotpInvalidSha1(session)) => {
                                eprintln!("⚠️  WARNING - It appears your authenticator app may be broken ⚠️  ");
                                eprintln!(" The TOTP authenticator you are using is forcing the use of SHA1\n");
                                eprintln!(" -- If you accept this risk, and wish to proceed, type 'I am sure' ");
                                eprintln!(" -- Otherwise press ENTER to cancel this operation\n");
                                eprint!("Are you sure: ");

                                let mut confirm_input = String::new();
                                if let Err(e) = io::stdin().read_line(&mut confirm_input) {
                                    error!("Failed to read from stdin -> {:?}", e);
                                };

                                if confirm_input.to_lowercase().trim() == "i am sure" {
                                    match client.idm_account_primary_credential_accept_sha1_totp(
                                        acsopt.aopts.account_id.as_str(),
                                        session,
                                    ) {
                                        Ok(_) => {
                                            println!("TOTP registration success.");
                                        }
                                        Err(e) => {
                                            error!("Error Completing -> {:?}", e);
                                        }
                                    };
                                } else {
                                    eprintln!("Cancelling TOTP registration");
                                }
                                break;
                            }
                            Err(ClientError::TotpVerifyFailed(_, _)) => {
                                eprintln!("Incorrect TOTP code - try again");
                                attempts -= 1;
                                continue;
                            }
                            Err(e) => {
                                error!("Error Completing -> {:?}", e);
                                break;
                            }
                        }
                    } // end loop
                }
                AccountCredential::RemoveTotp(acsopt) => {
                    let client = acsopt.copt.to_client();
                    match client.idm_account_primary_credential_remove_totp(
                        acsopt.aopts.account_id.as_str(),
                    ) {
                        Ok(_) => {
                            println!("TOTP removal success.");
                        }
                        Err(e) => {
                            error!("Error Removing TOTP from account -> {:?}", e);
                        }
                    }
                }
                AccountCredential::BackupCodeGenerate(acsopt) => {
                    let client = acsopt.copt.to_client();
                    match client.idm_account_primary_credential_generate_backup_code(
                        acsopt.aopts.account_id.as_str(),
                    ) {
                        Ok(s) => {
                            println!("Please store these Backup codes in a safe place");
                            println!("---");
                            println!("{}", s.join("\n"));
                            println!("---");
                        }
                        Err(e) => {
                            error!("Error generating Backup Codes for account -> {:?}", e);
                        }
                    }
                }
                AccountCredential::BackupCodeRemove(acsopt) => {
                    let client = acsopt.copt.to_client();
                    match client.idm_account_primary_credential_remove_backup_code(
                        acsopt.aopts.account_id.as_str(),
                    ) {
                        Ok(_) => {
                            println!("BackupCodeRemove success.");
                        }
                        Err(e) => {
                            error!("Error BackupCodeRemove for account -> {:?}", e);
                        }
                    }
                }
                AccountCredential::Status(acsopt) => {
                    let client = acsopt.copt.to_client();
                    match client.idm_account_get_credential_status(acsopt.aopts.account_id.as_str())
                    {
                        Ok(status) => {
                            print!("{}", status);
                        }
                        Err(e) => {
                            error!("Error displaying credential status -> {:?}", e);
                        }
                    }
                }
            }, // end AccountOpt::Credential
            AccountOpt::Radius(aropt) => match aropt {
                AccountRadius::Show(aopt) => {
                    let client = aopt.copt.to_client();

                    let rcred =
                        client.idm_account_radius_credential_get(aopt.aopts.account_id.as_str());

                    match rcred {
                        Ok(Some(s)) => println!("Radius secret: {}", s),
                        Ok(None) => println!("NO Radius secret"),
                        Err(e) => {
                            error!("Error -> {:?}", e);
                        }
                    }
                }
                AccountRadius::Generate(aopt) => {
                    let client = aopt.copt.to_client();
                    if let Err(e) = client
                        .idm_account_radius_credential_regenerate(aopt.aopts.account_id.as_str())
                    {
                        error!("Error -> {:?}", e);
                    }
                }
                AccountRadius::Delete(aopt) => {
                    let client = aopt.copt.to_client();
                    if let Err(e) =
                        client.idm_account_radius_credential_delete(aopt.aopts.account_id.as_str())
                    {
                        error!("Error -> {:?}", e);
                    }
                }
            }, // end AccountOpt::Radius
            AccountOpt::Posix(apopt) => match apopt {
                AccountPosix::Show(aopt) => {
                    let client = aopt.copt.to_client();
                    match client.idm_account_unix_token_get(aopt.aopts.account_id.as_str()) {
                        Ok(token) => println!("{}", token),
                        Err(e) => {
                            error!("Error -> {:?}", e);
                        }
                    }
                }
                AccountPosix::Set(aopt) => {
                    let client = aopt.copt.to_client();
                    if let Err(e) = client.idm_account_unix_extend(
                        aopt.aopts.account_id.as_str(),
                        aopt.gidnumber,
                        aopt.shell.as_deref(),
                    ) {
                        error!("Error -> {:?}", e);
                    }
                }
                AccountPosix::SetPassword(aopt) => {
                    let client = aopt.copt.to_client();
                    let password = match password_prompt("Enter new posix (sudo) password: ") {
                        Some(v) => v,
                        None => {
                            println!("Passwords do not match");
                            return;
                        }
                    };

                    if let Err(e) = client.idm_account_unix_cred_put(
                        aopt.aopts.account_id.as_str(),
                        password.as_str(),
                    ) {
                        error!("Error -> {:?}", e);
                    }
                }
            }, // end AccountOpt::Posix
            AccountOpt::Person(apopt) => match apopt {
                AccountPerson::Extend(aopt) => {
                    let client = aopt.copt.to_client();
                    if let Err(e) = client.idm_account_person_extend(
                        aopt.aopts.account_id.as_str(),
                        aopt.mail.as_deref(),
                        aopt.legalname.as_deref(),
                    ) {
                        error!("Error -> {:?}", e);
                    }
                }
                AccountPerson::Set(aopt) => {
                    let client = aopt.copt.to_client();
                    if let Err(e) = client.idm_account_person_set(
                        aopt.aopts.account_id.as_str(),
                        aopt.mail.as_deref(),
                        aopt.legalname.as_deref(),
                    ) {
                        error!("Error -> {:?}", e);
                    }
                }
            }, // end AccountOpt::Person
            AccountOpt::Ssh(asopt) => match asopt {
                AccountSsh::List(aopt) => {
                    let client = aopt.copt.to_client();

                    match client.idm_account_get_ssh_pubkeys(aopt.aopts.account_id.as_str()) {
                        Ok(pkeys) => pkeys.iter().for_each(|pkey| println!("{}", pkey)),
                        Err(e) => {
                            error!("Error -> {:?}", e);
                        }
                    }
                }
                AccountSsh::Add(aopt) => {
                    let client = aopt.copt.to_client();
                    if let Err(e) = client.idm_account_post_ssh_pubkey(
                        aopt.aopts.account_id.as_str(),
                        aopt.tag.as_str(),
                        aopt.pubkey.as_str(),
                    ) {
                        error!("Error -> {:?}", e);
                    }
                }
                AccountSsh::Delete(aopt) => {
                    let client = aopt.copt.to_client();
                    if let Err(e) = client.idm_account_delete_ssh_pubkey(
                        aopt.aopts.account_id.as_str(),
                        aopt.tag.as_str(),
                    ) {
                        error!("Error -> {:?}", e);
                    }
                }
            }, // end AccountOpt::Ssh
            AccountOpt::List(copt) => {
                let client = copt.to_client();
                match client.idm_account_list() {
                    Ok(r) => r.iter().for_each(|ent| println!("{}", ent)),
                    Err(e) => error!("Error -> {:?}", e),
                }
            }
            AccountOpt::Get(aopt) => {
                let client = aopt.copt.to_client();
                match client.idm_account_get(aopt.aopts.account_id.as_str()) {
                    Ok(Some(e)) => println!("{}", e),
                    Ok(None) => println!("No matching entries"),
                    Err(e) => error!("Error -> {:?}", e),
                }
            }
            AccountOpt::Delete(aopt) => {
                let client = aopt.copt.to_client();
                if let Err(e) = client.idm_account_delete(aopt.aopts.account_id.as_str()) {
                    error!("Error -> {:?}", e)
                }
            }
            AccountOpt::Create(acopt) => {
                let client = acopt.copt.to_client();
                if let Err(e) = client.idm_account_create(
                    acopt.aopts.account_id.as_str(),
                    acopt.display_name.as_str(),
                ) {
                    error!("Error -> {:?}", e)
                }
            }
            AccountOpt::Validity(avopt) => match avopt {
                AccountValidity::Show(ano) => {
                    let client = ano.copt.to_client();

                    let r = client
                        .idm_account_get_attr(ano.aopts.account_id.as_str(), "account_expire")
                        .and_then(|v1| {
                            client
                                .idm_account_get_attr(
                                    ano.aopts.account_id.as_str(),
                                    "account_valid_from",
                                )
                                .map(|v2| (v1, v2))
                        });

                    match r {
                        Ok((ex, vf)) => {
                            if let Some(t) = vf {
                                // Convert the time to local timezone.
                                let t = OffsetDateTime::parse(&t[0], time::Format::Rfc3339)
                                    .map(|odt| {
                                        odt.to_offset(
                                            time::UtcOffset::try_current_local_offset()
                                                .unwrap_or(time::UtcOffset::UTC),
                                        )
                                        .format(time::Format::Rfc3339)
                                    })
                                    .unwrap_or_else(|_| "invalid timestamp".to_string());

                                println!("valid after: {}", t);
                            } else {
                                println!("valid after: any time");
                            }

                            if let Some(t) = ex {
                                let t = OffsetDateTime::parse(&t[0], time::Format::Rfc3339)
                                    .map(|odt| {
                                        odt.to_offset(
                                            time::UtcOffset::try_current_local_offset()
                                                .unwrap_or(time::UtcOffset::UTC),
                                        )
                                        .format(time::Format::Rfc3339)
                                    })
                                    .unwrap_or_else(|_| "invalid timestamp".to_string());
                                println!("expire: {}", t);
                            } else {
                                println!("expire: never");
                            }
                        }
                        Err(e) => error!("Error -> {:?}", e),
                    }
                }
                AccountValidity::ExpireAt(ano) => {
                    let client = ano.copt.to_client();
                    if matches!(ano.datetime.as_str(), "never" | "clear") {
                        // Unset the value
                        match client
                            .idm_account_purge_attr(ano.aopts.account_id.as_str(), "account_expire")
                        {
                            Err(e) => error!("Error -> {:?}", e),
                            _ => println!("Success"),
                        }
                    } else {
                        if let Err(e) =
                            OffsetDateTime::parse(ano.datetime.as_str(), time::Format::Rfc3339)
                        {
                            error!("Error -> {:?}", e);
                            return;
                        }

                        match client.idm_account_set_attr(
                            ano.aopts.account_id.as_str(),
                            "account_expire",
                            &[ano.datetime.as_str()],
                        ) {
                            Err(e) => error!("Error -> {:?}", e),
                            _ => println!("Success"),
                        }
                    }
                }
                AccountValidity::BeginFrom(ano) => {
                    let client = ano.copt.to_client();
                    if matches!(ano.datetime.as_str(), "any" | "clear" | "whenever") {
                        // Unset the value
                        match client.idm_account_purge_attr(
                            ano.aopts.account_id.as_str(),
                            "account_valid_from",
                        ) {
                            Err(e) => error!("Error -> {:?}", e),
                            _ => println!("Success"),
                        }
                    } else {
                        // Attempt to parse and set
                        if let Err(e) =
                            OffsetDateTime::parse(ano.datetime.as_str(), time::Format::Rfc3339)
                        {
                            error!("Error -> {:?}", e);
                            return;
                        }

                        match client.idm_account_set_attr(
                            ano.aopts.account_id.as_str(),
                            "account_valid_from",
                            &[ano.datetime.as_str()],
                        ) {
                            Err(e) => error!("Error -> {:?}", e),
                            _ => println!("Success"),
                        }
                    }
                }
            }, // end AccountOpt::Validity
        }
    }
}