rooster 2.14.1

A simple password manager
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
// #![allow(useless_format, too_many_arguments)]

use crate::password::v2::PasswordStore;
use clap::{Arg, ArgAction, Command};
use io::CliInputOutput;
pub use io::CursorInputOutput;
use io::OutputType;
pub use io::RegularInputOutput;
use rtoolbox::safe_string::SafeString;
use rtoolbox::safe_vec::SafeVec;
use std::env;
use std::fs::File;
use std::io::Read;
use std::io::Result as IoResult;
use std::ops::Deref;
use std::path::{Path, PathBuf};

mod aes;
mod clip;
mod commands;
mod ffi;
mod generate;
mod io;
mod list;
mod password;
#[cfg(unix)]
mod quale;
#[cfg(unix)]
mod shell_escape;

#[cfg(windows)]
fn example_environment_variable_configuration() -> &'static str {
    return "set ROOSTER_FILE=C:\\Users\\my-user\\path\\to\\rooster.file";
}

#[cfg(unix)]
fn example_environment_variable_configuration() -> &'static str {
    "export ROOSTER_FILE=$HOME/path/to/rooster.file"
}

fn only_digits(s: &str) -> bool {
    s.chars()
        .map(|c| char::is_ascii_digit(&c))
        .collect::<Vec<bool>>()
        .contains(&false)
}

fn validate_arg_usize(v: &str) -> Result<usize, String> {
    if only_digits(v) {
        return Err(String::from("The value must be made of digits"));
    }
    Ok(v.parse::<usize>().unwrap())
}

fn validate_arg_u8(v: &str) -> Result<u8, String> {
    if only_digits(v) {
        return Err(String::from("The value must be made of digits"));
    }
    Ok(v.parse::<u8>().unwrap())
}

fn validate_arg_u32(v: &str) -> Result<u32, String> {
    if only_digits(v) {
        return Err(String::from("The value must be made of digits"));
    }
    Ok(v.parse::<u32>().unwrap())
}

fn open_password_file(filename: &str) -> IoResult<File> {
    let mut options = std::fs::OpenOptions::new();
    options.read(true);
    options.write(true);
    options.create(false);
    options.open(Path::new(filename))
}

fn create_password_file(filename: &str) -> IoResult<File> {
    let mut options = std::fs::OpenOptions::new();
    options.read(true);
    options.write(true);
    options.create(true);
    options.open(Path::new(filename))
}

fn sync_password_store(
    store: &mut PasswordStore,
    file: &mut File,
    io: &mut impl CliInputOutput,
) -> Result<(), i32> {
    if let Err(err) = store.sync(file) {
        io.error(
            format!("I could not save the password file (reason: {:?}).", err),
            OutputType::Error,
        );
        return Err(1);
    }

    Ok(())
}

fn get_password_store(file: &mut File, io: &mut impl CliInputOutput) -> Result<PasswordStore, i32> {
    // Read the Rooster file contents.
    let mut input: SafeVec = SafeVec::new(Vec::new());
    file.read_to_end(input.inner_mut()).map_err(|_| 1)?;

    get_password_store_from_input_interactive(&input, 3, false, io).map_err(|_| 1)
}

fn get_password_store_from_input_interactive(
    input: &SafeVec,
    retries: i32,
    force_upgrade: bool,
    io: &mut impl CliInputOutput,
) -> Result<PasswordStore, password::PasswordError> {
    let master_password = match ask_master_password(io) {
        Ok(p) => p,
        Err(err) => {
            io.error(
                format!(
                    "Woops, I could not read your master password (reason: {}).",
                    err
                ),
                OutputType::Error,
            );
            return Err(password::PasswordError::Io(err));
        }
    };

    match get_password_store_from_input(input, &master_password, force_upgrade) {
        Ok(store) => Ok(store),
        Err(password::PasswordError::OutdatedRoosterBinary) => {
            io.error(
                "I could not open the Rooster file because your version of Rooster is outdated.",
                OutputType::Error,
            );
            io.error(
                "Try upgrading Rooster to the latest version.",
                OutputType::Error,
            );
            Err(password::PasswordError::OutdatedRoosterBinary)
        }
        Err(password::PasswordError::Io(err)) => {
            io.error(
                format!("I couldn't open your Rooster file (reason: {:?})", err),
                OutputType::Error,
            );
            Err(password::PasswordError::Io(err))
        }
        Err(password::PasswordError::NeedUpgradeFromV1) => {
            io.error("Your Rooster file has version 1. You need to upgrade to version 2.\n\nWARNING: If in doubt, it could mean you've been hacked. Only \
                 proceed if you recently upgraded your Rooster installation.\nUpgrade to version 2? [y/n]", OutputType::Error
            );
            loop {
                match io.read_line() {
                    Ok(line) => {
                        if line.starts_with('y') {
                            // This time we'll try to upgrade
                            return get_password_store_from_input_interactive(
                                input, retries, true, io,
                            );
                        } else if line.starts_with('n') {
                            // The user doesn't want to upgrade, that's fine
                            return Err(password::PasswordError::NoUpgrade);
                        } else {
                            io.error(
                                "I did not get that. Upgrade from v1 to v2? [y/n]",
                                OutputType::Error,
                            );
                        }
                    }
                    Err(io_err) => {
                        io.error(format!(
                                "Woops, an error occured while reading your response (reason: {:?}).",
                                io_err
                            ), OutputType::Error,
                        );
                        return Err(password::PasswordError::Io(io_err));
                    }
                }
            }
        }
        Err(password::PasswordError::InvalidPassword) => {
            if retries - 1 <= 0 {
                io.error(
                    "Woops, that's not the right password. Aborting.",
                    OutputType::Error,
                );
                return Err(password::PasswordError::InvalidPassword);
            }
            io.error(
                "Woops, that's not the right password. Let's try again.",
                OutputType::Error,
            );
            get_password_store_from_input_interactive(input, retries - 1, false, io)
        }
        Err(err) => {
            io.error(
                format!("I couldn't open your Rooster file (reason: {:?})", err),
                OutputType::Error,
            );
            Err(err)
        }
    }
}

fn get_password_store_from_input(
    input: &SafeVec,
    master_password: &SafeString,
    upgrade: bool,
) -> Result<PasswordStore, password::PasswordError> {
    // Try to open the file as is.
    match PasswordStore::from_input(master_password.clone(), input.clone()) {
        Ok(store) => Ok(store),
        Err(password::PasswordError::InvalidPassword) => {
            Err(password::PasswordError::InvalidPassword)
        }
        Err(password::PasswordError::OutdatedRoosterBinary) => {
            Err(password::PasswordError::OutdatedRoosterBinary)
        }
        Err(password::PasswordError::NeedUpgradeFromV1) => {
            if !upgrade {
                return Err(password::PasswordError::NeedUpgradeFromV1);
            }

            // If we can't open the file, we may need to upgrade its format first.
            match password::upgrade(master_password.clone(), input.clone()) {
                Ok(store) => Ok(store),
                Err(err) => Err(err),
            }
        }
        Err(err) => Err(err),
    }
}

fn ask_master_password(io: &mut impl CliInputOutput) -> IoResult<SafeString> {
    io.prompt_password("Type your master password: ")
}

pub fn main_with_args(
    args: &[&str],
    io: &mut impl CliInputOutput,
    rooster_file_path: &PathBuf,
) -> i32 {
    let matches = Command::new("rooster")
        .help_expected(true)
        .disable_help_subcommand(true)
        .subcommand_required(true)
        .arg_required_else_help(true)
        .about("Welcome to Rooster, a simple password manager")
        .version(env!("CARGO_PKG_VERSION"))
        .subcommand(
            Command::new("init")
                .about("Create a new password file")
                .arg(
                    Arg::new("force-for-tests")
                        .action(ArgAction::SetTrue)
                        .long("force-for-tests")
                        .hide(true)
                        .help("Forces initializing the file, used in integration tests only"),
                ),
        )
        .subcommand(
            Command::new("add")
                .about("Add a new password manually")
                .arg(
                    Arg::new("app")
                        .required(true)
                        .help("The name of the app (fuzzy-matched)"),
                )
                .arg(
                    Arg::new("username")
                        .required(true)
                        .help("Your username for this account"),
                )
                .arg(
                    Arg::new("show")
                        .action(ArgAction::SetTrue)
                        .short('s')
                        .long("show")
                        .help("Show the password instead of copying it to the clipboard"),
                ),
        )
        .subcommand(
            Command::new("change")
                .about("Change a password manually")
                .arg(
                    Arg::new("app")
                        .required(true)
                        .help("The name of the app (fuzzy-matched)"),
                )
                .arg(
                    Arg::new("show")
                        .action(ArgAction::SetTrue)
                        .short('s')
                        .long("show")
                        .help("Show the password instead of copying it to the clipboard"),
                ),
        )
        .subcommand(
            Command::new("delete").about("Delete a password").arg(
                Arg::new("app")
                    .required(true)
                    .help("The name of the app (fuzzy-matched)"),
            ),
        )
        .subcommand(
            Command::new("generate")
                .about("Generate a password")
                .arg(
                    Arg::new("app")
                        .required(true)
                        .help("The name of the app (fuzzy-matched)"),
                )
                .arg(
                    Arg::new("username")
                        .required(true)
                        .help("Your username for this account"),
                )
                .arg(
                    Arg::new("show")
                        .action(ArgAction::SetTrue)
                        .short('s')
                        .long("show")
                        .help("Show the password instead of copying it to the clipboard"),
                )
                .arg(
                    Arg::new("alnum")
                        .action(ArgAction::SetTrue)
                        .short('a')
                        .long("alnum")
                        .help("Only use alpha numeric (a-z, A-Z, 0-9) in generated passwords"),
                )
                .arg(
                    Arg::new("length")
                        .short('l')
                        .long("length")
                        .default_value("32")
                        .help("Set a custom length for the generated password")
                        .value_parser(validate_arg_usize),
                ),
        )
        .subcommand(
            Command::new("regenerate")
                .about("Regenerate a previously existing password")
                .arg(
                    Arg::new("app")
                        .required(true)
                        .help("The name of the app (fuzzy-matched)"),
                )
                .arg(
                    Arg::new("show")
                        .action(ArgAction::SetTrue)
                        .short('s')
                        .long("show")
                        .help("Show the password instead of copying it to the clipboard"),
                )
                .arg(
                    Arg::new("alnum")
                        .action(ArgAction::SetTrue)
                        .short('a')
                        .long("alnum")
                        .help("Only use alpha numeric (a-z, A-Z, 0-9) in generated passwords"),
                )
                .arg(
                    Arg::new("length")
                        .short('l')
                        .long("length")
                        .default_value("32")
                        .help("Set a custom length for the generated password")
                        .value_parser(validate_arg_usize),
                ),
        )
        .subcommand(
            Command::new("get")
                .about("Retrieve a password")
                .arg(
                    Arg::new("app")
                        .required(true)
                        .help("The name of the app (fuzzy-matched)"),
                )
                .arg(
                    Arg::new("show")
                        .action(ArgAction::SetTrue)
                        .short('s')
                        .long("show")
                        .help("Show the password instead of copying it to the clipboard"),
                ),
        )
        .subcommand(
            Command::new("rename")
                .about("Rename the app for a password")
                .arg(
                    Arg::new("app")
                        .required(true)
                        .help("The current name of the app (fuzzy-matched)"),
                )
                .arg(
                    Arg::new("new_name")
                        .required(true)
                        .help("The new name of the app"),
                ),
        )
        .subcommand(
            Command::new("transfer")
                .about("Change the username for a password")
                .arg(
                    Arg::new("app")
                        .required(true)
                        .help("The current name of the app (fuzzy-matched)"),
                )
                .arg(
                    Arg::new("new_username")
                        .required(true)
                        .help("Your new username for this account"),
                ),
        )
        .subcommand(Command::new("list").about("List all apps and usernames"))
        .subcommand(
            Command::new("import")
                .subcommand_required(true)
                .arg_required_else_help(true)
                .about("Import all your existing passwords from elsewhere")
                .subcommand(
                    Command::new("json")
                        .about("Import a file generated with `rooster export json`")
                        .arg(
                            Arg::new("path")
                                .required(true)
                                .help("The path to the file you want to import"),
                        ),
                )
                .subcommand(
                    Command::new("csv")
                        .about("Import a file generated with `rooster export csv`")
                        .arg(
                            Arg::new("path")
                                .required(true)
                                .help("The path to the file you want to import"),
                        ),
                )
                .subcommand(
                    Command::new("1password")
                        .about("Import a \"Common Fields\" CSV export from 1Password")
                        .arg(
                            Arg::new("path")
                                .required(true)
                                .help("The path to the file you want to import"),
                        ),
                ),
        )
        .subcommand(
            Command::new("export")
                .subcommand_required(true)
                .arg_required_else_help(true)
                .about("Export raw password data")
                .subcommand(Command::new("json").about("Export raw password data in JSON format"))
                .subcommand(Command::new("csv").about("Export raw password data in CSV format"))
                .subcommand(
                    Command::new("1password")
                        .about("Export raw password data in 1Password compatible CSV format"),
                ),
        )
        .subcommand(Command::new("set-master-password").about("Set your master password"))
        .subcommand(
            Command::new("set-scrypt-params")
                .about("Set the key derivation parameters")
                .arg(
                    Arg::new("log2n")
                        .required(true)
                        .help("The log2n parameter")
                        .value_parser(validate_arg_u8),
                )
                .arg(
                    Arg::new("r")
                        .required(true)
                        .help("The r parameter")
                        .value_parser(validate_arg_u32),
                )
                .arg(
                    Arg::new("p")
                        .required(true)
                        .help("The p parameter")
                        .value_parser(validate_arg_u32),
                )
                .arg(
                    Arg::new("force")
                        .action(ArgAction::SetTrue)
                        .short('f')
                        .long("force")
                        .help("Disable parameter checks"),
                ),
        )
        .get_matches_from(args);

    let subcommand = matches.subcommand_name().unwrap();

    let command_matches = matches.subcommand_matches(subcommand).unwrap();

    if subcommand == "init" {
        return match commands::init::callback_exec(command_matches, io, rooster_file_path) {
            Err(i) => i,
            _ => 0,
        };
    }

    let password_file_path_as_string = rooster_file_path.to_string_lossy().into_owned();

    if !rooster_file_path.exists() {
        io.title("First time user", OutputType::Standard);
        io.nl(OutputType::Standard);
        io.info("Try `rooster init`.", OutputType::Standard);
        io.nl(OutputType::Standard);
        io.title("Long time user", OutputType::Standard);
        io.nl(OutputType::Standard);
        io.info(
            "Set the ROOSTER_FILE environment variable. For instance:",
            OutputType::Standard,
        );
        io.info(
            format!("    {}", example_environment_variable_configuration()),
            OutputType::Standard,
        );
        return 1;
    }

    let mut file = match open_password_file(password_file_path_as_string.deref()) {
        Ok(file) => file,
        Err(err) => {
            match err.kind() {
                std::io::ErrorKind::NotFound => {
                    io.error(
                        "Woops, I can't find your password file. Run `rooster init` to create one.",
                        OutputType::Error,
                    );
                }
                _ => {
                    io.error(
                        format!(
                            "Woops, I couldn't read your password file ({} for \"{}\").",
                            err, password_file_path_as_string
                        ),
                        OutputType::Error,
                    );
                }
            }
            return 1;
        }
    };

    let mut store = match get_password_store(&mut file, io) {
        Err(code) => return code,
        Ok(store) => store,
    };

    let callback = match subcommand {
        "get" => commands::get::callback_exec,
        "add" => commands::add::callback_exec,
        "delete" => commands::delete::callback_exec,
        "generate" => commands::generate::callback_exec,
        "regenerate" => commands::regenerate::callback_exec,
        "list" => commands::list::callback_exec,
        "import" => commands::import::callback_exec,
        "export" => commands::export::callback_exec,
        "set-master-password" => commands::set_master_password::callback_exec,
        "set-scrypt-params" => commands::set_scrypt_params::callback_exec,
        "rename" => commands::rename::callback_exec,
        "transfer" => commands::transfer::callback_exec,
        "change" => commands::change::callback_exec,
        _ => unreachable!("Validation should have been done by `clap` before"),
    };

    if let Err(code) = callback(command_matches, &mut store, io) {
        return code;
    }

    if let Err(code) = sync_password_store(&mut store, &mut file, io) {
        return code;
    }

    0
}