├── .gitignore ├── passlane.sh ├── src ├── ui │ ├── mod.rs │ ├── output.rs │ └── input.rs ├── vault │ ├── mod.rs │ ├── vault_trait.rs │ ├── entities.rs │ └── keepass_vault.rs ├── actions │ ├── generate.rs │ ├── help.rs │ ├── lock.rs │ ├── unlock.rs │ ├── import.rs │ ├── export.rs │ ├── add.rs │ ├── mod.rs │ ├── init.rs │ ├── edit.rs │ ├── delete.rs │ └── show.rs ├── keychain.rs ├── crypto.rs ├── store.rs └── main.rs ├── copy_schema.sh ├── test.csv ├── .idea ├── codeStyles │ └── codeStyleConfig.xml ├── misc.xml ├── vcs.xml ├── .gitignore ├── modules.xml └── passlane.iml ├── shell.nix ├── default.nix ├── flake.nix ├── flake.lock ├── SECURITY.md ├── Cargo.toml ├── .github └── workflows │ └── release.yml ├── CHANGELOG.md ├── TODO.md ├── README.md └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | .cargo/config.toml 2 | /target 3 | -------------------------------------------------------------------------------- /passlane.sh: -------------------------------------------------------------------------------- 1 | #! /bin/sh 2 | /usr/local/bin/passlane -------------------------------------------------------------------------------- /src/ui/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod input; 2 | pub mod output; 3 | -------------------------------------------------------------------------------- /copy_schema.sh: -------------------------------------------------------------------------------- 1 | #! /bin/sh 2 | cp ../../passlanevault.com/graphql/schema.graphql ./src -------------------------------------------------------------------------------- /src/vault/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod entities; 2 | pub mod vault_trait; 3 | pub mod keepass_vault; 4 | -------------------------------------------------------------------------------- /test.csv: -------------------------------------------------------------------------------- 1 | username,password,service 2 | apina,123412345a,nakkila.net 3 | apina,123412345a,nakkinack.net -------------------------------------------------------------------------------- /.idea/codeStyles/codeStyleConfig.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 6 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /shelf/ 3 | /workspace.xml 4 | # Editor-based HTTP Client requests 5 | /httpRequests/ 6 | # Datasource local storage ignored files 7 | /dataSources/ 8 | /dataSources.local.xml 9 | # GitHub Copilot persisted chat sessions 10 | /copilot/chatSessions 11 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /shell.nix: -------------------------------------------------------------------------------- 1 | { pkgs ? import { } }: 2 | pkgs.mkShell { 3 | # Get dependencies from the main package 4 | inputsFrom = [ (pkgs.callPackage ./default.nix { }) ]; 5 | # Additional tooling 6 | buildInputs = with pkgs; [ 7 | rust-analyzer # LSP Server 8 | rustfmt # Formatter 9 | clippy # Linter 10 | ]; 11 | } -------------------------------------------------------------------------------- /src/actions/generate.rs: -------------------------------------------------------------------------------- 1 | use crate::actions::{copy_to_clipboard, Action}; 2 | use crate::crypto; 3 | use crate::vault::entities::Error; 4 | 5 | pub struct GeneratePasswordAction; 6 | 7 | impl Action for GeneratePasswordAction { 8 | fn run(&self) -> Result { 9 | let password = crypto::generate(); 10 | copy_to_clipboard(&password); 11 | Ok("Password - also copied to clipboard".to_string()) 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /default.nix: -------------------------------------------------------------------------------- 1 | { pkgs ? import { } }: 2 | let manifest = (pkgs.lib.importTOML ./Cargo.toml).package; 3 | in 4 | pkgs.rustPlatform.buildRustPackage rec { 5 | pname = manifest.name; 6 | version = manifest.version; 7 | cargoLock = { 8 | lockFile = ./Cargo.lock; 9 | }; 10 | src = pkgs.lib.cleanSource ./.; 11 | 12 | buildInputs = [ 13 | pkgs.darwin.apple_sdk.frameworks.CoreServices 14 | pkgs.darwin.apple_sdk.frameworks.AppKit 15 | ]; 16 | } -------------------------------------------------------------------------------- /.idea/passlane.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /flake.nix: -------------------------------------------------------------------------------- 1 | { 2 | description = "A password manager for the command line"; 3 | inputs = { 4 | nixpkgs.url = "github:nixos/nixpkgs/nixos-unstable"; 5 | }; 6 | outputs = { self, nixpkgs }: 7 | let 8 | supportedSystems = [ "aarch64-darwin" ]; 9 | forAllSystems = nixpkgs.lib.genAttrs supportedSystems; 10 | pkgsFor = nixpkgs.legacyPackages; 11 | in { 12 | packages = forAllSystems (system: { 13 | default = pkgsFor.${system}.callPackage ./default.nix { }; 14 | }); 15 | devShells = forAllSystems (system: { 16 | default = pkgsFor.${system}.callPackage ./shell.nix { }; 17 | }); 18 | }; 19 | } -------------------------------------------------------------------------------- /flake.lock: -------------------------------------------------------------------------------- 1 | { 2 | "nodes": { 3 | "nixpkgs": { 4 | "locked": { 5 | "lastModified": 1711163522, 6 | "narHash": "sha256-YN/Ciidm+A0fmJPWlHBGvVkcarYWSC+s3NTPk/P+q3c=", 7 | "owner": "nixos", 8 | "repo": "nixpkgs", 9 | "rev": "44d0940ea560dee511026a53f0e2e2cde489b4d4", 10 | "type": "github" 11 | }, 12 | "original": { 13 | "owner": "nixos", 14 | "ref": "nixos-unstable", 15 | "repo": "nixpkgs", 16 | "type": "github" 17 | } 18 | }, 19 | "root": { 20 | "inputs": { 21 | "nixpkgs": "nixpkgs" 22 | } 23 | } 24 | }, 25 | "root": "root", 26 | "version": 7 27 | } 28 | -------------------------------------------------------------------------------- /src/actions/help.rs: -------------------------------------------------------------------------------- 1 | use clap::Command; 2 | use crate::actions::Action; 3 | use crate::vault::entities::Error; 4 | 5 | pub struct PrintHelpAction { 6 | cli: Command, 7 | } 8 | 9 | impl PrintHelpAction { 10 | pub fn new(cli: Command) -> PrintHelpAction { 11 | PrintHelpAction { 12 | cli 13 | } 14 | } 15 | } 16 | 17 | impl Action for PrintHelpAction { 18 | fn run(&self) -> Result { 19 | // write the help to a string 20 | let mut help_text = Vec::new(); 21 | self.cli.clone().write_help(&mut help_text)?; 22 | 23 | String::from_utf8(help_text).map(|s| s.to_string()).map_err(|_| Error::new("Failed to convert help text to string")) 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/actions/lock.rs: -------------------------------------------------------------------------------- 1 | use crate::actions::Action; 2 | use crate::keychain; 3 | use crate::vault::entities::Error; 4 | 5 | pub struct LockAction {} 6 | 7 | impl Action for LockAction { 8 | fn run(&self) -> Result { 9 | let credential_vault_response = match keychain::delete_master_password() { 10 | Ok(_) => { 11 | "Vault locked" 12 | } 13 | Err(_) => { 14 | "Vault was already locked" 15 | } 16 | }; 17 | let totp_vault_response = match keychain::delete_totp_master_password() { 18 | Ok(_) => { 19 | "TOTP vault locked" 20 | } 21 | Err(_) => { 22 | "TOTP vault was already locked" 23 | } 24 | }; 25 | Ok(format!("{}\n{}", credential_vault_response, totp_vault_response)) 26 | } 27 | } -------------------------------------------------------------------------------- /src/actions/unlock.rs: -------------------------------------------------------------------------------- 1 | use clap::ArgMatches; 2 | use crate::actions::{Action, unlock, unlock_totp_vault}; 3 | use crate::keychain; 4 | use crate::vault::entities::Error; 5 | 6 | pub struct UnlockAction { 7 | pub totp: bool, 8 | } 9 | 10 | impl UnlockAction { 11 | pub fn new(matches: &ArgMatches) -> UnlockAction { 12 | UnlockAction { 13 | totp: matches.get_one::("otp").map_or(false, |v| *v), 14 | } 15 | } 16 | } 17 | 18 | impl Action for UnlockAction { 19 | fn run(&self) -> Result { 20 | if self.totp { 21 | let vault = unlock_totp_vault()?; 22 | keychain::save_totp_master_password(&vault.get_master_password())?; 23 | } else { 24 | let vault = unlock()?; 25 | keychain::save_master_password(&vault.get_master_password())?; 26 | } 27 | Ok("Vault unlocked".to_string()) 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | 3 | Passlane is free software and is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose and noninfringement. In no event shall the authors or copyright holders be liable for any claim, damages or other liability, whether in an action of contract, tort or otherwise, arising from, out of or in connection with the software or the use or other dealings in the software. 4 | 5 | ## Supported Versions 6 | 7 | Only the current major version will receive security updates. 8 | 9 | ## Reporting a Vulnerability 10 | 11 | Please use the GitHub private vulnerability reporting features to report vulnerability. See the [GitHub docs](https://docs.github.com/en/code-security/security-advisories/guidance-on-reporting-and-writing/privately-reporting-a-security-vulnerability) for more details. 12 | 13 | Since keepass-rs is a volunteer project, vulnerabilities will be addressed on a best effort basis, with no guarantees made on timelines to resolution. 14 | -------------------------------------------------------------------------------- /src/actions/import.rs: -------------------------------------------------------------------------------- 1 | use crate::actions::UnlockingAction; 2 | use crate::store; 3 | use crate::vault::entities::Error; 4 | use crate::vault::vault_trait::Vault; 5 | use clap::ArgMatches; 6 | 7 | pub struct ImportCsvAction { 8 | pub file_path: String, 9 | } 10 | 11 | impl ImportCsvAction { 12 | pub fn new(matches: &ArgMatches) -> ImportCsvAction { 13 | ImportCsvAction { 14 | file_path: matches 15 | .get_one::("FILE_PATH") 16 | .expect("required") 17 | .to_string(), 18 | } 19 | } 20 | } 21 | 22 | fn push_from_csv(vault: &mut Box, file_path: &str) -> Result { 23 | let creds = store::read_from_csv(file_path)?; 24 | vault.save_credentials(&creds)?; 25 | let num_imported = creds.len(); 26 | Ok(num_imported.try_into().unwrap()) 27 | } 28 | 29 | impl UnlockingAction for ImportCsvAction { 30 | fn run_with_vault(&self, vault: &mut Box) -> Result, Error> { 31 | push_from_csv(vault, &self.file_path) 32 | .map(|count| format!("Imported {} entries", count)) 33 | .map(Some) 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "passlane" 3 | version = "2.5.1" 4 | edition = "2021" 5 | authors = ["Anssi Piirainen "] 6 | license = "GPL-3.0-or-later" 7 | description = "A password manager and authenticator for the command line" 8 | readme = "README.md" 9 | homepage = "https://github.com/anssip/passlane" 10 | repository = "https://github.com/anssip/passlane" 11 | keywords = [ 12 | "keepass", 13 | "password-manager", 14 | "password-generator", 15 | "totp", 16 | "authenticator", 17 | ] 18 | categories = ["command-line-utilities"] 19 | 20 | [dependencies] 21 | rand = "0.8.5" 22 | clipboard = "0.5.0" 23 | clap = "4.5.4" 24 | csv = "1.3.0" 25 | serde = { version = "1.0.198", features = ["derive"] } 26 | serde_json = "1.0.116" 27 | erased-serde = "0.3" 28 | magic-crypt = "3.1.10" 29 | dirs = "5.0.1" 30 | regex = "1.5.5" 31 | comfy-table = "7.0.1" 32 | serde_urlencoded = "0.7.1" 33 | log = "0.4.16" 34 | anyhow = "1.0.56" 35 | chrono = { version = "0.4.19", features = ["serde"] } 36 | env_logger = "0.10.0" 37 | hex = "0.4.3" 38 | keepass-ng = { version = "0.9.0", features = ["save_kdbx4", "totp"] } 39 | keyring = "2.3.2" 40 | uuid = { version = "1.8.0", features = ["v4", "serde"] } 41 | percent-encoding = "2.3.1" 42 | rustyline-derive = "0.10.0" 43 | rustyline = "14.0.0" 44 | inquire = "0.7.5" -------------------------------------------------------------------------------- /src/keychain.rs: -------------------------------------------------------------------------------- 1 | use crate::vault::entities::Error; 2 | use keyring::Entry; 3 | use log::debug; 4 | 5 | const SERVICE_NAME: &str = "passlane_master_pwd"; 6 | const SERVICE_NAME_TOTP: &str = "passlane_totp_master_pwd"; 7 | const USERNAME: &str = "passlane"; 8 | 9 | impl From for Error { 10 | fn from(e: keyring::Error) -> Self { 11 | Error { 12 | message: e.to_string(), 13 | } 14 | } 15 | } 16 | 17 | pub fn save_master_password(pwd: &str) -> Result<(), Error> { 18 | let entry = Entry::new(SERVICE_NAME, USERNAME)?; 19 | Ok(entry.set_password(pwd)?) 20 | } 21 | pub fn save_totp_master_password(pwd: &str) -> Result<(), Error> { 22 | let entry = Entry::new(SERVICE_NAME_TOTP, USERNAME)?; 23 | Ok(entry.set_password(pwd)?) 24 | } 25 | 26 | pub fn get_master_password() -> Result { 27 | debug!("Getting master password from keychain"); 28 | let entry = Entry::new(SERVICE_NAME, USERNAME)?; 29 | Ok(entry.get_password()?) 30 | } 31 | 32 | pub fn delete_master_password() -> Result<(), Error> { 33 | let entry = Entry::new(SERVICE_NAME, USERNAME)?; 34 | Ok(entry.delete_password()?) 35 | } 36 | 37 | pub(crate) fn get_totp_master_password() -> Result { 38 | let entry = Entry::new(SERVICE_NAME_TOTP, USERNAME)?; 39 | Ok(entry.get_password()?) 40 | } 41 | 42 | pub(crate) fn delete_totp_master_password() -> Result<(), Error> { 43 | let entry = Entry::new(SERVICE_NAME_TOTP, USERNAME)?; 44 | Ok(entry.delete_password()?) 45 | } 46 | -------------------------------------------------------------------------------- /src/crypto.rs: -------------------------------------------------------------------------------- 1 | use rand::thread_rng; 2 | use rand::Rng; 3 | 4 | const LOW_CASE: &str = "abcdefghijklmnopqrstuvxyz"; 5 | const UP_CASE: &str = "ABCDEFGHIJKLMNOPQRSTUVXYZ"; 6 | const NUMBERS: &str = "0123456789"; 7 | pub const SPECIAL: &str = "£$&()*+[]@#^-_!?:;,.{}<>~%/\\|\"'`´^¨=§"; 8 | 9 | pub fn generate() -> String { 10 | let mut password = "".to_string(); 11 | 12 | for _ in 0..=14 { 13 | let char_group = random_index(4); 14 | password = match char_group { 15 | 0 => append(&password, &LOW_CASE.to_string()), 16 | 1 => append(&password, &UP_CASE.to_string()), 17 | 2 => append(&password, &NUMBERS.to_string()), 18 | 3 => append(&password, &SPECIAL.to_string()), 19 | _ => password, 20 | } 21 | } 22 | password 23 | } 24 | 25 | pub fn validate_password(value: &String) -> bool { 26 | value.len() >= 15 27 | && value.chars().any(|c| LOW_CASE.contains(c)) 28 | && value.chars().any(|c| UP_CASE.contains(c)) 29 | && value.chars().any(|c| NUMBERS.contains(c)) 30 | && value.chars().any(|c| SPECIAL.contains(c)) 31 | } 32 | 33 | fn random_index(range: usize) -> usize { 34 | let mut rng = thread_rng(); 35 | rng.gen_range(0..range.try_into().unwrap()) 36 | } 37 | 38 | fn append(to: &String, charset: &String) -> String { 39 | let character = charset.chars().nth(random_index(charset.len() - 1)); 40 | let character = match character { 41 | Some(c) => c, 42 | None => '-', 43 | }; 44 | let mut result = String::from(to); 45 | result.push(character); 46 | result 47 | } 48 | -------------------------------------------------------------------------------- /src/actions/export.rs: -------------------------------------------------------------------------------- 1 | use clap::ArgMatches; 2 | use log::debug; 3 | use crate::actions::{ItemType, UnlockingAction}; 4 | use crate::store; 5 | use crate::vault::entities::Error; 6 | use crate::vault::vault_trait::Vault; 7 | 8 | pub struct ExportAction { 9 | pub file_path: String, 10 | pub item_type: ItemType, 11 | } 12 | 13 | impl ExportAction { 14 | pub fn new(matches: &ArgMatches) -> ExportAction { 15 | ExportAction { 16 | file_path: matches.get_one::("file_path").expect("required").to_string(), 17 | item_type: ItemType::new_from_args(matches), 18 | } 19 | } 20 | pub fn export_csv(&self, vault: &mut Box) -> Result { 21 | debug!("exporting to csv"); 22 | if self.item_type == ItemType::Credential { 23 | let creds = vault.grep(None); 24 | if creds.is_empty() { 25 | println!("No credentials found"); 26 | return Ok(0); 27 | } 28 | store::write_credentials_to_csv(&self.file_path, &creds) 29 | } else if self.item_type == ItemType::Payment { 30 | let cards = vault.find_payments(); 31 | store::write_payment_cards_to_csv(&self.file_path, &cards) 32 | } else if self.item_type == ItemType::Note { 33 | let notes = vault.find_notes(); 34 | store::write_secure_notes_to_csv(&self.file_path, ¬es) 35 | } else { 36 | Ok(0) 37 | } 38 | } 39 | } 40 | 41 | impl UnlockingAction for ExportAction { 42 | fn run_with_vault(&self, vault: &mut Box) -> Result, Error> { 43 | self.export_csv(vault).map(|count| format!("Exported {} entries", count)).map(Some) 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/vault/vault_trait.rs: -------------------------------------------------------------------------------- 1 | use crate::vault::entities::{Credential, Error, Note, PaymentCard, Totp}; 2 | use uuid::Uuid; 3 | 4 | pub trait PasswordVault { 5 | fn get_master_password(&self) -> String; 6 | 7 | fn grep(&self, grep: Option<&str>) -> Vec; 8 | 9 | fn save_credentials(&mut self, credentials: &Vec) -> Result; 10 | 11 | fn save_one_credential(&mut self, credential: Credential) -> Result<(), Error>; 12 | 13 | fn update_credential(&mut self, credential: Credential) -> Result<(), Error>; 14 | 15 | fn delete_credentials(&mut self, uuid: &Uuid) -> Result<(), Error>; 16 | 17 | fn delete_matching(&mut self, grep: &str) -> Result; 18 | } 19 | 20 | pub trait PaymentVault { 21 | fn find_payments(&self) -> Vec; 22 | 23 | fn save_payment(&mut self, payment: PaymentCard) -> Result<(), Error>; 24 | 25 | fn delete_payment(&mut self, uuid: &Uuid) -> Result<(), Error>; 26 | 27 | fn update_payment(&mut self, payment: PaymentCard) -> Result<(), Error>; 28 | } 29 | 30 | pub trait NoteVault { 31 | fn find_notes(&self) -> Vec; 32 | 33 | fn save_note(&mut self, note: &Note) -> Result<(), Error>; 34 | 35 | fn delete_note(&mut self, uuid: &Uuid) -> Result<(), Error>; 36 | 37 | fn update_note(&mut self, note: Note) -> Result<(), Error>; 38 | } 39 | 40 | pub trait TotpVault { 41 | fn find_totp(&self, grep: Option<&str>) -> Vec; 42 | 43 | fn save_totp(&mut self, totp: &Totp) -> Result<(), Error>; 44 | 45 | fn delete_totp(&mut self, uuid: &Uuid) -> Result<(), Error>; 46 | 47 | fn update_totp(&mut self, totp: Totp) -> Result<(), Error>; 48 | } 49 | 50 | pub trait Vault: PasswordVault + PaymentVault + NoteVault + TotpVault {} 51 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release 2 | 3 | on: 4 | push: 5 | tags: 6 | - v[0-9]+.* 7 | 8 | jobs: 9 | create-release: 10 | runs-on: ubuntu-latest 11 | steps: 12 | - uses: actions/checkout@v3 13 | - uses: taiki-e/create-gh-release-action@v1 14 | with: 15 | # (optional) 16 | changelog: CHANGELOG.md 17 | env: 18 | # (required) 19 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 20 | 21 | upload-assets: 22 | strategy: 23 | matrix: 24 | os: 25 | - macos-latest 26 | - windows-latest 27 | runs-on: ${{ matrix.os }} 28 | steps: 29 | - uses: actions/checkout@v3 30 | - run: rustup update stable 31 | - uses: taiki-e/upload-rust-binary-action@v1 32 | with: 33 | # (required) 34 | bin: passlane 35 | # (optional) On which platform to distribute the `.tar.gz` file. 36 | # [default value: unix] 37 | # [possible values: all, unix, windows, none] 38 | tar: unix 39 | # (optional) On which platform to distribute the `.zip` file. 40 | # [default value: windows] 41 | # [possible values: all, unix, windows, none] 42 | zip: windows 43 | env: 44 | # (required) 45 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 46 | upload-assets-ubuntu: 47 | strategy: 48 | matrix: 49 | os: 50 | - ubuntu-latest 51 | runs-on: ${{ matrix.os }} 52 | steps: 53 | - uses: actions/checkout@v3 54 | - run: rustup update stable 55 | - run: sudo apt-get install -y libxcb-shape0-dev 56 | - run: sudo apt-get install -y libxcb-xfixes0-dev 57 | - uses: taiki-e/upload-rust-binary-action@v1 58 | with: 59 | # (required) 60 | bin: passlane 61 | # (optional) On which platform to distribute the `.tar.gz` file. 62 | # [default value: unix] 63 | # [possible values: all, unix, windows, none] 64 | tar: unix 65 | # (optional) On which platform to distribute the `.zip` file. 66 | # [default value: windows] 67 | # [possible values: all, unix, windows, none] 68 | zip: windows 69 | env: 70 | # (required) 71 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 72 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | ## [2.5.1] 4 | 5 | - Fix to not clear the password prompt when editing a credential and skipping the password change 6 | 7 | ## [2.5.0] 8 | 9 | - Added the init command to easily start using this tool 10 | - Made the UI prompts more user friendly and look better 11 | 12 | ## [2.4.3] 13 | 14 | - Added the edit command to edit entries in the vault 15 | - Fixed a panic that occurred when generating passwords with running passlane without any options 16 | 17 | ## [2.4.2] 18 | 19 | - Fix to validate all input from the command line to be stored (to remove all characters not allowed in Keepass XML) 20 | - Show last modified date for each entry in the results tables 21 | - Fix to store OTPs as protected values in the Keepass file 22 | 23 | ## [2.4.1] 24 | 25 | (skipped) 26 | 27 | ## [2.4.0] 28 | 29 | - Added support for TOTP (Time-based One-Time Password) codes 30 | - Refactor the code base significantly 31 | 32 | ## [2.3.2] 33 | 34 | - Switch to keepass-ng dependency 35 | 36 | ## [2.3.1] 37 | 38 | - Fix to show a proper error message when entering incorrect master password 39 | - Fix to initial creation of the Keepass file 40 | 41 | ## [2.3.0] 42 | 43 | - Switch to Keepass storage format 44 | - Remove online vault 45 | 46 | ## [2.2.2] 47 | 48 | - Fix login 49 | 50 | ## [2.2.1] 51 | 52 | - Fix to allow multiline notes 53 | - Export of vault contents (credentials, secure notes, payment cards) 54 | 55 | ## [2.2.0] 56 | 57 | - Added secure notes 58 | 59 | ## [2.1.1] 60 | 61 | - Fixed to allow null values in the user account first name and last name. [#4](https://github.com/anssip/passlane/issues/4) 62 | 63 | ## [2.1.0] 64 | 65 | - Added possibility to manage payment cards. 66 | 67 | ## [2.0.0] 68 | 69 | - Introduced encryption keys. 70 | - Added the possibility to keep the vault open (with `passlane unlock`) so that the master password is not prompted with every password query. 71 | - Encryption keys are kept on client device, only the end user can decrypt and access sensitive password info. 72 | 73 | ## [1.0.1] 74 | 75 | - Add ability to update the master password in the online vault. Changing the master password updates every credential with newly encrypted passwords. 76 | 77 | ## [1.0.0] 78 | 79 | - Online vault at https://passlanevault.com 80 | - Switch to use commands instead of options in the command line 81 | - Generate & save at the same time using `passlane add -g` 82 | - Delete should not ask master password 83 | - `migrate` command to migrate from old format without iv 84 | 85 | ## [0.1.4] 86 | 87 | - New feature: Show results in table when querying for passwords using `--gerp` 88 | - New feature: Add possibility to delete passwords using `--delete` 89 | - Fixed: "Failed: Unable to retrieve value from clipboard" --> prompt for the password to be saved 90 | 91 | ## [0.1.3] 92 | 93 | - Add ability to save passwords entered by the user - not just saving of the previously genereted one from clipboard. 94 | - Added `--verbose` option to show passwords when grepping with the `--g` option. 95 | - Passwords prompt input no longer shows the entered passwords. 96 | 97 | # [0.1.0] 98 | 99 | - Initial release 100 | -------------------------------------------------------------------------------- /src/actions/add.rs: -------------------------------------------------------------------------------- 1 | use crate::actions::{copy_to_clipboard, unlock, unlock_totp_vault, Action, ItemType}; 2 | use crate::vault::entities::Error; 3 | use crate::vault::vault_trait::Vault; 4 | use crate::{crypto, ui}; 5 | use clap::ArgMatches; 6 | use clipboard::{ClipboardContext, ClipboardProvider}; 7 | 8 | pub struct AddAction { 9 | pub generate: bool, 10 | pub clipboard: bool, 11 | pub item_type: ItemType, 12 | pub is_totp: bool, 13 | } 14 | 15 | impl AddAction { 16 | pub fn new(matches: &ArgMatches) -> AddAction { 17 | AddAction { 18 | generate: matches.get_one::("generate").map_or(false, |v| *v), 19 | clipboard: matches.get_one::("clipboard").map_or(false, |v| *v), 20 | item_type: ItemType::new_from_args(matches), 21 | is_totp: matches.get_one::("otp").map_or(false, |v| *v), 22 | } 23 | } 24 | fn password_from_clipboard(&self) -> Result { 25 | let mut ctx: ClipboardContext = ClipboardProvider::new().unwrap(); 26 | let value = ctx 27 | .get_contents() 28 | .expect("Unable to retrieve value from clipboard"); 29 | if !crypto::validate_password(&value) { 30 | Error::new("The text in clipboard is not a valid password"); 31 | } 32 | Ok(value) 33 | } 34 | fn get_password(&self) -> Result { 35 | if self.generate { 36 | Ok(crypto::generate()) 37 | } else if self.clipboard { 38 | self.password_from_clipboard() 39 | } else { 40 | Ok(ui::input::ask_password("Enter password to save", None)) 41 | } 42 | } 43 | fn get_vault(&self) -> Result, Error> { 44 | if self.is_totp { 45 | unlock_totp_vault() 46 | } else { 47 | unlock() 48 | } 49 | } 50 | fn add_credential(&self) -> Result { 51 | let password = self.get_password()?; 52 | 53 | let creds = ui::input::ask_credentials(&password); 54 | let mut vault = self.get_vault()?; 55 | vault.save_one_credential(creds.clone())?; 56 | copy_to_clipboard(&password); 57 | Ok("Password copied to clipboard".to_string()) 58 | } 59 | fn add_payment(&self) -> Result { 60 | let payment = ui::input::ask_payment_info(); 61 | println!("Saving..."); 62 | let mut vault = self.get_vault()?; 63 | vault.save_payment(payment)?; 64 | Ok("Payment saved.".to_string()) 65 | } 66 | fn add_note(&self) -> anyhow::Result { 67 | let note = ui::input::ask_note_info(); 68 | println!("Saving..."); 69 | let mut vault = self.get_vault()?; 70 | vault.save_note(¬e)?; 71 | Ok("Note saved.".to_string()) 72 | } 73 | fn add_totp(&self) -> Result { 74 | let totp = ui::input::ask_totp_info(); 75 | println!("Saving..."); 76 | let mut vault = self.get_vault()?; 77 | vault.save_totp(&totp)?; 78 | Ok("TOTP saved.".to_string()) 79 | } 80 | 81 | fn add(&self) -> Result { 82 | match self.item_type { 83 | ItemType::Credential => self.add_credential(), 84 | ItemType::Payment => self.add_payment(), 85 | ItemType::Note => self.add_note(), 86 | ItemType::Totp => self.add_totp(), 87 | } 88 | } 89 | } 90 | 91 | impl Action for AddAction { 92 | fn run(&self) -> Result { 93 | self.add() 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /TODO.md: -------------------------------------------------------------------------------- 1 | # TODO 2 | 3 | ## Roadmap 4 | 5 | ### Next 6 | 7 | - [ ] Make it possible to sign up to a mailing list to be notified of updates 8 | - [ ] Add note field to credentials (userful when you have several accounts on the same service) 9 | - [ ] Improve readme 10 | - [ ] try icloud db storage 11 | - [ ] Show first 4 in payment card list 12 | - [x] Make sure first usage asks for configuration values to be stored in the config file 13 | - [x] Show service field with only 30 first characters 14 | - [x] Sanitize all input to be stored (to remove all characters not allowed in Keepass XML) 15 | - [x] Show dates for each entry 16 | - [x] Editing of entries 17 | - [ ] Add an option to pass master password from the command line 18 | - [ ] Option to output JSON, for scripting 19 | - [ ] remove anyhow? 20 | - [x] add TOTP support 21 | - [x] first time vault creation 22 | - [x] invalid password error message 23 | - [x] OTP support 24 | 25 | ### Scription examples 26 | 27 | With JSON output, following could be done. 28 | 29 | NOT: make sure you have unlocked the vault before running these commands. Alternatively, you can use the `---master-pwd` flag to provide the password. 30 | 31 | 1. Integrate with other security tools: 32 | 33 | ```bash 34 | # Get password and pipe it to a security analysis tool 35 | passlane show alma --json | jq -r '.credentials[0].password' | password-strength-checker 36 | 37 | # Bulk check all passwords 38 | passlane list --json | jq -r '.credentials[].password' | password-strength-checker --bulk 39 | ``` 40 | 41 | 2. Automated password rotation: 42 | 43 | ```bash 44 | # Script to rotate passwords for all services 45 | passlane list --json | jq -r '.credentials[] | .service + " " + .username' | while read service username; do 46 | new_password=$(generate-strong-password) 47 | update-service-password "$service" "$username" "$new_password" 48 | passlane update "$service" --username "$username" --password "$new_password" 49 | done 50 | ``` 51 | 52 | 3. Export to other password managers: 53 | 54 | ```bash 55 | # Convert to 1Password format 56 | passlane list --json | jq ' 57 | .credentials[] | { 58 | title: .service, 59 | username: .username, 60 | password: .password, 61 | type: "login" 62 | } 63 | ' > 1password_import.json 64 | ``` 65 | 66 | 4. Create custom reports: 67 | 68 | ```bash 69 | # Find services using the same password 70 | passlane list --json | jq -r ' 71 | .credentials | group_by(.password) | 72 | map(select(length > 1) | map(.service)) | 73 | .[] | @csv 74 | ' | column -t -s, -n 75 | ``` 76 | 77 | 5. Automate login processes: 78 | 79 | ```bash 80 | # Use with Selenium for automated testing 81 | SERVICE="https://example.com" 82 | CREDS=$(passlane show "$SERVICE" --json) 83 | USERNAME=$(echo "$CREDS" | jq -r '.credentials[0].username') 84 | PASSWORD=$(echo "$CREDS" | jq -r '.credentials[0].password') 85 | 86 | python < /tmp/passwords.json 122 | python -m http.server 8000 & 123 | curl http://localhost:8000/passwords.json | jq '.credentials[] | select(.service == "example.com")' 124 | ``` 125 | -------------------------------------------------------------------------------- /src/actions/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod add; 2 | pub mod delete; 3 | pub mod edit; 4 | pub mod export; 5 | pub mod generate; 6 | pub mod help; 7 | pub mod import; 8 | pub mod init; 9 | pub mod lock; 10 | pub mod show; 11 | pub mod unlock; 12 | 13 | use crate::keychain; 14 | use crate::store; 15 | 16 | use crate::ui::input::{ask_master_password, ask_totp_master_password}; 17 | use crate::vault::entities::Error; 18 | use crate::vault::keepass_vault::KeepassVault; 19 | use crate::vault::vault_trait::Vault; 20 | use clap::ArgMatches; 21 | use clipboard::ClipboardContext; 22 | use clipboard::ClipboardProvider; 23 | 24 | pub(crate) trait MatchHandlerTemplate 25 | where 26 | Self::ItemType: Clone, 27 | { 28 | type ItemType; 29 | 30 | fn pre_handle_matches(&self, matches: &Vec); 31 | fn handle_one_match(&mut self, the_match: Self::ItemType) -> Result, Error>; 32 | fn handle_many_matches( 33 | &mut self, 34 | matches: Vec, 35 | ) -> Result, Error>; 36 | } 37 | 38 | pub(crate) fn handle_matches( 39 | matches: Vec, 40 | handler: &mut Box, 41 | ) -> Result, Error> 42 | where 43 | H: MatchHandlerTemplate, 44 | H::ItemType: Clone, 45 | { 46 | if matches.is_empty() { 47 | Ok(Some("No matches found".to_string())) 48 | } else { 49 | handler.pre_handle_matches(&matches.clone()); 50 | 51 | if matches.len() == 1 { 52 | handler.handle_one_match(matches[0].clone()) 53 | } else { 54 | handler.handle_many_matches(matches) 55 | } 56 | } 57 | } 58 | 59 | pub trait Action { 60 | fn run(&self) -> Result { 61 | Ok("Success".to_string()) 62 | } 63 | } 64 | 65 | fn get_vault_properties() -> (String, String, Option) { 66 | let stored_password = keychain::get_master_password(); 67 | let master_pwd = stored_password.unwrap_or_else(|_| ask_master_password(None)); 68 | let filepath = store::get_vault_path(); 69 | let keyfile_path = store::get_keyfile_path(); 70 | (master_pwd, filepath, keyfile_path) 71 | } 72 | 73 | fn unlock() -> Result, Error> { 74 | let (master_pwd, filepath, keyfile_path) = get_vault_properties(); 75 | println!("Unlocking vault..."); 76 | get_vault(&master_pwd, &filepath, keyfile_path) 77 | } 78 | 79 | fn unlock_totp_vault() -> Result, Error> { 80 | let stored_password = keychain::get_totp_master_password(); 81 | let master_pwd = stored_password.unwrap_or_else(|_| ask_totp_master_password()); 82 | let filepath = store::get_totp_vault_path(); 83 | let keyfile_path = store::get_totp_keyfile_path(); 84 | println!("Unlocking TOTP vault..."); 85 | get_vault(&master_pwd, &filepath, keyfile_path) 86 | } 87 | 88 | fn get_vault( 89 | password: &str, 90 | filepath: &str, 91 | keyfile_path: Option, 92 | ) -> Result, Error> { 93 | // we could return some other Vault implementation here 94 | let vault = KeepassVault::open(password, filepath, keyfile_path)?; 95 | Ok(Box::new(vault)) 96 | } 97 | 98 | pub fn copy_to_clipboard(value: &str) { 99 | let mut ctx: ClipboardContext = ClipboardProvider::new().unwrap(); 100 | ctx.set_contents(String::from(value)).unwrap(); 101 | } 102 | 103 | pub trait UnlockingAction { 104 | fn execute(&self) -> Result, Error> { 105 | if self.is_totp_vault() { 106 | self.run_with_vault(&mut unlock_totp_vault()?) 107 | } else { 108 | self.run_with_vault(&mut unlock()?) 109 | } 110 | } 111 | 112 | fn is_totp_vault(&self) -> bool { 113 | false 114 | } 115 | 116 | fn run_with_vault(&self, _: &mut Box) -> Result, Error> { 117 | Ok(Some("Success".to_string())) 118 | } 119 | } 120 | 121 | #[derive(PartialEq)] 122 | pub enum ItemType { 123 | Credential, 124 | Payment, 125 | Note, 126 | Totp, 127 | } 128 | 129 | impl ItemType { 130 | pub fn new_from_args(matches: &ArgMatches) -> ItemType { 131 | if matches.get_one::("payments").map_or(false, |v| *v) { 132 | ItemType::Payment 133 | } else if matches.get_one("notes").map_or(false, |v| *v) { 134 | ItemType::Note 135 | } else if matches.get_one("otp").map_or(false, |v| *v) { 136 | ItemType::Totp 137 | } else { 138 | ItemType::Credential 139 | } 140 | } 141 | } 142 | -------------------------------------------------------------------------------- /src/actions/init.rs: -------------------------------------------------------------------------------- 1 | use crate::actions::Action; 2 | use crate::keychain; 3 | use crate::store; 4 | use crate::ui::input::{ 5 | ask_existing_path, ask_keyfile_path, ask_new_master_password, ask_open_existing_totp_vault, 6 | ask_open_existing_vault, ask_store_master_password, ask_totp_vault_path, ask_vault_path, 7 | newline, 8 | }; 9 | use crate::vault::entities::Error; 10 | use crate::vault::keepass_vault::KeepassVault; 11 | 12 | pub struct InitAction {} 13 | 14 | impl Action for InitAction { 15 | fn run(&self) -> Result { 16 | // TODO: Show welcome message with ASCII art 17 | 18 | let (vault_location, is_new_vault) = self.initialize_vault()?; 19 | newline(); 20 | 21 | self.initialize_totp_vault()?; 22 | newline(); 23 | 24 | let keyfile_location = self.init_keyfile()?; 25 | newline(); 26 | 27 | let master_pwd = self.initialize_master_password()?; 28 | 29 | if is_new_vault { 30 | println!("Initializing new vault..."); 31 | self.create_keepass_vault(&vault_location, &master_pwd, keyfile_location.as_deref())?; 32 | } 33 | 34 | Ok(String::from("Initialized")) 35 | } 36 | } 37 | 38 | impl InitAction { 39 | fn initialize_vault(&self) -> Result<(String, bool), Error> { 40 | if store::has_vault_path() { 41 | println!("Vault already configured"); 42 | return Ok((store::get_vault_path(), false)); 43 | } 44 | 45 | let (location, is_new_vault) = if ask_open_existing_vault() { 46 | ( 47 | self.get_and_save_vault_location(ask_existing_path, "Vault")?, 48 | false, 49 | ) 50 | } else { 51 | ( 52 | self.get_and_save_vault_location( 53 | || ask_vault_path(&store::get_vault_path()), 54 | "Vault", 55 | )?, 56 | true, 57 | ) 58 | }; 59 | Ok((location, is_new_vault)) 60 | } 61 | 62 | fn initialize_totp_vault(&self) -> Result { 63 | if store::has_totp_vault_path() { 64 | println!("TOTP Vault already configured"); 65 | return Ok(store::get_totp_vault_path()); 66 | } 67 | 68 | let location = if ask_open_existing_totp_vault() { 69 | self.get_and_save_vault_location(ask_existing_path, "TOTP Vault")? 70 | } else { 71 | self.get_and_save_vault_location( 72 | || ask_totp_vault_path(&store::get_totp_vault_path()), 73 | "TOTP Vault", 74 | )? 75 | }; 76 | 77 | Ok(location) 78 | } 79 | 80 | fn get_and_save_vault_location( 81 | &self, 82 | ask_location: F, 83 | vault_type: &str, 84 | ) -> Result 85 | where 86 | F: Fn() -> String, 87 | { 88 | let location = ask_location(); 89 | println!("{} location {}", vault_type, location); 90 | match vault_type { 91 | "Vault" => store::save_vault_path(&location)?, 92 | "TOTP Vault" => store::save_totp_vault_path(&location)?, 93 | _ => { 94 | return Err(Error { 95 | message: format!("Unknown vault type: {}", vault_type), 96 | }) 97 | } 98 | } 99 | Ok(location) 100 | } 101 | 102 | fn init_keyfile(&self) -> Result, Error> { 103 | if store::has_keyfile_path() { 104 | println!("Keyfile already configured"); 105 | return Ok(store::get_keyfile_path()); 106 | } 107 | let keyfile_location = ask_keyfile_path(store::get_keyfile_path().as_deref()); 108 | if let Some(keyfile) = &keyfile_location { 109 | if keyfile != "" { 110 | store::save_keyfile_path(keyfile)?; 111 | } 112 | } 113 | Ok(keyfile_location) 114 | } 115 | 116 | fn initialize_master_password(&self) -> Result { 117 | println!("Initializing master password... checking if already stored in keychain"); 118 | let master_pwd = keychain::get_master_password(); 119 | match master_pwd { 120 | Ok(pwd) => { 121 | println!("Master password already configured"); 122 | Ok(pwd) 123 | } 124 | Err(_) => { 125 | println!("Initializing a new master password"); 126 | let master_pwd = ask_new_master_password(); 127 | if ask_store_master_password() { 128 | keychain::save_master_password(&master_pwd)?; 129 | } 130 | Ok(master_pwd) 131 | } 132 | } 133 | } 134 | 135 | fn create_keepass_vault( 136 | &self, 137 | vault_location: &str, 138 | master_pwd: &str, 139 | keyfile: Option<&str>, 140 | ) -> Result<(), Error> { 141 | KeepassVault::new(vault_location, master_pwd, keyfile)?; 142 | Ok(()) 143 | } 144 | } 145 | -------------------------------------------------------------------------------- /src/store.rs: -------------------------------------------------------------------------------- 1 | use crate::vault::entities::{Credential, Error, Note, PaymentCard}; 2 | use csv::{ReaderBuilder, Writer}; 3 | use serde::Serialize; 4 | use std::fs::create_dir; 5 | use std::fs::OpenOptions; 6 | use std::io::prelude::*; 7 | use std::path::Path; 8 | use std::path::PathBuf; 9 | 10 | impl From for Error { 11 | fn from(e: csv::Error) -> Self { 12 | Error { 13 | message: e.to_string(), 14 | } 15 | } 16 | } 17 | 18 | impl From for Error { 19 | fn from(e: serde_json::Error) -> Self { 20 | Error { 21 | message: e.to_string(), 22 | } 23 | } 24 | } 25 | 26 | #[derive(Debug, Serialize, Clone)] 27 | pub struct CSVPaymentCard { 28 | pub name: String, 29 | pub name_on_card: String, 30 | pub number: String, 31 | pub cvv: String, 32 | pub expiry: String, 33 | pub color: String, 34 | pub billing_address: String, 35 | } 36 | 37 | #[derive(Debug, Serialize, Clone)] 38 | pub struct CSVSecureNote { 39 | pub title: String, 40 | pub note: String, 41 | } 42 | 43 | fn home_dir() -> PathBuf { 44 | dirs::home_dir().unwrap_or_else(|| PathBuf::from("~")) 45 | } 46 | 47 | fn dir_path() -> PathBuf { 48 | let dir_path = home_dir().join(".passlane"); 49 | let exists = Path::new(&dir_path).exists(); 50 | if !exists { 51 | create_dir(&dir_path).expect("Unable to create .passlane dir"); 52 | } 53 | dir_path 54 | } 55 | 56 | pub fn read_from_csv(file_path: &str) -> anyhow::Result> { 57 | let path = PathBuf::from(file_path); 58 | let in_file = OpenOptions::new().read(true).open(path)?; 59 | let mut reader = ReaderBuilder::new().has_headers(true).from_reader(in_file); 60 | let credentials = &mut Vec::new(); 61 | for result in reader.deserialize() { 62 | credentials.push(result?); 63 | } 64 | Ok(credentials.clone()) 65 | } 66 | 67 | fn read_from_file(path: &PathBuf) -> Option { 68 | let mut file = OpenOptions::new() 69 | .read(true) 70 | .write(false) 71 | .create_new(false) 72 | .open(&path) 73 | .unwrap(); 74 | 75 | let mut file_content = String::new(); 76 | file.read_to_string(&mut file_content) 77 | .expect("Unable to read master password file"); 78 | Some(file_content.trim().parse().unwrap()) 79 | } 80 | 81 | fn resolve_keyfile_path(path_config_file: &str) -> Option { 82 | let path = dir_path().join(path_config_file); 83 | if !path.exists() { 84 | None 85 | } else { 86 | read_from_file(&path) 87 | } 88 | } 89 | 90 | pub fn get_keyfile_path() -> Option { 91 | resolve_keyfile_path(".keyfile_path") 92 | } 93 | 94 | pub(crate) fn get_totp_keyfile_path() -> Option { 95 | resolve_keyfile_path(".totp_keyfile_path") 96 | } 97 | 98 | fn resolve_vault_path(default_filename: &str, path_config_filename: &str) -> String { 99 | let default_path = dir_path() 100 | .join(default_filename) 101 | .to_str() 102 | .unwrap() 103 | .to_string(); 104 | let path = dir_path().join(path_config_filename); 105 | if path.exists() { 106 | return read_from_file(&path) 107 | .unwrap_or(default_path) 108 | .trim() 109 | .to_string(); 110 | } 111 | default_path 112 | } 113 | 114 | fn config_file_exists(path_config_filename: &str) -> bool { 115 | dir_path().join(path_config_filename).exists() 116 | } 117 | 118 | pub(crate) fn get_vault_path() -> String { 119 | resolve_vault_path("store.kdbx", ".vault_path") 120 | } 121 | 122 | pub(crate) fn get_totp_vault_path() -> String { 123 | resolve_vault_path("totp.kdbx", ".totp_vault_path") 124 | } 125 | 126 | pub(crate) fn write_credentials_to_csv( 127 | file_path: &str, 128 | creds: &Vec, 129 | ) -> Result { 130 | let mut wtr = Writer::from_path(file_path)?; 131 | for cred in creds { 132 | wtr.serialize(cred)?; 133 | } 134 | wtr.flush()?; 135 | Ok(creds.len() as i64) 136 | } 137 | 138 | pub(crate) fn write_payment_cards_to_csv( 139 | file_path: &str, 140 | cards: &Vec, 141 | ) -> Result { 142 | let mut wtr = Writer::from_path(file_path)?; 143 | for card in cards { 144 | wtr.serialize(CSVPaymentCard { 145 | name: String::from(card.name()), 146 | name_on_card: String::from(card.name_on_card()), 147 | number: String::from(card.number()), 148 | cvv: String::from(card.cvv()), 149 | expiry: format!("{}", card.expiry()), 150 | color: match card.color() { 151 | Some(color) => String::from(color), 152 | None => String::from(""), 153 | }, 154 | billing_address: match card.billing_address() { 155 | Some(address) => format!("{}", address), 156 | None => String::from(""), 157 | }, 158 | })?; 159 | } 160 | wtr.flush()?; 161 | Ok(cards.len() as i64) 162 | } 163 | 164 | pub(crate) fn write_secure_notes_to_csv(file_path: &str, notes: &Vec) -> Result { 165 | let mut wtr = Writer::from_path(file_path)?; 166 | for note in notes { 167 | wtr.serialize(CSVSecureNote { 168 | title: note.title().to_string(), 169 | note: note.content().to_string(), 170 | })?; 171 | } 172 | wtr.flush()?; 173 | Ok(notes.len() as i64) 174 | } 175 | 176 | pub fn save_config_path(config_file: &str, path: &str) -> Result<(), Error> { 177 | let config_path = dir_path().join(config_file); 178 | let exists = config_path.exists(); 179 | let mut file = OpenOptions::new() 180 | .create(!exists) 181 | .write(true) 182 | .truncate(true) 183 | .open(config_path)?; 184 | file.write_all(String::from(path).as_bytes())?; 185 | Ok(()) 186 | } 187 | 188 | pub(crate) fn save_vault_path(path: &str) -> Result<(), Error> { 189 | save_config_path(".vault_path", path) 190 | } 191 | 192 | pub(crate) fn save_totp_vault_path(path: &str) -> Result<(), Error> { 193 | save_config_path(".totp_vault_path", path) 194 | } 195 | 196 | pub(crate) fn save_keyfile_path(path: &str) -> Result<(), Error> { 197 | save_config_path(".keyfile_path", path) 198 | } 199 | 200 | pub fn has_vault_path() -> bool { 201 | config_file_exists(".vault_path") 202 | } 203 | 204 | pub fn has_totp_vault_path() -> bool { 205 | config_file_exists(".totp_vault_path") 206 | } 207 | 208 | pub fn has_keyfile_path() -> bool { 209 | config_file_exists(".keyfile_path") 210 | } 211 | -------------------------------------------------------------------------------- /src/ui/output.rs: -------------------------------------------------------------------------------- 1 | use comfy_table::*; 2 | use std::cmp::min; 3 | 4 | use crate::vault::entities::{Credential, Note, PaymentCard, Totp}; 5 | 6 | pub fn show_credentials_table(credentials: &[Credential], show_password: bool) { 7 | let mut table = Table::new(); 8 | let header_cell = |label: String| -> Cell { Cell::new(label).fg(Color::Green) }; 9 | let headers = if show_password { 10 | vec!["", "Service", "Username/email", "Password", "Modified"] 11 | } else { 12 | vec!["", "Service", "Username/email", "Modified"] 13 | }; 14 | table.set_header( 15 | headers 16 | .iter() 17 | .map(|&h| header_cell(String::from(h))) 18 | .collect::>(), 19 | ); 20 | for (index, creds) in (0_i16..).zip(credentials.iter()) { 21 | let service = creds.service().to_string(); 22 | let columns = if show_password { 23 | vec![ 24 | Cell::new(index.to_string()).fg(Color::Yellow), 25 | Cell::new(service[..min(service.len(), 30)].to_string()), 26 | Cell::new(String::from(creds.username())), 27 | Cell::new(String::from(creds.password())), 28 | Cell::new(creds.last_modified().format("%d.%m.%Y %H:%M").to_string()), 29 | ] 30 | } else { 31 | vec![ 32 | Cell::new(index.to_string()).fg(Color::Yellow), 33 | Cell::new(service[..min(service.len(), 30)].to_string()), 34 | Cell::new(String::from(creds.username())), 35 | Cell::new(creds.last_modified().format("%d.%m.%Y %H:%M").to_string()), 36 | ] 37 | }; 38 | table.add_row(columns); 39 | } 40 | println!("{table}"); 41 | } 42 | 43 | fn header_cell(label: String) -> Cell { 44 | Cell::new(label).fg(Color::Green) 45 | } 46 | 47 | pub fn show_payment_cards_table(cards: &Vec, show_cleartext: bool) { 48 | let mut table = Table::new(); 49 | let headers = if show_cleartext { 50 | vec![ 51 | "", 52 | "Name", 53 | "Color", 54 | "Number", 55 | "Expiry", 56 | "CVV", 57 | "Name on card", 58 | "Modified", 59 | ] 60 | } else { 61 | vec!["", "Name", "Color", "Expiry", "Modified"] 62 | }; 63 | table.set_header( 64 | headers 65 | .iter() 66 | .map(|&h| header_cell(String::from(h))) 67 | .collect::>(), 68 | ); 69 | for (index, card) in (0_i16..).zip(cards.iter()) { 70 | let columns = if show_cleartext { 71 | vec![ 72 | Cell::new(index.to_string()).fg(Color::Yellow), 73 | Cell::new(String::from(card.name())), 74 | Cell::new(String::from(if let Some(color) = card.color() { 75 | &color 76 | } else { 77 | "" 78 | })), 79 | Cell::new(String::from(card.number())), 80 | Cell::new(String::from(format!("{}", card.expiry()))), 81 | Cell::new(String::from(card.cvv())), 82 | Cell::new(String::from(card.name_on_card())), 83 | Cell::new(card.last_modified().format("%d.%m.%Y %H:%M").to_string()), 84 | ] 85 | } else { 86 | vec![ 87 | Cell::new(index.to_string()).fg(Color::Yellow), 88 | Cell::new(String::from(card.name())), 89 | Cell::new(card.color_str()), 90 | Cell::new(card.expiry_str()), 91 | Cell::new(card.last_modified().format("%d.%m.%Y %H:%M").to_string()), 92 | ] 93 | }; 94 | table.add_row(columns); 95 | } 96 | println!("{table}"); 97 | } 98 | 99 | pub fn show_card(card: &PaymentCard) { 100 | let mut table = Table::new(); 101 | let mut add_row = |label: &str, value: &str, color: Option| { 102 | table.add_row(vec![ 103 | Cell::new(label).fg(if let Some(col) = color { 104 | col 105 | } else { 106 | Color::Yellow 107 | }), 108 | Cell::new(value), 109 | ]); 110 | }; 111 | add_row("Name", card.name(), None); 112 | add_row("Color", &card.color_str(), None); 113 | add_row("Number", card.number(), None); 114 | add_row("Expiry", &card.expiry_str(), None); 115 | add_row("CVV", card.cvv(), None); 116 | add_row("Name on card", card.name_on_card(), None); 117 | if let Some(address) = card.billing_address() { 118 | add_row("Billing address", "", Some(comfy_table::Color::Cyan)); 119 | add_row("Street", address.street(), Some(comfy_table::Color::Cyan)); 120 | add_row("Zip", address.zip(), Some(comfy_table::Color::Cyan)); 121 | add_row("City", address.city(), Some(comfy_table::Color::Cyan)); 122 | if let Some(state) = address.state() { 123 | add_row("State", &state, Some(comfy_table::Color::Cyan)); 124 | } 125 | add_row("Country", address.country(), Some(comfy_table::Color::Cyan)); 126 | } 127 | println!("{table}"); 128 | } 129 | 130 | pub(crate) fn show_notes_table(notes: &[Note], show_cleartext: bool) { 131 | let mut table = Table::new(); 132 | let headers = if show_cleartext { 133 | vec!["", "Title", "Note", "Modified"] 134 | } else { 135 | vec!["", "Title", "Modified"] 136 | }; 137 | table.set_header( 138 | headers 139 | .iter() 140 | .map(|&h| header_cell(String::from(h))) 141 | .collect::>(), 142 | ); 143 | for (index, note) in notes.iter().enumerate() { 144 | let columns = if show_cleartext { 145 | vec![ 146 | Cell::new(index.to_string()).fg(Color::Yellow), 147 | Cell::new(note.title()), 148 | Cell::new(note.content()), 149 | Cell::new(¬e.last_modified().format("%Y-%m-%d %H:%M:%S").to_string()), 150 | ] 151 | } else { 152 | vec![ 153 | Cell::new(index.to_string()).fg(Color::Yellow), 154 | Cell::new(¬e.title()), 155 | Cell::new(¬e.last_modified().format("%Y-%m-%d %H:%M:%S").to_string()), 156 | ] 157 | }; 158 | table.add_row(columns); 159 | } 160 | println!("{table}"); 161 | } 162 | 163 | pub(crate) fn show_note(note: &Note) { 164 | println!("---------------------------"); 165 | println!("{}\n", note.title()); 166 | println!("{}", note.content()); 167 | println!("---------------------------"); 168 | } 169 | 170 | pub(crate) fn show_totp_table(totps: &[Totp]) { 171 | let mut table = Table::new(); 172 | table.set_header( 173 | vec![ 174 | header_cell("".to_string()), 175 | header_cell("Label".to_string()), 176 | header_cell("Issuer".to_string()), 177 | header_cell("Modified".to_string()), 178 | ] 179 | .into_iter() 180 | .collect::>(), 181 | ); 182 | for (index, totp) in totps.iter().enumerate() { 183 | table.add_row(vec![ 184 | Cell::new(index.to_string()).fg(Color::Yellow), 185 | Cell::new(totp.label().to_string()), 186 | Cell::new(totp.issuer().to_string()), 187 | Cell::new(totp.last_modified().format("%d.%m.%Y %H:%M").to_string()), 188 | ]); 189 | } 190 | println!("{table}"); 191 | } 192 | -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | extern crate clipboard; 2 | extern crate magic_crypt; 3 | 4 | mod actions; 5 | mod crypto; 6 | mod keychain; 7 | mod store; 8 | mod ui; 9 | mod vault; 10 | 11 | use crate::actions::add::AddAction; 12 | use crate::actions::delete::DeleteAction; 13 | use crate::actions::edit::EditAction; 14 | use crate::actions::export::ExportAction; 15 | use crate::actions::generate::GeneratePasswordAction; 16 | use crate::actions::help::PrintHelpAction; 17 | use crate::actions::import::ImportCsvAction; 18 | use crate::actions::lock::LockAction; 19 | use crate::actions::show::ShowAction; 20 | use crate::actions::unlock::UnlockAction; 21 | use actions::*; 22 | use clap::{arg, ArgAction, Command}; 23 | use init::InitAction; 24 | use std::env; 25 | 26 | fn cli() -> Command { 27 | Command::new("passlane") 28 | .about("A password manager using Keepass as the storage backend.") 29 | .subcommand_required(false) 30 | .arg_required_else_help(false) 31 | .allow_external_subcommands(true) 32 | .subcommand( 33 | Command::new("init") 34 | .about("Initialize passlane. Walks you through the configuration process.") 35 | ) 36 | .subcommand( 37 | Command::new("add") 38 | .about("Adds an item to the vault. Without arguments adds a new credential, use -p to add a payment card and -n to add a secure note.") 39 | .arg(arg!( 40 | -p --payments "Add a payment card." 41 | ).action(ArgAction::SetTrue)) 42 | .arg(arg!( 43 | -n --notes "Add a secure note." 44 | ).action(ArgAction::SetTrue)) 45 | .arg(arg!( 46 | -o --otp "Add a One Time Password authorizer." 47 | ).action(ArgAction::SetTrue)) 48 | .arg(arg!( 49 | -g --generate "Generate the password to be saved." 50 | ).action(ArgAction::SetTrue)) 51 | .arg(arg!( 52 | -l --clipboard "Get the password to save from the clipboard." 53 | ).action(ArgAction::SetTrue)) 54 | ) 55 | .subcommand( 56 | Command::new("edit") 57 | .about("Edit an entry.") 58 | .arg(arg!(-c --credentials "Edit credentials.").action(ArgAction::SetTrue).requires("search")) 59 | .arg(arg!(-p --payments "Edit payment cards.").action(ArgAction::SetTrue)) 60 | .arg(arg!(-n --notes "Edit secure notes.").action(ArgAction::SetTrue)) 61 | .arg(arg!(-o --otp "Edit One Time Password authorizer.").action(ArgAction::SetTrue)) 62 | .arg(arg!( "The regular expression used to search services whose credentials to edit.").group("search").required(false)) 63 | .arg_required_else_help(true) 64 | ) 65 | .subcommand( 66 | Command::new("csv") 67 | .about("Imports credentials from a CSV file.") 68 | .arg(arg!( "The the CSV file to import.")) 69 | ) 70 | .subcommand( 71 | Command::new("delete") 72 | .about("Deletes one or more entries.") 73 | .arg(arg!( 74 | -c --credentials "Delete credentials." 75 | ).action(ArgAction::SetTrue).requires("search")) 76 | .arg(arg!( 77 | -p --payments "Delete payment cards." 78 | ).action(ArgAction::SetTrue)) 79 | .arg(arg!( 80 | -n --notes "Delete secure notes." 81 | ).action(ArgAction::SetTrue)) 82 | .arg(arg!( 83 | -o --otp "Delete One Time Password authorizer." 84 | ).action(ArgAction::SetTrue)) 85 | .arg(arg!( "The regular expression used to search services whose credentials to delete.").group("search").required(false)) 86 | .arg_required_else_help(true) 87 | ) 88 | .subcommand( 89 | Command::new("show") 90 | .about("Shows one or more entries.") 91 | .arg(arg!( 92 | -v --verbose "Verbosely display matches table in clear text." 93 | ).action(ArgAction::SetTrue)) 94 | .arg(arg!( 95 | -p --payments "Shows payment cards." 96 | ).action(ArgAction::SetTrue)) 97 | .arg(arg!( 98 | -o --otp "Shows one time passwords (OTPs)" 99 | ).action(ArgAction::SetTrue)) 100 | .arg(arg!( 101 | -n --notes "Shows secure notes." 102 | ).action(ArgAction::SetTrue)) 103 | .arg(arg!( 104 | -c --credentials "Shows credentials by searching with the specified regular expression." 105 | ).action(ArgAction::SetTrue).requires("search")) 106 | .arg(arg!( "Regular expression used to search services to show.").group("search").required(false)) 107 | .arg_required_else_help(true) 108 | ) 109 | .subcommand( 110 | Command::new("lock") 111 | .about("Lock the vaults to prevent all access") 112 | ) 113 | .subcommand( 114 | Command::new("unlock") 115 | .about("Opens the vaults and grants access to the entries") 116 | .arg(arg!( 117 | -o --otp "Opens the one time passwords vault" 118 | ).action(ArgAction::SetTrue)) 119 | ) 120 | .subcommand( 121 | Command::new("export") 122 | .about("Exports the vault contents to a CSV file.") 123 | .arg(arg!( 124 | -p --payments "Exporet payment cards." 125 | ).action(ArgAction::SetTrue)) 126 | .arg(arg!( 127 | -n --notes "Export secure notes." 128 | ).action(ArgAction::SetTrue)) 129 | .arg(arg!( 130 | -o --otp "Shows one time passwords (OTPs)" 131 | ).action(ArgAction::SetTrue)) 132 | .arg(arg!( "The the CSV file to export to.")) 133 | ) 134 | } 135 | 136 | fn main() { 137 | env_logger::init(); 138 | let matches = cli().get_matches(); 139 | 140 | enum VaultAction { 141 | Action(Box), 142 | UnlockingAction(Box), 143 | } 144 | 145 | let action = match matches.subcommand() { 146 | Some(("init", _)) => VaultAction::Action(Box::new(InitAction {})), 147 | Some(("add", sub_matches)) => VaultAction::Action(Box::new(AddAction::new(sub_matches))), 148 | Some(("show", sub_matches)) => { 149 | VaultAction::UnlockingAction(Box::new(ShowAction::new(sub_matches))) 150 | } 151 | Some(("delete", sub_matches)) => { 152 | VaultAction::UnlockingAction(Box::new(DeleteAction::new(sub_matches))) 153 | } 154 | Some(("csv", sub_matches)) => { 155 | VaultAction::UnlockingAction(Box::new(ImportCsvAction::new(sub_matches))) 156 | } 157 | Some(("lock", _)) => VaultAction::Action(Box::new(LockAction {})), 158 | Some(("unlock", sub_matches)) => { 159 | VaultAction::Action(Box::new(UnlockAction::new(sub_matches))) 160 | } 161 | Some(("export", sub_matches)) => { 162 | VaultAction::UnlockingAction(Box::new(ExportAction::new(sub_matches))) 163 | } 164 | Some(("edit", sub_matches)) => { 165 | VaultAction::UnlockingAction(Box::new(EditAction::new(sub_matches))) 166 | } 167 | _ => { 168 | if env::args().len() == 1 { 169 | VaultAction::Action(Box::new(GeneratePasswordAction {})) 170 | } else { 171 | VaultAction::Action(Box::new(PrintHelpAction::new(cli()))) 172 | } 173 | } 174 | }; 175 | match action { 176 | VaultAction::Action(action) => { 177 | action 178 | .run() 179 | .map(|msg| println!("{}", msg)) 180 | .unwrap_or_else(|e| { 181 | eprintln!("{}", e); 182 | std::process::exit(1); 183 | }); 184 | } 185 | VaultAction::UnlockingAction(action) => { 186 | action 187 | .execute() 188 | .map(|msg| println!("{}", msg.unwrap_or("".to_string()))) 189 | .unwrap_or_else(|e| { 190 | eprintln!("{}", e); 191 | std::process::exit(1); 192 | }); 193 | } 194 | } 195 | } 196 | -------------------------------------------------------------------------------- /src/actions/edit.rs: -------------------------------------------------------------------------------- 1 | use clap::ArgMatches; 2 | 3 | use crate::ui::output::{ 4 | show_credentials_table, show_notes_table, show_payment_cards_table, show_totp_table, 5 | }; 6 | use crate::vault::entities::{Credential, Error, Note, PaymentCard, Totp}; 7 | use crate::vault::vault_trait::Vault; 8 | use crate::{handle_matches, ui, ItemType, MatchHandlerTemplate, UnlockingAction}; 9 | 10 | struct EditCredentialsTemplate<'a> { 11 | vault: &'a mut Box, 12 | } 13 | 14 | impl<'a> EditCredentialsTemplate<'a> { 15 | fn edit_and_save_credential( 16 | &mut self, 17 | credential: &Credential, 18 | ) -> Result, Error> { 19 | let updated = ui::input::ask_modified_credential(credential); 20 | println!("Saving..."); 21 | self.vault.update_credential(updated)?; 22 | Ok(Some("Saved".to_string())) 23 | } 24 | } 25 | 26 | impl<'a> MatchHandlerTemplate for EditCredentialsTemplate<'a> { 27 | type ItemType = Credential; 28 | 29 | fn pre_handle_matches(&self, matches: &Vec) { 30 | println!("Found {} credentials...", matches.len()); 31 | } 32 | 33 | fn handle_one_match(&mut self, the_match: Self::ItemType) -> Result, Error> { 34 | self.edit_and_save_credential(&the_match) 35 | } 36 | 37 | fn handle_many_matches( 38 | &mut self, 39 | matches: Vec, 40 | ) -> Result, Error> { 41 | show_credentials_table(&matches, false); 42 | match ui::input::ask_index( 43 | "To edit, please enter a row number from the table above", 44 | matches.len() as i16 - 1, 45 | Some("Press q to exit without editing"), 46 | ) { 47 | Ok(index) => { 48 | println!( 49 | "Editing credential for service '{}'...", 50 | matches[index].service() 51 | ); 52 | self.edit_and_save_credential(&matches[index]) 53 | } 54 | Err(message) => Err(Error { message }), 55 | } 56 | } 57 | } 58 | 59 | struct EditNoteTemplate<'a> { 60 | vault: &'a mut Box, 61 | } 62 | 63 | impl<'a> EditNoteTemplate<'a> { 64 | fn edit_and_save_note(&mut self, note: &Note) -> Result, Error> { 65 | let updated = ui::input::ask_modified_note(note); 66 | println!("Saving..."); 67 | self.vault.update_note(updated)?; 68 | Ok(Some("Saved".to_string())) 69 | } 70 | } 71 | 72 | impl<'a> MatchHandlerTemplate for EditNoteTemplate<'a> { 73 | type ItemType = Note; 74 | 75 | fn pre_handle_matches(&self, matches: &Vec) { 76 | println!("Found {} payment cards", matches.len()); 77 | show_notes_table(matches, false); 78 | } 79 | 80 | fn handle_one_match(&mut self, the_match: Self::ItemType) -> Result, Error> { 81 | self.edit_and_save_note(&the_match) 82 | } 83 | 84 | fn handle_many_matches( 85 | &mut self, 86 | matches: Vec, 87 | ) -> Result, Error> { 88 | match ui::input::ask_index( 89 | "To edit, please enter a row number from the table above", 90 | matches.len() as i16 - 1, 91 | Some("Press q to exit without editing"), 92 | ) { 93 | Ok(index) => { 94 | if index == usize::MAX { 95 | // ignore 96 | Ok(None) 97 | } else { 98 | println!("Editing card with title '{}'...", matches[index].title()); 99 | self.edit_and_save_note(&matches[index]) 100 | } 101 | } 102 | Err(message) => Err(Error { message }), 103 | } 104 | } 105 | } 106 | 107 | struct EditPaymentTemplate<'a> { 108 | vault: &'a mut Box, 109 | } 110 | 111 | impl<'a> EditPaymentTemplate<'a> { 112 | fn edit_and_save(&mut self, card: &PaymentCard) -> Result, Error> { 113 | let updated = ui::input::ask_modified_payment_info(card); 114 | println!("Saving..."); 115 | self.vault.update_payment(updated)?; 116 | Ok(Some("Saved".to_string())) 117 | } 118 | } 119 | 120 | impl<'a> MatchHandlerTemplate for EditPaymentTemplate<'a> { 121 | type ItemType = PaymentCard; 122 | 123 | fn pre_handle_matches(&self, matches: &Vec) { 124 | println!("Found {} payment cards", matches.len()); 125 | show_payment_cards_table(matches, false); 126 | } 127 | 128 | fn handle_one_match(&mut self, the_match: Self::ItemType) -> Result, Error> { 129 | self.edit_and_save(&the_match) 130 | } 131 | 132 | fn handle_many_matches( 133 | &mut self, 134 | matches: Vec, 135 | ) -> Result, Error> { 136 | match ui::input::ask_index( 137 | "To edit, please enter a row number from the table above", 138 | matches.len() as i16 - 1, 139 | Some("Press q to exit without editing"), 140 | ) { 141 | Ok(index) => { 142 | if index == usize::MAX { 143 | // ignore 144 | Ok(None) 145 | } else { 146 | println!("Editing card with title '{}'...", matches[index].name()); 147 | self.edit_and_save(&matches[index]) 148 | } 149 | } 150 | Err(message) => Err(Error { message }), 151 | } 152 | } 153 | } 154 | 155 | struct EditTotpTemplate<'a> { 156 | vault: &'a mut Box, 157 | } 158 | 159 | impl<'a> EditTotpTemplate<'a> { 160 | fn edit_and_save(&mut self, totp: &Totp) -> Result, Error> { 161 | let updated = ui::input::ask_modified_totp(totp); 162 | println!("Saving..."); 163 | self.vault.update_totp(updated)?; 164 | Ok(Some("Saved".to_string())) 165 | } 166 | } 167 | 168 | impl<'a> MatchHandlerTemplate for EditTotpTemplate<'a> { 169 | type ItemType = Totp; 170 | 171 | fn pre_handle_matches(&self, matches: &Vec) { 172 | println!("Found {} TOTP entries", matches.len()); 173 | show_totp_table(matches); 174 | } 175 | 176 | fn handle_one_match(&mut self, the_match: Self::ItemType) -> Result, Error> { 177 | self.edit_and_save(&the_match) 178 | } 179 | 180 | fn handle_many_matches( 181 | &mut self, 182 | matches: Vec, 183 | ) -> Result, Error> { 184 | match ui::input::ask_index( 185 | "To edit, please enter a row number from the table above", 186 | matches.len() as i16 - 1, 187 | Some("Press q to exit without editing"), 188 | ) { 189 | Ok(index) => { 190 | if index == usize::MAX { 191 | // ignore 192 | Ok(None) 193 | } else { 194 | println!("Editing TOTP with label '{}'...", matches[index].label()); 195 | self.edit_and_save(&matches[index]) 196 | } 197 | } 198 | Err(message) => Err(Error { message }), 199 | } 200 | } 201 | } 202 | 203 | pub struct EditAction { 204 | pub grep: Option, 205 | pub item_type: ItemType, 206 | pub is_totp: bool, 207 | } 208 | 209 | impl EditAction { 210 | pub fn new(matches: &ArgMatches) -> EditAction { 211 | EditAction { 212 | grep: matches.get_one::("REGEXP").cloned(), 213 | item_type: ItemType::new_from_args(matches), 214 | is_totp: matches.get_one::("otp").map_or(false, |v| *v), 215 | } 216 | } 217 | } 218 | 219 | impl UnlockingAction for EditAction { 220 | fn is_totp_vault(&self) -> bool { 221 | self.is_totp 222 | } 223 | 224 | fn run_with_vault(&self, vault: &mut Box) -> Result, Error> { 225 | match self.item_type { 226 | ItemType::Credential => { 227 | let grep = match &self.grep { 228 | Some(grep) => grep.as_str(), 229 | None => { 230 | return Err(Error { 231 | message: "No search term provided".to_string(), 232 | }) 233 | } 234 | }; 235 | handle_matches( 236 | vault.grep(Some(grep)), 237 | &mut Box::new(EditCredentialsTemplate { vault }), 238 | ) 239 | } 240 | ItemType::Payment => handle_matches( 241 | vault.find_payments(), 242 | &mut Box::new(EditPaymentTemplate { vault }), 243 | ), 244 | ItemType::Note => handle_matches( 245 | vault.find_notes(), 246 | &mut Box::new(EditNoteTemplate { vault }), 247 | ), 248 | ItemType::Totp => handle_matches( 249 | vault.find_totp(self.grep.as_deref()), 250 | &mut Box::new(EditTotpTemplate { vault }), 251 | ), 252 | } 253 | } 254 | } 255 | -------------------------------------------------------------------------------- /src/actions/delete.rs: -------------------------------------------------------------------------------- 1 | use crate::actions::{handle_matches, ItemType, MatchHandlerTemplate, UnlockingAction}; 2 | use crate::ui; 3 | use crate::ui::output::{ 4 | show_credentials_table, show_notes_table, show_payment_cards_table, show_totp_table, 5 | }; 6 | use crate::vault::entities::{Credential, Error, Note, PaymentCard, Totp}; 7 | use crate::vault::vault_trait::Vault; 8 | use clap::ArgMatches; 9 | 10 | struct DeleteCredentialsTemplate<'a> { 11 | vault: &'a mut Box, 12 | grep: &'a str, 13 | } 14 | 15 | impl<'a> MatchHandlerTemplate for DeleteCredentialsTemplate<'a> { 16 | type ItemType = Credential; 17 | 18 | fn pre_handle_matches(&self, matches: &Vec) { 19 | println!("Found {} credentials...", matches.len()); 20 | } 21 | 22 | fn handle_one_match(&mut self, the_match: Self::ItemType) -> Result, Error> { 23 | self.vault.delete_credentials(the_match.uuid())?; 24 | Ok(Some("Deleted".to_string())) 25 | } 26 | 27 | fn handle_many_matches( 28 | &mut self, 29 | matches: Vec, 30 | ) -> Result, Error> { 31 | show_credentials_table(&matches, false); 32 | match ui::input::ask_index( 33 | "To delete, please enter a row number from the table above", 34 | matches.len() as i16 - 1, 35 | Some("Press q to exit without deleting"), 36 | ) { 37 | Ok(index) => { 38 | if index == usize::MAX { 39 | self.vault.delete_matching(self.grep)?; 40 | Ok(Some("Deleted".to_string())) 41 | } else { 42 | println!( 43 | "Deleting credential for service '{}'...", 44 | matches[index].service() 45 | ); 46 | self.vault.delete_credentials(matches[index].uuid())?; 47 | Ok(Some("Deleted".to_string())) 48 | } 49 | } 50 | Err(message) => Err(Error { message }), 51 | } 52 | } 53 | } 54 | 55 | struct DeletePaymentTemplate<'a> { 56 | vault: &'a mut Box, 57 | } 58 | 59 | impl<'a> MatchHandlerTemplate for DeletePaymentTemplate<'a> { 60 | type ItemType = PaymentCard; 61 | 62 | fn pre_handle_matches(&self, matches: &Vec) { 63 | println!("Found {} payment cards...", matches.len()); 64 | show_payment_cards_table(matches, false); 65 | } 66 | 67 | fn handle_one_match(&mut self, the_match: Self::ItemType) -> Result, Error> { 68 | let response = ui::input::ask("Do you want to delete this card? (y/n)"); 69 | if response == "y" { 70 | println!("Deleting payment card '{}'...", the_match.name()); 71 | self.vault.delete_payment(the_match.id())?; 72 | return Ok(Some("Deleted".to_string())); 73 | } 74 | Ok(None) 75 | } 76 | 77 | fn handle_many_matches( 78 | &mut self, 79 | matches: Vec, 80 | ) -> Result, Error> { 81 | match ui::input::ask_index( 82 | "To delete, please enter a row number from the table above", 83 | matches.len() as i16 - 1, 84 | Some("Press q to exit without deleting"), 85 | ) { 86 | Ok(index) => { 87 | if index == usize::MAX { 88 | Ok(None) 89 | } else { 90 | println!("Deleting payment card '{}'...", matches[index].name()); 91 | self.vault.delete_payment(&matches[index].id())?; 92 | Ok(Some("Deleted".to_string())) 93 | } 94 | } 95 | Err(message) => Err(Error { message }), 96 | } 97 | } 98 | } 99 | 100 | struct DeleteNoteTemplate<'a> { 101 | vault: &'a mut Box, 102 | } 103 | 104 | impl<'a> MatchHandlerTemplate for DeleteNoteTemplate<'a> { 105 | type ItemType = Note; 106 | 107 | fn pre_handle_matches(&self, matches: &Vec) { 108 | println!("Found {} notes", matches.len()); 109 | show_notes_table(matches, false); 110 | } 111 | 112 | fn handle_one_match(&mut self, the_match: Self::ItemType) -> Result, Error> { 113 | let response = ui::input::ask("Do you want to delete this note? (y/n)"); 114 | if response == "y" { 115 | println!("Deleting note with title '{}'...", the_match.title()); 116 | self.vault.delete_note(&the_match.id())?; 117 | return Ok(Some("Deleted".to_string())); 118 | } 119 | Ok(None) 120 | } 121 | 122 | fn handle_many_matches( 123 | &mut self, 124 | matches: Vec, 125 | ) -> Result, Error> { 126 | match ui::input::ask_index( 127 | "To delete, please enter a row number from the table above", 128 | matches.len() as i16 - 1, 129 | Some("Press q to exit without deleting"), 130 | ) { 131 | Ok(index) => { 132 | if index == usize::MAX { 133 | // ignore 134 | Ok(None) 135 | } else { 136 | println!("Deleting note with title '{}'...", matches[index].title()); 137 | self.vault.delete_note(&matches[index].id())?; 138 | Ok(Some("Deleted".to_string())) 139 | } 140 | } 141 | Err(message) => Err(Error { message }), 142 | } 143 | } 144 | } 145 | 146 | struct DeleteTotpTemplate<'a> { 147 | vault: &'a mut Box, 148 | } 149 | 150 | impl<'a> MatchHandlerTemplate for DeleteTotpTemplate<'a> { 151 | type ItemType = Totp; 152 | 153 | fn pre_handle_matches(&self, matches: &Vec) { 154 | println!("Found {} TOTP entries", matches.len()); 155 | show_totp_table(matches); 156 | } 157 | 158 | fn handle_one_match(&mut self, the_match: Self::ItemType) -> Result, Error> { 159 | let response = ui::input::ask("Do you want to delete this TOTP entry? (y/n)"); 160 | if response == "y" { 161 | println!("Deleting TOTP entry '{}'...", the_match.label()); 162 | self.vault.delete_totp(&the_match.id())?; 163 | return Ok(Some("Deleted".to_string())); 164 | } 165 | Ok(None) 166 | } 167 | 168 | fn handle_many_matches( 169 | &mut self, 170 | matches: Vec, 171 | ) -> Result, Error> { 172 | match ui::input::ask_index( 173 | "To delete, please enter a row number from the table above", 174 | matches.len() as i16 - 1, 175 | Some("Press q to exit without deleting"), 176 | ) { 177 | Ok(index) => { 178 | if index == usize::MAX { 179 | Ok(None) 180 | } else { 181 | println!( 182 | "Deleting TOTP entry labeled '{}'...", 183 | matches[index].label() 184 | ); 185 | self.vault.delete_totp(&matches[index].id())?; 186 | Ok(Some("Deleted".to_string())) 187 | } 188 | } 189 | Err(message) => Err(Error { message }), 190 | } 191 | } 192 | } 193 | 194 | pub struct DeleteAction { 195 | pub grep: Option, 196 | pub item_type: ItemType, 197 | pub is_totp: bool, 198 | } 199 | 200 | impl DeleteAction { 201 | pub fn new(matches: &ArgMatches) -> DeleteAction { 202 | DeleteAction { 203 | grep: matches.get_one::("REGEXP").cloned(), 204 | item_type: ItemType::new_from_args(matches), 205 | is_totp: matches.get_one::("otp").map_or(false, |v| *v), 206 | } 207 | } 208 | } 209 | 210 | impl UnlockingAction for DeleteAction { 211 | fn is_totp_vault(&self) -> bool { 212 | self.is_totp 213 | } 214 | 215 | fn run_with_vault(&self, vault: &mut Box) -> Result, Error> { 216 | match self.item_type { 217 | ItemType::Credential => { 218 | let grep = match &self.grep { 219 | Some(grep) => grep.as_str(), 220 | None => { 221 | return Err(Error { 222 | message: "No search term provided".to_string(), 223 | }) 224 | } 225 | }; 226 | handle_matches( 227 | vault.grep(Some(grep)), 228 | &mut Box::new(DeleteCredentialsTemplate { vault, grep }), 229 | ) 230 | } 231 | ItemType::Payment => handle_matches( 232 | vault.find_payments(), 233 | &mut Box::new(DeletePaymentTemplate { vault }), 234 | ), 235 | ItemType::Note => handle_matches( 236 | vault.find_notes(), 237 | &mut Box::new(DeleteNoteTemplate { vault }), 238 | ), 239 | ItemType::Totp => handle_matches( 240 | vault.find_totp(self.grep.as_deref()), 241 | &mut Box::new(DeleteTotpTemplate { vault }), 242 | ), 243 | } 244 | } 245 | } 246 | -------------------------------------------------------------------------------- /src/actions/show.rs: -------------------------------------------------------------------------------- 1 | use crate::actions::{ 2 | copy_to_clipboard, handle_matches, ItemType, MatchHandlerTemplate, UnlockingAction, 3 | }; 4 | 5 | use crate::ui::input::{ask_index, ask_with_options}; 6 | use crate::ui::output::{ 7 | show_card, show_credentials_table, show_note, show_notes_table, show_payment_cards_table, 8 | show_totp_table, 9 | }; 10 | use crate::vault::entities::{Credential, Error, Note, PaymentCard, Totp}; 11 | use crate::vault::vault_trait::Vault; 12 | use clap::ArgMatches; 13 | use log::debug; 14 | use std::io::{self, Read, Write}; 15 | use std::sync::mpsc; 16 | use std::thread; 17 | use std::time::Duration; 18 | 19 | struct ShowCredentialsTemplate { 20 | verbose: bool, 21 | } 22 | 23 | impl MatchHandlerTemplate for ShowCredentialsTemplate { 24 | type ItemType = Credential; 25 | 26 | fn pre_handle_matches(&self, matches: &Vec) { 27 | println!("Found {} credentials:", matches.len()); 28 | } 29 | 30 | fn handle_one_match(&mut self, the_match: Self::ItemType) -> Result, Error> { 31 | show_credentials_table(&vec![the_match.clone()], self.verbose); 32 | copy_to_clipboard(the_match.password()); 33 | Ok(Some("Password copied to clipboard!".to_string())) 34 | } 35 | 36 | fn handle_many_matches( 37 | &mut self, 38 | matches: Vec, 39 | ) -> Result, Error> { 40 | show_credentials_table(&matches, self.verbose); 41 | 42 | match ask_index( 43 | "To copy one of these passwords to clipboard, please enter a row number from the table above", 44 | matches.len() as i16 - 1, 45 | Some("Press q to exit without copying the password"), 46 | ) { 47 | Ok(index) => { 48 | copy_to_clipboard(matches[index].password()); 49 | Ok(Some("Password copied to clipboard!".to_string())) 50 | } 51 | Err(message) => { 52 | Err(Error { message }) 53 | } 54 | } 55 | } 56 | } 57 | 58 | struct ShowPaymentsTemplate { 59 | show_cleartext: bool, 60 | } 61 | 62 | impl MatchHandlerTemplate for ShowPaymentsTemplate { 63 | type ItemType = PaymentCard; 64 | 65 | fn pre_handle_matches(&self, matches: &Vec) { 66 | println!("Found {} payment cards:", matches.len()); 67 | } 68 | 69 | fn handle_one_match(&mut self, the_match: Self::ItemType) -> Result, Error> { 70 | show_payment_cards_table(&vec![the_match.clone()], self.show_cleartext); 71 | copy_to_clipboard(the_match.number()); 72 | match ask_with_options( 73 | "Do you want to see the full card details? (yes/no)", 74 | vec!["yes", "no"], 75 | ) 76 | .as_str() 77 | { 78 | "yes" => { 79 | show_card(&the_match); 80 | Ok(Some("Card number copied to clipboard!".to_string())) 81 | } 82 | _ => Ok(Some("Card number copied to clipboard!".to_string())), 83 | } 84 | } 85 | 86 | fn handle_many_matches( 87 | &mut self, 88 | matches: Vec, 89 | ) -> Result, Error> { 90 | show_payment_cards_table(&matches, self.show_cleartext); 91 | 92 | match ask_index( 93 | "To see card details, enter a row number from the table above", 94 | matches.len() as i16 - 1, 95 | Some("Press q to exit without showing"), 96 | ) { 97 | Ok(index) => { 98 | show_card(&matches[index]); 99 | copy_to_clipboard(matches[index].number()); 100 | Ok(Some("Card number copied to clipboard!".to_string())) 101 | } 102 | Err(message) => Err(Error { message }), 103 | } 104 | } 105 | } 106 | 107 | struct ShowNotesTemplate { 108 | verbose: bool, 109 | } 110 | 111 | impl MatchHandlerTemplate for ShowNotesTemplate { 112 | type ItemType = Note; 113 | 114 | fn pre_handle_matches(&self, matches: &Vec) { 115 | println!("Found {} notes:", matches.len()); 116 | } 117 | 118 | fn handle_one_match(&mut self, the_match: Self::ItemType) -> Result, Error> { 119 | show_notes_table(&vec![the_match.clone()], self.verbose); 120 | let response = ask_with_options( 121 | "Do you want to see the full note? (yes/no)", 122 | vec!["yes", "no"], 123 | ); 124 | if response == "yes" { 125 | show_note(&the_match); 126 | } 127 | Ok(None) 128 | } 129 | 130 | fn handle_many_matches( 131 | &mut self, 132 | matches: Vec, 133 | ) -> Result, Error> { 134 | show_notes_table(&matches, self.verbose); 135 | 136 | match ask_index( 137 | "To see the full note, please enter a row number from the table above", 138 | matches.len() as i16 - 1, 139 | Some("Press q to exit without showing the note"), 140 | ) { 141 | Ok(index) => { 142 | show_note(&matches[index]); 143 | Ok(None) 144 | } 145 | Err(message) => Err(Error { message }), 146 | } 147 | } 148 | } 149 | 150 | struct ShowTotpTemplate; 151 | 152 | impl MatchHandlerTemplate for ShowTotpTemplate { 153 | type ItemType = Totp; 154 | 155 | fn pre_handle_matches(&self, matches: &Vec) { 156 | println!("Found {} matching OTP authorizers:", matches.len()); 157 | show_totp_table(matches); 158 | } 159 | 160 | fn handle_one_match(&mut self, the_match: Self::ItemType) -> Result, Error> { 161 | debug!("found totp: {}", the_match); 162 | Self::show_code(the_match) 163 | } 164 | 165 | fn handle_many_matches( 166 | &mut self, 167 | matches: Vec, 168 | ) -> Result, Error> { 169 | match ask_index( 170 | "To see the code for one of these OTP authorizers, please enter a row number from the table above", 171 | matches.len() as i16 - 1, 172 | Some("Press q to exit without showing the code"), 173 | ) { 174 | Ok(index) => { 175 | Self::show_code(matches[index].clone()) 176 | } 177 | Err(message) => { 178 | Err(Error { message }) 179 | } 180 | } 181 | } 182 | } 183 | 184 | impl ShowTotpTemplate { 185 | fn show_code(the_match: Totp) -> Result, Error> { 186 | let (tx, rx) = mpsc::channel(); 187 | let (tx_counter, rx_counter) = mpsc::channel(); 188 | 189 | // Spawn a thread to listen for keyboard input 190 | thread::spawn(move || { 191 | let mut buffer = [0; 1]; 192 | let stdin = io::stdin(); 193 | let mut handle = stdin.lock(); 194 | 195 | loop { 196 | if handle.read_exact(&mut buffer).is_ok() { 197 | let input = buffer[0]; 198 | if input == b'q' || input == 4 { 199 | // 'q' or Ctrl+D (EOF) 200 | tx.send(()).expect("Failed to send termination signal"); 201 | break; 202 | } 203 | } 204 | } 205 | }); 206 | 207 | // Spawn a thread to handle the countdown timer 208 | thread::spawn(move || loop { 209 | let duration = rx_counter.recv().expect("Failed to receive duration"); 210 | println!("Next code in {} seconds", duration); 211 | println!("{}", ".".repeat(duration as usize)); 212 | io::stdout().flush().unwrap(); 213 | 214 | for _ in (1..=duration).rev() { 215 | print!("."); 216 | io::stdout().flush().unwrap(); 217 | thread::sleep(Duration::from_secs(1)); 218 | } 219 | }); 220 | 221 | loop { 222 | let code = the_match.get_code(); 223 | 224 | match code { 225 | Ok(code) => { 226 | copy_to_clipboard(&code.value); 227 | println!( 228 | "\nCode {} (also copied to clipboard). Press q to exit.", 229 | code.value 230 | ); 231 | 232 | // Send the duration to the countdown timer thread 233 | tx_counter 234 | .send(code.valid_for_seconds) 235 | .expect("Failed to send duration"); 236 | 237 | // Wait for the specified duration or a keyboard interrupt 238 | let duration = Duration::from_secs(code.valid_for_seconds); 239 | if rx.recv_timeout(duration).is_ok() { 240 | println!("Exiting as requested."); 241 | break; 242 | } 243 | } 244 | Err(e) => { 245 | return Err(Error { message: e.message }); 246 | } 247 | } 248 | } 249 | Ok(None) 250 | } 251 | } 252 | 253 | pub struct ShowAction { 254 | pub grep: Option, 255 | pub verbose: bool, 256 | pub item_type: ItemType, 257 | pub is_totp: bool, 258 | } 259 | 260 | impl ShowAction { 261 | pub fn new(matches: &ArgMatches) -> ShowAction { 262 | ShowAction { 263 | grep: matches.get_one::("REGEXP").cloned(), 264 | verbose: matches.get_one::("verbose").map_or(false, |v| *v), 265 | item_type: ItemType::new_from_args(matches), 266 | is_totp: matches.get_one::("otp").map_or(false, |v| *v), 267 | } 268 | } 269 | } 270 | 271 | impl UnlockingAction for ShowAction { 272 | fn is_totp_vault(&self) -> bool { 273 | self.is_totp 274 | } 275 | 276 | fn run_with_vault(&self, vault: &mut Box) -> Result, Error> { 277 | match self.item_type { 278 | ItemType::Credential => { 279 | let grep = match &self.grep { 280 | Some(grep) => grep.as_str(), 281 | None => { 282 | return Err(Error { 283 | message: "No search term REGEXP provided".to_string(), 284 | }) 285 | } 286 | }; 287 | handle_matches( 288 | vault.grep(Some(grep)), 289 | &mut Box::new(ShowCredentialsTemplate { 290 | verbose: self.verbose, 291 | }), 292 | ) 293 | } 294 | ItemType::Payment => handle_matches( 295 | vault.find_payments(), 296 | &mut Box::new(ShowPaymentsTemplate { 297 | show_cleartext: self.verbose, 298 | }), 299 | ), 300 | ItemType::Note => handle_matches( 301 | vault.find_notes(), 302 | &mut Box::new(ShowNotesTemplate { 303 | verbose: self.verbose, 304 | }), 305 | ), 306 | ItemType::Totp => handle_matches( 307 | vault.find_totp(self.grep.as_deref()), 308 | &mut Box::new(ShowTotpTemplate), 309 | ), 310 | } 311 | } 312 | } 313 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Passlane 2 | 3 | ![passlane-logo-small](https://github.com/anssip/passlane/assets/271711/6041f6fb-816f-43e9-b54c-325180addef1) 4 | 5 | A password manager and authenticator CLI using Keepass as the storage backend. In addition to passwords, it supports 6 | **authenticator functionality** with Timed One Time Passwords (TOTP), secure saving and managing of 7 | **payment cards** and **secure notes**. 8 | 9 | Passlane uses the Keepass encrypted file format for storing the data. 10 | 11 | Passlane is written in Rust. 12 | 13 | ## Features 14 | 15 | - Keepass storage format which allows you to use the vault with other Keepass compatible applications 16 | - Supports KDB, KDBX3 and KDBX4 file formats 17 | - The keepass storage file can be optionally secured using a [key file](https://keepassxc.org/docs/) to provide additional protection 18 | - Generate and save passwords 19 | - Save and view payment card information 20 | - Save and view secure notes 21 | - Authenticator functionality with TOTP 22 | - Import passwords from CSV files 23 | - Export vault contents to CSV files 24 | 25 | ## Table of contents 26 | 27 | - [Installation](#installation) 28 | - [Usage](#usage) 29 | - [Locking and unlocking the vault](#locking-and-unlocking-the-vault) 30 | - [Generating and saving passwords](#generating-and-saving-passwords) 31 | - [Using saved credentials](#using-saved-credentials) 32 | - [Payment cards](#payment-cards) 33 | - [Secure notes](#secure-notes) 34 | - [Authenticator functionality](#authenticator-functionality) 35 | - [Migrating from 1Password, LastPass, Dashlane etc.](#migrating-from-1password-lastpass-dashlane-etc) 36 | - [Import from CSV](#import-from-csv) 37 | - [Export to CSV](#export-to-csv) 38 | - [Syncing data to your devices](#syncing-data-to-your-devices) 39 | - [Other Keepass compatible applications](#other-keepass-compatible-applications) 40 | 41 | ## Installation 42 | 43 | 1. Download the [latest release](https://github.com/anssip/passlane/releases) 44 | 2. Unpack the archive 45 | 3. Place the unarchived binary `passlane` to your $PATH 46 | 47 | ### To compile from sources 48 | 49 | 1. Install rust development environment: [rustup](https://rustup.rs) 50 | 2. Clone this repo 51 | 3. Run build: `cargo build --release` 52 | 4. Add the built `passlane` binary to your `$PATH` 53 | 54 | ### Nix 55 | 56 | Run with nix - following creates a new password: 57 | 58 | ```bash 59 | nix run github:anssip/passlane 60 | ``` 61 | 62 | See below for more information on how to use the CLI. 63 | 64 | ## Usage 65 | 66 | ### First time setup 67 | 68 | Run the init command to create a new vault file, or to link passlane to an existing Keepass compatible vault file. The command will interactively ask you for the required information. 69 | 70 | ```bash 71 | passlane init 72 | ``` 73 | 74 | You place the vault file to the cloud allowing access from all your devices. [See below for more info](#syncing-data-to-your-devices). 75 | 76 | ### Keypass key file 77 | 78 | In addition to the master password, you can use a key file to provide additional protection for the vault file. At this 79 | time, Passlane cannot be used to create a key file, but you can create one with KeepassXC or other Keepass compatible 80 | app. Once you have the file, configure the location of this file in the `.keyfile_path` file in the `~/.passlane/` directory. 81 | 82 | ### Locking and unlocking the vault 83 | 84 | Use the unlock command to store the master password in your computer's keychain. This way you don't have to enter the 85 | master password every time you access your passwords and other vault contents. On Macs you can then use biometric authentication 86 | to gain access to the keychain and further to the vault without typing any passwords. 87 | 88 | ```bash 89 | passlane unlock 90 | ``` 91 | 92 | You can later remove the master password from the keychain with the lock command. 93 | 94 | The one time passwords (OTPs) are stored in a separate vault file. You can unlock it with the same command 95 | accompanied with the -o option. 96 | 97 | ```bash 98 | passlane unlock -o 99 | ``` 100 | 101 | To lock the vaults use the lock command. This locks both the password vault and the OTP vault: 102 | 103 | ```bash 104 | passlane lock 105 | ``` 106 | 107 | To get help on the available commands: 108 | 109 | ```bash 110 | ➜ passlane -h 111 | 112 | A password manager using Keepass as the storage backend. 113 | 114 | Usage: passlane [COMMAND] 115 | 116 | Commands: 117 | init Initialize passlane. Walks you through the configuration process. 118 | add Adds an item to the vault. Without arguments adds a new credential, use -p to add a payment card and -n to add a secure note. 119 | edit Edit an entry. 120 | csv Imports credentials from a CSV file. 121 | delete Deletes one or more entries. 122 | show Shows one or more entries. 123 | lock Lock the vaults to prevent all access 124 | unlock Opens the vaults and grants access to the entries 125 | export Exports the vault contents to a CSV file. 126 | help Print this message or the help of the given subcommand(s) 127 | 128 | Options: 129 | -h, --help Print help 130 | ``` 131 | 132 | ### Generating and saving passwords 133 | 134 | To generate a new password without saving it. The generated password value is also copied to the clipboard. 135 | 136 | ```bash 137 | passlane 138 | ``` 139 | 140 | To save new credentials by copying the password from clipboard: 141 | 142 | ```bash 143 | passlane add --clipboard 144 | ``` 145 | 146 | To generate a new password and save credentials with one command: 147 | 148 | ```bash 149 | passlane add -g 150 | ``` 151 | 152 | ### Using saved credentials 153 | 154 | You can search and show saved credentials with regular expressions 155 | 156 | ```bash 157 | passlane show 158 | ``` 159 | 160 | Run `passlane show foobard.com` --> shows foobar.com's password and also copies the value to the clipboard. 161 | 162 | If the search finds more than one matches: 163 | 164 | ```bash 165 | ➜ bin passlane show google 166 | Unlocking vault... 167 | Found 6 credentials: 168 | +---+--------------------------------+--------------------------------+------------------+ 169 | | | Service | Username/email | Modified | 170 | +========================================================================================+ 171 | | 0 | google.com | anssi@emmy.fi | 23.10.2024 07:22 | 172 | |---+--------------------------------+--------------------------------+------------------| 173 | | 1 | https://accounts.google.com/si | anssi@amm.co.jp | 23.04.2024 14:15 | 174 | |---+--------------------------------+--------------------------------+------------------| 175 | | 2 | google.com | anssi.piirainen@flowplayer.com | 23.04.2024 14:15 | 176 | |---+--------------------------------+--------------------------------+------------------| 177 | | 3 | google.com | anssip | 23.04.2024 14:15 | 178 | |---+--------------------------------+--------------------------------+------------------| 179 | | 4 | google.com | anssi@carbon.video | 23.04.2024 14:15 | 180 | +---+--------------------------------+--------------------------------+------------------+ 181 | ? To copy one of these passwords to clipboard, please enter a row number from the table above 182 | [Press q to exit without copying the password] 183 | ``` 184 | 185 | ### Payment cards 186 | 187 | To list all your saved payment cards. 188 | 189 | ```bash 190 | ➜ bin passlane show -p 191 | Unlocking vault... 192 | Found 3 payment cards: 193 | +---+-------------------------+-------+--------+------------------+ 194 | | | Name | Color | Expiry | Modified | 195 | +=================================================================+ 196 | | 0 | OP Corporate Gold (NPD) | Gold | 1/2029 | 23.10.2024 13:15 | 197 | |---+-------------------------+-------+--------+------------------| 198 | | 1 | Binance | black | 4/2010 | 23.10.2024 13:15 | 199 | |---+-------------------------+-------+--------+------------------| 200 | | 2 | Visa Gold (personal) | Gold | 6/2025 | 23.10.2024 13:15 | 201 | +---+-------------------------+-------+--------+------------------+ 202 | ? To see card details, enter a row number from the table above 203 | [Press q to exit without showing] 204 | ``` 205 | 206 | To save a payment card: 207 | 208 | ```bash 209 | passlane add -p 210 | ``` 211 | 212 | You can delete a note with the delete command and the -n option. 213 | 214 | ### Secure notes 215 | 216 | You can also save and manage **secure notes** in Passlane. The contents of notes, the title and the note text itself, are all fully encrypted and only visible to you. 217 | 218 | You can store multiline notes in the vault. To add a secure note: 219 | 220 | ``` 221 | passlane add -n 222 | ``` 223 | 224 | To delete secure notes: 225 | 226 | ``` 227 | passlane delete -n 228 | ``` 229 | 230 | To show secure notes: 231 | 232 | ``` 233 | passlane show -n 234 | ``` 235 | 236 | ### Authenticator functionality 237 | 238 | By default, Passlane stores the Timed One Time Passwords in a file named `totp.json` in the `~/.passlane/` directory. 239 | You can change the location by storing the file path in a text file called `.totp_vault_path` in the `~/.passlane/` directory. 240 | **We recommend that you store the file in a separate location that is different from the main vault file.** This way 241 | you gain the benefit of two-factor authentication. You don't want to store these eggs in the same basket. 242 | 243 | Here is an example where teh totp vault file is stored in Dropbox: 244 | 245 | ```bash 246 | ~/.passlane > cat .totp_vault_path 247 | /Users/anssi/Dropbox/stuff/totp.kdbx 248 | ``` 249 | 250 | The TOTP vault has a separate master password that you need to enter when you access the one time passwords. 251 | You can also store the master password in your computer's keychain to avoid typing it every time. Use 252 | the unlock command with the `-o` option for this purpose. 253 | 254 | ```bash 255 | passlane unlock -o 256 | ``` 257 | 258 | To add a new one time password authentication entry: 259 | 260 | ```bash 261 | passlane add -o 262 | ``` 263 | 264 | Use -o to show the one time passwords. Following lists all OTP entries in the vault: 265 | 266 | ```bash 267 | passlane show -o 268 | ``` 269 | 270 | To look up by name of the issuer, use the following command: 271 | 272 | ```bash 273 | passlane show -o heroku 274 | ``` 275 | 276 | the output will be: 277 | 278 | ```bash 279 | Unlocking TOTP vault... 280 | Found 1 matching OTP authorizers: 281 | 282 | Code 447091 (also copied to clipboard). Press q to exit. 283 | Next code in 23 seconds 284 | ....................... 285 | ....................... 286 | Code 942344 (also copied to clipboard). Press q to exit. 287 | Next code in 30 seconds 288 | .............................. 289 | ... 290 | ``` 291 | 292 | ### Import from CSV 293 | 294 | You can import credentials from a CSV file. With this approach, you can easily migrate from less elegant and often expensive commercial services. 295 | 296 | First, make sure that the CSV file has a header line (1st line) with the following column titles: 297 | 298 | - username 299 | - password 300 | - service 301 | 302 | The `service` field is the URL or name of the service. When importing from Dashlane, the only necessary preparation is to rename `url` to `service`. 303 | 304 | To export the credentials to a CSV file and import the file into Passlane: 305 | 306 | ```bash 307 | passlane csv 308 | ``` 309 | 310 | Here are links to instructions for doing the CSV export: 311 | 312 | - [LastPass](https://support.lastpass.com/help/how-do-i-nbsp-export-stored-data-from-lastpass-using-a-generic-csv-file) 313 | - [1Password](https://support.1password.com/export/) 314 | - [Dashlane](https://support.dashlane.com/hc/en-us/articles/202625092-Export-your-passwords-from-Dashlane) 315 | 316 | ### Export to CSV 317 | 318 | You can export all your vault contents to CSV files. The exported files can be imported to other password managers or to a spreadsheet program. 319 | 320 | To export credentials to a file called creds.csv 321 | 322 | ```bash 323 | passlane export creds.csv 324 | ``` 325 | 326 | To export payment cards to a file called cards.csv. 327 | 328 | ```bash 329 | passlane export -p cards.csv 330 | ``` 331 | 332 | To export secure notes to a file called notes.csv 333 | 334 | ```bash 335 | passlane export -n notes.csv 336 | ``` 337 | 338 | ## Syncing data to your devices 339 | 340 | You can place the vault file to a cloud storage service like Dropbox, Google Drive, or iCloud Drive. 341 | This way you can access your passwords from all your devices. 342 | By default, Passlane assumes that the file is located at `~/.passlane/store.kdbx`. 343 | You can change the location by storing the file path in a text file called `.vault_path` at the `~/.passlane/` directory. 344 | 345 | For example, this shows how John has stored the path `/Users/john/Dropbox/Stuff/store.kdbx` to the `.vault_path` file: 346 | 347 | ```bash 348 | ➜ ~ cat ~/.passlane/.vault_path 349 | /Users/john/Dropbox/Stuff/store.kdbx 350 | ``` 351 | 352 | ## Other Keepass compatible applications 353 | 354 | There are several other Keepass compatible applications that you can use to access the vault file: 355 | 356 | - [KeepassXC](https://keepassxc.org/) is a desktop application for Windows, macOS, and Linux 357 | - [KeepassXC-Browser](https://github.com/keepassxreboot/keepassxc-browser) 358 | - [KeePassium](https://keepassium.com/) is a mobile application for iOS 359 | - ... and many others 360 | -------------------------------------------------------------------------------- /src/vault/entities.rs: -------------------------------------------------------------------------------- 1 | use chrono::{DateTime, Utc}; 2 | use keepass_ng::db::TOTP; 3 | use log::debug; 4 | use serde::{Deserialize, Serialize}; 5 | use std::fmt; 6 | use std::fmt::{Display, Formatter}; 7 | use std::num::ParseIntError; 8 | use std::str::FromStr; 9 | use std::time::SystemTimeError; 10 | use uuid::Uuid; 11 | 12 | use crate::crypto::SPECIAL; 13 | 14 | #[derive(Debug)] 15 | pub struct Error { 16 | pub message: String, 17 | } 18 | 19 | impl Error { 20 | pub fn new(message: &str) -> Self { 21 | Error { 22 | message: message.to_string(), 23 | } 24 | } 25 | } 26 | 27 | impl From for Error { 28 | fn from(err: SystemTimeError) -> Self { 29 | Error { 30 | message: err.to_string(), 31 | } 32 | } 33 | } 34 | 35 | impl From for Error { 36 | fn from(err: std::io::Error) -> Self { 37 | Error { 38 | message: err.to_string(), 39 | } 40 | } 41 | } 42 | 43 | impl From for Error { 44 | fn from(err: anyhow::Error) -> Self { 45 | Error { 46 | message: err.to_string(), 47 | } 48 | } 49 | } 50 | 51 | impl Display for Error { 52 | fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { 53 | write!(f, "{}", &self.message) 54 | } 55 | } 56 | 57 | #[derive(Clone, Serialize, Deserialize)] 58 | pub struct Credential { 59 | #[serde(skip_serializing, skip_deserializing)] 60 | uuid: Uuid, 61 | password: String, 62 | service: String, 63 | username: String, 64 | #[serde(default = "default_last_modified")] 65 | last_modified: DateTime, 66 | } 67 | 68 | fn default_last_modified() -> DateTime { 69 | Utc::now() 70 | } 71 | 72 | impl Credential { 73 | pub fn new( 74 | uuid: Option<&Uuid>, 75 | password: &str, 76 | service: &str, 77 | username: &str, 78 | last_modified: Option>, 79 | ) -> Self { 80 | Credential { 81 | uuid: uuid.map(|id| id.clone()).unwrap_or_else(|| Uuid::new_v4()), 82 | password: password.to_string(), 83 | service: sanitize(service), 84 | username: sanitize(username), 85 | last_modified: last_modified.unwrap_or(Utc::now()), 86 | } 87 | } 88 | 89 | pub fn uuid(&self) -> &Uuid { 90 | &self.uuid 91 | } 92 | 93 | pub fn password(&self) -> &str { 94 | &self.password 95 | } 96 | 97 | pub fn service(&self) -> &str { 98 | &self.service 99 | } 100 | 101 | pub fn username(&self) -> &str { 102 | &self.username 103 | } 104 | 105 | pub fn last_modified(&self) -> &DateTime { 106 | &self.last_modified 107 | } 108 | } 109 | 110 | #[derive(Clone)] 111 | pub struct PaymentCard { 112 | id: Uuid, 113 | name: String, 114 | name_on_card: String, 115 | number: String, 116 | cvv: String, 117 | expiry: Expiry, 118 | color: Option, 119 | billing_address: Option
, 120 | last_modified: DateTime, 121 | } 122 | 123 | impl PaymentCard { 124 | pub fn new( 125 | id: Option<&Uuid>, 126 | name: &str, 127 | name_on_card: &str, 128 | number: &str, 129 | cvv: &str, 130 | expiry: Expiry, 131 | color: Option<&str>, 132 | billing_address: Option<&Address>, 133 | last_modified: Option>, 134 | ) -> Self { 135 | PaymentCard { 136 | id: id.map(|id| id.clone()).unwrap_or_else(|| Uuid::new_v4()), 137 | name: sanitize(name), 138 | name_on_card: sanitize(name_on_card), 139 | number: sanitize(number), 140 | cvv: sanitize(cvv), 141 | expiry, 142 | color: color.map(sanitize), 143 | billing_address: billing_address.cloned(), 144 | last_modified: last_modified.unwrap_or_else(|| Utc::now()), 145 | } 146 | } 147 | 148 | pub fn id(&self) -> &Uuid { 149 | &self.id 150 | } 151 | 152 | pub fn name(&self) -> &str { 153 | &self.name 154 | } 155 | 156 | pub fn name_on_card(&self) -> &str { 157 | &self.name_on_card 158 | } 159 | 160 | pub fn number(&self) -> &str { 161 | &self.number 162 | } 163 | 164 | pub fn cvv(&self) -> &str { 165 | &self.cvv 166 | } 167 | 168 | pub fn expiry(&self) -> &Expiry { 169 | &self.expiry 170 | } 171 | 172 | pub fn color(&self) -> Option<&String> { 173 | self.color.as_ref() 174 | } 175 | 176 | pub fn billing_address(&self) -> Option<&Address> { 177 | self.billing_address.as_ref() 178 | } 179 | 180 | pub fn last_modified(&self) -> &DateTime { 181 | &self.last_modified 182 | } 183 | } 184 | 185 | #[derive(Clone)] 186 | pub struct Totp { 187 | id: Uuid, 188 | url: String, 189 | label: String, 190 | issuer: String, 191 | secret: String, 192 | algorithm: String, 193 | period: u64, 194 | digits: u32, 195 | last_modified: DateTime, 196 | } 197 | 198 | impl Totp { 199 | pub fn new( 200 | id: Option<&Uuid>, 201 | url: &str, 202 | label: &str, 203 | issuer: &str, 204 | secret: &str, 205 | algorithm: &str, 206 | period: u64, 207 | digits: u32, 208 | last_modified: Option>, 209 | ) -> Self { 210 | Totp { 211 | id: id.map(|id| id.clone()).unwrap_or_else(|| Uuid::new_v4()), 212 | url: url.to_string(), 213 | label: sanitize(label), 214 | issuer: issuer.to_string(), 215 | secret: secret.to_string(), 216 | algorithm: algorithm.to_string(), 217 | period, 218 | digits, 219 | last_modified: last_modified.unwrap_or_else(|| Utc::now()), 220 | } 221 | } 222 | 223 | pub fn id(&self) -> &Uuid { 224 | &self.id 225 | } 226 | 227 | pub fn url(&self) -> &str { 228 | &self.url 229 | } 230 | 231 | pub fn label(&self) -> &str { 232 | &self.label 233 | } 234 | 235 | pub fn issuer(&self) -> &str { 236 | &self.issuer 237 | } 238 | 239 | pub fn secret(&self) -> &str { 240 | &self.secret 241 | } 242 | 243 | pub fn algorithm(&self) -> &str { 244 | &self.algorithm 245 | } 246 | 247 | pub fn period(&self) -> u64 { 248 | self.period 249 | } 250 | 251 | pub fn digits(&self) -> u32 { 252 | self.digits 253 | } 254 | 255 | pub fn last_modified(&self) -> &DateTime { 256 | &self.last_modified 257 | } 258 | } 259 | 260 | impl Display for Totp { 261 | fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { 262 | write!( 263 | f, 264 | "label: {}, issuer: {}, secret: {}, algo: {}, digits: {}", 265 | self.label, self.issuer, self.secret, self.algorithm, self.digits 266 | ) 267 | } 268 | } 269 | 270 | pub struct TotpCode { 271 | pub value: String, 272 | pub valid_for_seconds: u64, 273 | } 274 | 275 | impl Totp { 276 | pub fn get_code(&self) -> Result { 277 | let totp = TOTP::from_str(&self.url) 278 | .map_err(|e| Error::new(&format!("Failed to parse totp url: {:?}", e)))?; 279 | 280 | debug!("Getting code for totp: {}", totp); 281 | let code = totp.value_now()?; 282 | Ok(TotpCode { 283 | value: code.code, 284 | valid_for_seconds: code.valid_for.as_secs(), 285 | }) 286 | } 287 | } 288 | 289 | impl PaymentCard { 290 | pub fn color_str(&self) -> String { 291 | if let Some(color) = &self.color { 292 | color.clone() 293 | } else { 294 | "".to_string() 295 | } 296 | } 297 | pub fn expiry_str(&self) -> String { 298 | self.expiry.to_string() 299 | } 300 | } 301 | 302 | #[derive(Clone)] 303 | pub struct Expiry { 304 | pub month: u32, 305 | pub year: u32, 306 | } 307 | 308 | impl Display for Expiry { 309 | fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { 310 | write!(f, "{}/{}", self.month, self.year) 311 | } 312 | } 313 | 314 | #[derive(Debug)] 315 | pub enum ExpiryParseError { 316 | InvalidFormat, 317 | ParseError(ParseIntError), 318 | } 319 | 320 | impl fmt::Display for ExpiryParseError { 321 | fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { 322 | match self { 323 | ExpiryParseError::InvalidFormat => write!(f, "Invalid format. Expected MM/YYYY"), 324 | ExpiryParseError::ParseError(e) => e.fmt(f), 325 | } 326 | } 327 | } 328 | 329 | impl std::error::Error for ExpiryParseError {} 330 | 331 | impl From for ExpiryParseError { 332 | fn from(err: ParseIntError) -> ExpiryParseError { 333 | ExpiryParseError::ParseError(err) 334 | } 335 | } 336 | 337 | impl FromStr for Expiry { 338 | type Err = ExpiryParseError; 339 | 340 | fn from_str(s: &str) -> Result { 341 | let parts: Vec<&str> = s.split('/').collect(); 342 | if parts.len() != 2 { 343 | return Err(ExpiryParseError::InvalidFormat); 344 | } 345 | let month = parts[0] 346 | .parse::() 347 | .map_err(ExpiryParseError::ParseError)?; 348 | let year = parts[1] 349 | .parse::() 350 | .map_err(ExpiryParseError::ParseError)?; 351 | Ok(Expiry { month, year }) 352 | } 353 | } 354 | 355 | #[derive(Clone)] 356 | pub struct Address { 357 | id: Uuid, 358 | street: String, 359 | city: String, 360 | country: String, 361 | state: Option, 362 | zip: String, 363 | } 364 | 365 | impl Address { 366 | pub fn new( 367 | id: Option<&Uuid>, 368 | street: &str, 369 | city: &str, 370 | country: &str, 371 | state: Option<&str>, 372 | zip: &str, 373 | ) -> Self { 374 | Address { 375 | id: id.map(|id| id.clone()).unwrap_or_else(|| Uuid::new_v4()), 376 | street: sanitize(street), 377 | city: sanitize(city), 378 | country: sanitize(country), 379 | state: state.map(sanitize), 380 | zip: sanitize(zip), 381 | } 382 | } 383 | 384 | pub fn id(&self) -> &Uuid { 385 | &self.id 386 | } 387 | 388 | pub fn street(&self) -> &str { 389 | &self.street 390 | } 391 | 392 | pub fn city(&self) -> &str { 393 | &self.city 394 | } 395 | 396 | pub fn country(&self) -> &str { 397 | &self.country 398 | } 399 | 400 | pub fn state(&self) -> Option<&String> { 401 | self.state.as_ref() 402 | } 403 | 404 | pub fn zip(&self) -> &str { 405 | &self.zip 406 | } 407 | } 408 | 409 | #[derive(Clone)] 410 | pub struct Note { 411 | id: Uuid, 412 | title: String, 413 | content: String, 414 | last_modified: DateTime, 415 | } 416 | 417 | fn sanitize(value: &str) -> String { 418 | value 419 | .chars() 420 | .filter(|c| c.is_alphanumeric() || c.is_whitespace() || SPECIAL.contains(*c)) 421 | .collect::() 422 | } 423 | 424 | impl Note { 425 | pub fn new( 426 | id: Option<&Uuid>, 427 | title: &str, 428 | content: &str, 429 | last_modified: Option>, 430 | ) -> Self { 431 | Note { 432 | id: id.map(|id| id.clone()).unwrap_or_else(|| Uuid::new_v4()), 433 | title: sanitize(title), 434 | content: sanitize(content), 435 | last_modified: last_modified.unwrap_or_else(Utc::now), 436 | } 437 | } 438 | pub fn id(&self) -> Uuid { 439 | self.id 440 | } 441 | pub fn title(&self) -> &str { 442 | &self.title 443 | } 444 | pub fn content(&self) -> &str { 445 | &self.content 446 | } 447 | pub fn last_modified(&self) -> DateTime { 448 | self.last_modified 449 | } 450 | } 451 | 452 | impl Display for Address { 453 | fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { 454 | write!( 455 | f, 456 | "{}, {}, {}, {}", 457 | self.street, self.zip, self.city, self.country 458 | ) 459 | } 460 | } 461 | 462 | #[derive(Debug)] 463 | pub enum AddressParseError { 464 | InvalidFormat, 465 | ParseError(ParseIntError), 466 | } 467 | 468 | impl fmt::Display for AddressParseError { 469 | fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { 470 | match self { 471 | AddressParseError::InvalidFormat => { 472 | write!(f, "Invalid format. Expected Street, Zip, City, Country") 473 | } 474 | AddressParseError::ParseError(e) => e.fmt(f), 475 | } 476 | } 477 | } 478 | 479 | impl std::error::Error for AddressParseError {} 480 | 481 | impl From for AddressParseError { 482 | fn from(err: ParseIntError) -> AddressParseError { 483 | AddressParseError::ParseError(err) 484 | } 485 | } 486 | 487 | impl FromStr for Address { 488 | type Err = AddressParseError; 489 | 490 | fn from_str(s: &str) -> Result { 491 | let parts: Vec<&str> = s.split(',').collect(); 492 | if parts.len() != 4 { 493 | return Err(AddressParseError::InvalidFormat); 494 | } 495 | let street = parts[0].trim().to_string(); 496 | let zip = parts[1].trim().to_string(); 497 | let city = parts[2].trim().to_string(); 498 | let country = parts[3].trim().to_string(); 499 | Ok(Address { 500 | id: Uuid::new_v4(), 501 | street, 502 | city, 503 | country, 504 | state: None, 505 | zip, 506 | }) 507 | } 508 | } 509 | -------------------------------------------------------------------------------- /src/ui/input.rs: -------------------------------------------------------------------------------- 1 | use std::path::Path; 2 | 3 | use rustyline::completion::{Completer, Pair}; 4 | use rustyline::error::ReadlineError; 5 | use rustyline::highlight::Highlighter; 6 | use rustyline::hint::{Hinter, HistoryHinter}; 7 | use rustyline::validate::Validator; 8 | use rustyline::{Config, Editor, Result as RustylineResult}; 9 | use rustyline_derive::Helper; 10 | 11 | use crate::vault::entities::{Address, Credential, Expiry, Note, PaymentCard, Totp}; 12 | use inquire::{Confirm, CustomType, Password, Select, Text}; 13 | 14 | #[derive(Helper)] 15 | struct MultilineHelper { 16 | hinter: HistoryHinter, 17 | } 18 | 19 | impl Validator for MultilineHelper {} 20 | impl Highlighter for MultilineHelper {} 21 | 22 | impl Hinter for MultilineHelper { 23 | type Hint = String; 24 | 25 | fn hint(&self, line: &str, pos: usize, ctx: &rustyline::Context<'_>) -> Option { 26 | self.hinter.hint(line, pos, ctx) 27 | } 28 | } 29 | 30 | impl Completer for MultilineHelper { 31 | type Candidate = Pair; 32 | 33 | fn complete( 34 | &self, 35 | _: &str, 36 | pos: usize, 37 | _: &rustyline::Context<'_>, 38 | ) -> RustylineResult<(usize, Vec)> { 39 | Ok((pos, vec![])) // No completion, just return an empty vector 40 | } 41 | } 42 | 43 | pub fn ask_multiline_with_initial(question: &str, default_answer: Option<&str>) -> String { 44 | let config = Config::builder() 45 | .edit_mode(rustyline::EditMode::Emacs) 46 | .auto_add_history(true) 47 | .build(); 48 | let mut rl = Editor::with_config(config).unwrap(); 49 | let helper = MultilineHelper { 50 | hinter: HistoryHinter {}, 51 | }; 52 | rl.set_helper(Some(helper)); 53 | 54 | let initial_prompt = format!( 55 | "{}\n(Press Enter on an empty line to finish, Ctrl+D to finish editing, use \\\\n for newlines)\n> ", 56 | question 57 | ); 58 | let continuation_prompt = "| "; 59 | 60 | let default = default_answer.unwrap_or(""); 61 | 62 | let mut full_input = String::new(); 63 | let mut is_first_line = true; 64 | 65 | loop { 66 | let prompt = if is_first_line { 67 | &initial_prompt 68 | } else { 69 | continuation_prompt 70 | }; 71 | let readline = if is_first_line && !default.is_empty() { 72 | rl.readline_with_initial(prompt, (default, "")) 73 | } else { 74 | rl.readline(prompt) 75 | }; 76 | 77 | match readline { 78 | Ok(line) => { 79 | if !full_input.is_empty() { 80 | full_input.push('\n'); 81 | } 82 | full_input.push_str(&line.replace("\\\\n", "\n")); 83 | is_first_line = false; 84 | } 85 | Err(ReadlineError::Interrupted) => { 86 | println!("Interrupted"); 87 | return String::new(); 88 | } 89 | Err(ReadlineError::Eof) => { 90 | if !full_input.trim().is_empty() { 91 | break; 92 | } else if default_answer.is_some() { 93 | return default_answer.unwrap().to_string(); 94 | } else { 95 | return String::new(); 96 | } 97 | } 98 | Err(err) => { 99 | println!("Error: {:?}", err); 100 | return String::new(); 101 | } 102 | } 103 | } 104 | full_input.trim_end().to_string() 105 | } 106 | 107 | pub fn ask(question: &str) -> String { 108 | Text::new(question).prompt().unwrap() 109 | } 110 | 111 | pub fn ask_with_initial( 112 | question: &str, 113 | default_answer: Option<&str>, 114 | help_message: Option<&str>, 115 | ) -> String { 116 | let mut prompt = Text::new(question); 117 | if let Some(default) = default_answer { 118 | prompt = prompt.with_default(default); 119 | } 120 | if let Some(message) = help_message { 121 | prompt = prompt.with_help_message(message); 122 | } 123 | prompt.prompt().unwrap() 124 | } 125 | 126 | pub fn ask_with_initial_optional( 127 | question: &str, 128 | default_answer: Option<&str>, 129 | help_message: Option<&str>, 130 | optional: bool, 131 | ) -> Option { 132 | let mut prompt = Text::new(question); 133 | if let Some(default) = default_answer { 134 | prompt = prompt.with_default(default); 135 | } 136 | if let Some(message) = help_message { 137 | prompt = prompt.with_help_message(message); 138 | } 139 | let result = prompt.prompt().unwrap(); 140 | if !optional && result.is_empty() { 141 | ask_with_initial_optional(question, default_answer, help_message, optional) 142 | } else { 143 | if result == "" { 144 | None 145 | } else { 146 | Some(result) 147 | } 148 | } 149 | } 150 | 151 | pub fn ask_password(question: &str, help_message: Option<&str>) -> String { 152 | let mut prompt = Password::new(question); 153 | if let Some(message) = help_message { 154 | prompt = prompt.with_help_message(message); 155 | } 156 | prompt.prompt().unwrap() 157 | } 158 | 159 | pub fn ask_new_password(question: &str) -> Option { 160 | if ask_with_options("Do you want to change the password?", vec!["y", "n"]) == "n" { 161 | return None; 162 | } 163 | let prompt = Password::new(question); 164 | Some(prompt.prompt().unwrap()) 165 | } 166 | 167 | pub fn ask_number(question: &str) -> u64 { 168 | CustomType::::new(question) 169 | .with_error_message("Please enter a valid number") 170 | .prompt() 171 | .unwrap() 172 | } 173 | 174 | pub fn ask_credentials(password: &str) -> Credential { 175 | let service = ask("Enter URL or service"); 176 | let username = ask("Enter username"); 177 | Credential::new(None, password, &service, &username, None) 178 | } 179 | 180 | pub(crate) fn ask_modified_credential<'a>(the_match: &'a Credential) -> Credential { 181 | let service = ask_with_initial( 182 | "Enter URL or service", 183 | Some(the_match.service()), 184 | Some("Press enter and leave empty to keep the current value shown in parantheses"), 185 | ); 186 | let username = ask_with_initial( 187 | "Enter username", 188 | Some(the_match.username()), 189 | Some("Press enter and leave empty to keep the current value shown in parantheses"), 190 | ); 191 | let password = ask_new_password("Enter new password"); 192 | 193 | Credential::new( 194 | Some(the_match.uuid()), 195 | password.as_deref().unwrap_or(the_match.password()), 196 | &service, 197 | &username, 198 | None, 199 | ) 200 | } 201 | 202 | pub(crate) fn ask_modified_address(address: &Address) -> Address { 203 | let street = ask_with_initial("Enter street", Some(address.street()), None); 204 | let city = ask_with_initial("Enter city", Some(address.city()), None); 205 | let zip = ask_with_initial("Enter ZIP code", Some(address.zip()), None); 206 | let country = ask_with_initial("Enter country", Some(address.country()), None); 207 | let state = ask_with_initial_optional( 208 | "Enter state", 209 | address.state().map(|s| s.as_str()), 210 | None, 211 | true, 212 | ); 213 | 214 | Address::new( 215 | Some(address.id()), 216 | &street, 217 | &city, 218 | &country, 219 | state.as_deref(), 220 | &zip, 221 | ) 222 | } 223 | 224 | pub(crate) fn ask_modified_payment_info<'a>(payment_card: &'a PaymentCard) -> PaymentCard { 225 | let name = ask_with_initial("Enter card name", Some(payment_card.name()), None); 226 | let color = ask_with_initial_optional( 227 | "Enter color", 228 | payment_card.color().map(|s| s.as_str()), 229 | None, 230 | true, 231 | ); 232 | let cardholder_name = ask_with_initial( 233 | "Enter card holder name", 234 | Some(payment_card.name_on_card()), 235 | None, 236 | ); 237 | let card_number = ask_with_initial("Enter card number", Some(payment_card.number()), None); 238 | let expiration_month = ask_with_initial( 239 | "Enter card expiration month", 240 | Some(&payment_card.expiry().month.to_string()), 241 | None, 242 | ); 243 | let expiration_year = ask_with_initial( 244 | "Enter card expiration year", 245 | Some(&payment_card.expiry().year.to_string()), 246 | None, 247 | ); 248 | let security_code = ask_with_initial("Enter card cvv", Some(payment_card.cvv()), None); 249 | println!("Billing address:"); 250 | let address = match payment_card.billing_address() { 251 | Some(address) => ask_modified_address(&address), 252 | None => ask_address(), 253 | }; 254 | 255 | PaymentCard::new( 256 | Some(payment_card.id()), 257 | &name, 258 | &cardholder_name, 259 | &card_number, 260 | &security_code, 261 | Expiry { 262 | year: expiration_year.parse().unwrap(), 263 | month: expiration_month.parse().unwrap(), 264 | }, 265 | color.as_deref(), 266 | Some(&address), 267 | None, 268 | ) 269 | } 270 | 271 | pub(crate) fn ask_modified_note<'a>(the_match: &'a Note) -> Note { 272 | let title = ask_with_initial("Enter title", Some(the_match.title()), None); 273 | let content = ask_multiline_with_initial("Enter content", Some(the_match.content())); 274 | 275 | Note::new( 276 | Some(&the_match.id()), 277 | &title, 278 | &content, 279 | Some(the_match.last_modified()), 280 | ) 281 | } 282 | 283 | pub(crate) fn ask_modified_totp<'a>(the_match: &'a Totp) -> Totp { 284 | let label = ask_with_initial("Enter label", Some(the_match.label()), None); 285 | let issuer = ask_with_initial("Enter issuer", Some(the_match.issuer()), None); 286 | let secret = ask_with_initial("Secret", Some(the_match.secret()), None); 287 | let digits = ask_with_initial("Digits", Some(&the_match.digits().to_string()), None) 288 | .parse::() 289 | .unwrap(); 290 | let period = ask_with_initial("Period", Some(&the_match.period().to_string()), None) 291 | .parse::() 292 | .unwrap(); 293 | let algorithm = ask_with_initial("Algorithm", Some(the_match.algorithm()), None); 294 | 295 | Totp::new( 296 | Some(the_match.id()), 297 | &format_totp_url(&label, &secret, &issuer, period, &algorithm, digits), 298 | &label, 299 | &issuer, 300 | &secret, 301 | &algorithm, 302 | period as u64, 303 | digits, 304 | None, 305 | ) 306 | } 307 | 308 | pub fn ask_master_password(question: Option<&str>) -> String { 309 | if let Some(q) = question { 310 | ask_password(q, None) 311 | } else { 312 | ask_password("Please enter master password", None) 313 | } 314 | } 315 | 316 | pub fn ask_new_master_password() -> String { 317 | let pwd1 = ask_password("Please enter new master password", None); 318 | let pwd2 = ask_password("Retype new master password", None); 319 | if pwd1 != pwd2 { 320 | println!("Passwords do not match, please try again"); 321 | ask_new_master_password() 322 | } else { 323 | pwd1 324 | } 325 | } 326 | 327 | pub(crate) fn ask_totp_master_password() -> String { 328 | ask_password( 329 | "Please enter master password of the One Time Passwords vault", 330 | None, 331 | ) 332 | } 333 | 334 | pub fn ask_index( 335 | question: &str, 336 | max_index: i16, 337 | help_message: Option<&str>, 338 | ) -> Result { 339 | let answer = ask_with_initial(question, None, help_message); 340 | if answer == "q" { 341 | return Err(String::from("Quitting")); 342 | } 343 | if answer == "a" { 344 | return Ok(usize::MAX); 345 | } 346 | match answer.parse::() { 347 | Ok(num) => { 348 | if num >= 0 && num <= max_index as i16 { 349 | Ok(num.try_into().unwrap()) 350 | } else { 351 | Err(String::from("Invalid index")) 352 | } 353 | } 354 | Err(_) => Err(String::from("Invalid index")), 355 | } 356 | } 357 | 358 | fn ask_address() -> Address { 359 | println!("Enter billing address"); 360 | let street = ask("Enter street address"); 361 | let city = ask("Enter city"); 362 | let state = ask_with_initial_optional( 363 | "Enter state", 364 | None, 365 | Some("leave empty if not applicable"), 366 | true, 367 | ); 368 | let zip = ask("Enter postal code"); 369 | let country = ask("Enter country"); 370 | 371 | Address::new(None, &street, &city, &country, state.as_deref(), &zip) 372 | } 373 | 374 | pub fn ask_payment_info() -> PaymentCard { 375 | let name = ask_with_initial("Enter card name", None, None); 376 | let color = ask_with_initial_optional("Enter card color", None, None, true); 377 | let number = ask_with_initial("Enter card number", None, None); 378 | let name_on_card = ask_with_initial("Enter card holder name", None, None); 379 | let card_expiration_month = ask_number("Enter card expiration month"); 380 | let card_expiration_year = ask_number("Enter card expiration year"); 381 | let cvv = ask_with_initial( 382 | "Enter card cvv", 383 | None, 384 | Some("Card Verification Value: 3 or 4 digits that are usually located on the back of the card in the signature panel"), 385 | ); 386 | let address = ask_address(); 387 | 388 | PaymentCard::new( 389 | None, 390 | &name, 391 | &name_on_card, 392 | &number, 393 | &cvv, 394 | Expiry { 395 | month: card_expiration_month as u32, 396 | year: card_expiration_year as u32, 397 | }, 398 | color.as_deref(), 399 | Some(&address), 400 | None, 401 | ) 402 | } 403 | 404 | pub(crate) fn ask_note_info() -> Note { 405 | let title = ask_with_initial("Enter note title", None, None); 406 | let content = ask_multiline_with_initial("Enter note content", None); 407 | 408 | Note::new(None, &title, &content, None) 409 | } 410 | 411 | fn format_totp_url( 412 | label: &str, 413 | secret: &str, 414 | issuer: &str, 415 | period: u64, 416 | algo: &str, 417 | digits: u32, 418 | ) -> String { 419 | format!( 420 | "otpauth://totp/{}?secret={}&issuer={}&period={}&alorithm={}&digits={}", 421 | label, secret, &issuer, period, algo, digits 422 | ) 423 | } 424 | 425 | pub(crate) fn ask_totp_info() -> Totp { 426 | let label = ask_with_initial( 427 | "Enter label, typically formatted like :", 428 | None, 429 | None, 430 | ); 431 | 432 | let issuer = ask_with_initial("Enter issuer:", None, None); 433 | let secret = ask_with_initial( 434 | "Enter secret, or leave empty to keep the current secret:", 435 | None, 436 | None, 437 | ); 438 | 439 | println!("Add TOTP using settings settings (number of digits: 6, algo: SHA1, period: 30 seconds), or proceed to specify algorithm and other details (y/n)?"); 440 | let proceed = ask_with_initial( 441 | "Press y (yes) to add with defaults, n (no) to specify details.", 442 | Some("y"), 443 | None, 444 | ); 445 | 446 | if proceed.to_lowercase() == "n" || proceed.to_lowercase() == "no" { 447 | let digits = ask_number("Enter number of digits:"); 448 | let period = ask_number("Enter period:"); 449 | let algorithm = ask_algorithm(); 450 | 451 | Totp::new( 452 | None, 453 | &format_totp_url( 454 | &label, 455 | &secret, 456 | &issuer, 457 | period as u64, 458 | &algorithm, 459 | digits as u32, 460 | ), 461 | &label, 462 | &issuer, 463 | &secret, 464 | &algorithm, 465 | period as u64, 466 | digits as u32, 467 | None, 468 | ) 469 | } else { 470 | Totp::new( 471 | None, 472 | &format_totp_url(&label, &secret, &issuer, 30, "SHA1", 6), 473 | &label, 474 | &issuer, 475 | &secret, 476 | "SHA1", 477 | 30, 478 | 6, 479 | None, 480 | ) 481 | } 482 | } 483 | 484 | fn ask_algorithm() -> String { 485 | let valid_algos = vec!["SHA1", "SHA256", "SHA512"]; 486 | let mut algo = ask_with_initial( 487 | "Enter algorithm; SHA1 (default), SHA256, SHA512:", 488 | Some("SHA1"), 489 | None, 490 | ); 491 | 492 | while !valid_algos.contains(&algo.to_uppercase().as_str()) { 493 | println!("Invalid algorithm"); 494 | algo = ask_with_initial( 495 | "Enter algorithm; SHA1 (default), SHA256, SHA512:", 496 | Some("SHA1"), 497 | None, 498 | ); 499 | } 500 | algo 501 | } 502 | 503 | const VAULT_HELP_MESSAGE: &str = "You can specify your Dropbox folder here to make it easier to sync the vault between devices, or any other folder you want to store the vault in."; 504 | 505 | pub fn ask_vault_path(current_path: &str) -> String { 506 | ask_path( 507 | "Enter vault location", 508 | current_path, 509 | "store.kdbx", 510 | Some(VAULT_HELP_MESSAGE), 511 | ) 512 | } 513 | 514 | pub fn ask_totp_vault_path(current_path: &str) -> String { 515 | ask_path( 516 | "Enter vault location for Timed One Time Passwords, a.k.a. TOTPs", 517 | current_path, 518 | "totp.kdbx", 519 | Some(VAULT_HELP_MESSAGE), 520 | ) 521 | } 522 | 523 | pub fn ask_path( 524 | question: &str, 525 | default_answer: &str, 526 | default_filename: &str, 527 | help_message: Option<&str>, 528 | ) -> String { 529 | let location = ask_with_initial(question, Some(default_answer), help_message); 530 | if !parent_path_exists(&location) { 531 | println!("'{}' does not exist, please try again", &location); 532 | ask_path(question, default_answer, default_filename, help_message) 533 | } else { 534 | verify_file_path(&location, default_filename) 535 | } 536 | } 537 | 538 | pub fn ask_existing_path() -> String { 539 | let location = ask_with_initial("Enter path to existing vault file", None, None); 540 | if !Path::new(&location).is_file() { 541 | println!("File '{}' does not exist, please try again", &location); 542 | ask_existing_path() 543 | } else { 544 | location 545 | } 546 | } 547 | 548 | fn verify_file_path(location: &str, default_filename: &str) -> String { 549 | let file_path = Path::new(location); 550 | if file_path.is_file() { 551 | println!("File '{}' already exists, please try again", location); 552 | ask_path("Enter vault location", location, default_filename, None) 553 | } else { 554 | let path = Path::new(location); 555 | if path.is_dir() { 556 | let location_with_filename = path.join(default_filename); 557 | location_with_filename.to_str().unwrap().to_string() 558 | } else { 559 | location.to_string() 560 | } 561 | } 562 | } 563 | 564 | fn parent_path_exists(location: &str) -> bool { 565 | let file_path = Path::new(location); 566 | if file_path.is_dir() { 567 | return true; 568 | } 569 | if location.ends_with(".kdbx") { 570 | return file_path.parent().unwrap().exists(); 571 | } 572 | file_path.exists() 573 | } 574 | 575 | pub fn ask_keyfile_path(current_path: Option<&str>) -> Option { 576 | ask_with_initial_optional( 577 | "Enter location for the Keyfile to encrypt the vaults with, or leave empty to not use a keyfile", 578 | current_path, 579 | Some("The keyfile should be created with KeepassXC. To learn more about keyfiles, visit: https://keepass.info/help/base/keys.html#keyfiles"), 580 | true, 581 | ) 582 | } 583 | 584 | pub fn newline() { 585 | println!(); 586 | } 587 | 588 | pub fn ask_store_master_password() -> bool { 589 | Confirm::new( 590 | "Store master password in keychain? You can also save it later using the 'unlock' command.", 591 | ) 592 | .with_default(true) 593 | .prompt() 594 | .unwrap() 595 | } 596 | 597 | pub fn ask_open_existing_vault() -> bool { 598 | Select::new( 599 | "Do you want to create a new vault or open an existing one?", 600 | vec!["New", "Existing"], 601 | ) 602 | .prompt() 603 | .unwrap() 604 | == "Existing" 605 | } 606 | 607 | pub fn ask_open_existing_totp_vault() -> bool { 608 | Select::new( 609 | "Do you want to create a new TOTP vault or open an existing one?", 610 | vec!["New", "Existing"], 611 | ) 612 | .prompt() 613 | .unwrap() 614 | == "Existing" 615 | } 616 | 617 | pub fn ask_with_options(question: &str, options: Vec<&str>) -> String { 618 | Select::new(question, options).prompt().unwrap().to_string() 619 | } 620 | -------------------------------------------------------------------------------- /src/vault/keepass_vault.rs: -------------------------------------------------------------------------------- 1 | use crate::vault::entities::{Address, Credential, Error, Expiry, Note, PaymentCard, Totp}; 2 | use crate::vault::vault_trait::{NoteVault, PasswordVault, PaymentVault, TotpVault, Vault}; 3 | use chrono::{DateTime, NaiveDateTime, Utc}; 4 | use keepass_ng::db::{ 5 | group_get_children, node_is_entry, node_is_group, search_node_by_uuid, Database, Entry, Group, 6 | Node, NodeIterator, NodePtr, SerializableNodePtr, 7 | }; 8 | use keepass_ng::error::DatabaseSaveError; 9 | use keepass_ng::{error::DatabaseOpenError, DatabaseConfig, DatabaseKey}; 10 | 11 | use log::debug; 12 | use std::fs::{File, OpenOptions}; 13 | use std::path::Path; 14 | use std::str::FromStr; 15 | use uuid::Uuid; 16 | 17 | pub struct KeepassVault { 18 | password: String, 19 | db: Database, 20 | filepath: String, 21 | keyfile: Option, 22 | } 23 | 24 | impl From for Error { 25 | fn from(e: DatabaseOpenError) -> Self { 26 | Error { 27 | message: e.to_string(), 28 | } 29 | } 30 | } 31 | 32 | impl From for Error { 33 | fn from(e: DatabaseSaveError) -> Self { 34 | Error { 35 | message: e.to_string(), 36 | } 37 | } 38 | } 39 | 40 | impl From for Error { 41 | fn from(e: keepass_ng::error::Error) -> Self { 42 | Error { 43 | message: e.to_string(), 44 | } 45 | } 46 | } 47 | 48 | fn node_has_totp(node: &NodePtr) -> bool { 49 | let node = node.borrow(); 50 | let e = node.as_any().downcast_ref::().unwrap(); 51 | debug!( 52 | "Checking node for TOTP: {:?} {:?}", 53 | e.get_title(), 54 | e.get_otp() 55 | ); 56 | e.get_otp().is_ok() 57 | } 58 | 59 | impl KeepassVault { 60 | pub fn open( 61 | password: &str, 62 | filepath: &str, 63 | keyfile_path: Option, 64 | ) -> Result { 65 | debug!("Opening database '{}'", filepath); 66 | let db = Self::open_database(filepath, password, &keyfile_path)?; 67 | Ok(Self { 68 | password: String::from(password), 69 | db, 70 | filepath: filepath.to_string(), 71 | keyfile: keyfile_path, 72 | }) 73 | } 74 | 75 | pub fn new( 76 | filepath: &str, 77 | password: &str, 78 | keyfile: Option<&str>, 79 | ) -> Result { 80 | let mut db = Database::new(DatabaseConfig::default()); 81 | db.meta.database_name = Some("Passlane database".to_string()); 82 | 83 | let mut key = DatabaseKey::new().with_password(password); 84 | 85 | if let Some(keyfile_path) = keyfile { 86 | println!("Using keyfile '{}'", keyfile_path); 87 | let mut file = File::open(keyfile_path)?; 88 | key = key.with_keyfile(&mut file)?; 89 | } 90 | db.save(&mut File::create(filepath)?, key)?; 91 | 92 | Ok(KeepassVault { 93 | db, 94 | password: password.to_string(), 95 | filepath: filepath.to_string(), 96 | keyfile: keyfile.map(ToString::to_string), 97 | }) 98 | } 99 | 100 | fn get_root(&self) -> SerializableNodePtr { 101 | self.db.root.clone() 102 | } 103 | 104 | fn get_root_uuid(&self) -> Uuid { 105 | self.get_root().borrow().get_uuid() 106 | } 107 | 108 | fn save_database(&self) -> Result<(), DatabaseSaveError> { 109 | let mut file = OpenOptions::new() 110 | .read(true) 111 | .write(true) 112 | .create_new(!Path::new(&self.filepath).exists()) 113 | .open(&self.filepath) 114 | .unwrap(); 115 | 116 | let (_, key) = 117 | Self::get_database_key(&self.filepath, &self.password, &self.keyfile).unwrap(); 118 | debug!("Saving database to file '{}'", &self.filepath); 119 | 120 | self.db.save(&mut file, key) 121 | } 122 | 123 | fn open_database( 124 | filepath: &str, 125 | password: &str, 126 | keyfile: &Option, 127 | ) -> Result { 128 | if !Path::new(filepath).exists() { 129 | debug!( 130 | "Database file '{}' does not exist, creating new database", 131 | filepath 132 | ); 133 | return Ok(Database::new(DatabaseConfig::default())); 134 | } 135 | let (mut db_file, key) = Self::get_database_key(filepath, password, keyfile)?; 136 | let mut db = Database::open(&mut db_file, key)?; 137 | db.set_recycle_bin_enabled(false); 138 | Ok(db) 139 | } 140 | 141 | fn create_group(&self, parent_uuid: Uuid, group_name: &str) -> Option { 142 | self.db 143 | .create_new_group(parent_uuid, 0) 144 | .map(|node| { 145 | node.borrow_mut() 146 | .as_any_mut() 147 | .downcast_mut::() 148 | .map(|group| { 149 | group.set_title(Some(group_name)); 150 | group.get_uuid() 151 | }) 152 | }) 153 | .unwrap() 154 | } 155 | 156 | fn get_database_key( 157 | filepath: &str, 158 | password: &str, 159 | keyfile: &Option, 160 | ) -> Result<(File, DatabaseKey), DatabaseOpenError> { 161 | let db_file = File::open(filepath)?; 162 | let key = match keyfile { 163 | Some(kf) => { 164 | debug!("Using keyfile '{}' and password", kf); 165 | let file = &mut File::open(kf).expect("Failed to open keyfile"); 166 | DatabaseKey::new() 167 | .with_password(password) 168 | .with_keyfile(file) 169 | .unwrap() 170 | } 171 | None => DatabaseKey::new().with_password(password), 172 | }; 173 | Ok((db_file, key)) 174 | } 175 | 176 | fn load_credentials(&self, grep: Option<&str>) -> Vec { 177 | NodeIterator::new(&self.get_root()) 178 | .filter(node_is_entry) 179 | .map(Self::node_to_credential) 180 | .filter(|cred| { 181 | if let Some(grep) = &grep { 182 | if !cred 183 | .username() 184 | .to_lowercase() 185 | .contains(&grep.to_lowercase()) 186 | && !cred.service().to_lowercase().contains(&grep.to_lowercase()) 187 | { 188 | return false; 189 | } 190 | } 191 | true 192 | }) 193 | .collect() 194 | } 195 | 196 | fn load_totps(&self, grep: Option<&str>) -> Vec { 197 | NodeIterator::new(&self.get_root()) 198 | // .map(|node| {debug!("Node: {:?}", node); node}) 199 | .filter(node_is_entry) 200 | .filter(node_has_totp) 201 | .map(Self::node_to_totp) 202 | .filter(|totp| { 203 | if let Some(grep) = &grep { 204 | if !totp.label().to_lowercase().contains(&grep.to_lowercase()) 205 | && !totp.issuer().to_lowercase().contains(&grep.to_lowercase()) 206 | { 207 | return false; 208 | } 209 | } 210 | true 211 | }) 212 | .collect() 213 | } 214 | 215 | fn load_payments(&self) -> Vec { 216 | let payments_group_uuid = self.find_group("Payments").unwrap(); 217 | let payments_group = search_node_by_uuid(&self.get_root(), payments_group_uuid).unwrap(); 218 | NodeIterator::new(&payments_group) 219 | .filter(node_is_entry) 220 | .map(Self::node_to_payment) 221 | .collect() 222 | } 223 | 224 | fn load_notes(&self) -> Vec { 225 | let payments_group_uuid = self.find_group("Notes").unwrap(); 226 | let payments_group = search_node_by_uuid(&self.get_root(), payments_group_uuid).unwrap(); 227 | NodeIterator::new(&payments_group) 228 | .filter(node_is_entry) 229 | .map(Self::node_to_note) 230 | .collect() 231 | } 232 | 233 | fn node_to_credential(node: NodePtr) -> Credential { 234 | let (username, service, password, uuid, modified_date_time) = Self::get_node_values(node); 235 | Credential::new( 236 | Some(&uuid), 237 | &password, 238 | &service, 239 | &username, 240 | modified_date_time.map(|dt| DateTime::::from_naive_utc_and_offset(dt, Utc)), 241 | ) 242 | } 243 | 244 | fn node_to_totp(node: NodePtr) -> Totp { 245 | let totp = Self::get_node_totp_values(node); 246 | match totp { 247 | Err(e) => { 248 | panic!("Failed to convert node to TOTP: {}", e.message); 249 | } 250 | Ok(totp) => { 251 | let (url, label, issuer, secret, algorithm, period, digits, id, last_modified) = 252 | totp; 253 | Totp::new( 254 | Some(&id), 255 | &url, 256 | &label, 257 | &issuer, 258 | &secret, 259 | &algorithm, 260 | period, 261 | digits, 262 | last_modified.map(|dt| DateTime::::from_naive_utc_and_offset(dt, Utc)), 263 | ) 264 | } 265 | } 266 | } 267 | 268 | fn get_node_values(node: NodePtr) -> (String, String, String, Uuid, Option) { 269 | let node = node.borrow(); 270 | let e = node.as_any().downcast_ref::().unwrap(); 271 | let username = e.get_username().unwrap_or("(no username)"); 272 | let service = e.get_url().unwrap_or("(no service)"); 273 | let password = e.get_password().unwrap_or("(no password)"); 274 | let uuid = e.get_uuid(); 275 | let last_modified = e.get_times().get_last_modification(); 276 | ( 277 | username.to_string(), 278 | service.to_string(), 279 | password.to_string(), 280 | uuid, 281 | last_modified, 282 | ) 283 | } 284 | 285 | fn node_to_payment(node: NodePtr) -> PaymentCard { 286 | let (name, name_on_card, number, cvv, expiry, color, billing_address, id) = 287 | Self::get_node_payment_values(node).unwrap(); 288 | PaymentCard::new( 289 | Some(&id), 290 | &name, 291 | &name_on_card, 292 | &number, 293 | &cvv, 294 | Expiry::from_str(&expiry).unwrap(), 295 | color.as_deref(), 296 | Some(&Address::from_str(&billing_address).unwrap()), 297 | None, 298 | ) 299 | } 300 | 301 | fn node_to_note(node: NodePtr) -> Note { 302 | let (title, content, id, last_modified) = Self::get_node_note_values(node); 303 | Note::new( 304 | Some(&id), 305 | &title, 306 | &content, 307 | last_modified.map(|dt| DateTime::::from_naive_utc_and_offset(dt, Utc)), 308 | ) 309 | } 310 | 311 | fn get_node_payment_values( 312 | node: NodePtr, 313 | ) -> Option<( 314 | String, 315 | String, 316 | String, 317 | String, 318 | String, 319 | Option, 320 | String, 321 | Uuid, 322 | )> { 323 | let node = node.borrow(); 324 | let e = node.as_any().downcast_ref::().unwrap(); 325 | let note = e.get_notes()?; 326 | let name = e.get_title().unwrap_or("(no name)"); 327 | let name_on_card = Self::extract_value_from_note(note, 0, "Name on card"); 328 | let number = Self::extract_value_from_note(note, 1, "Number"); 329 | let cvv = Self::extract_value_from_note(note, 2, "CVV"); 330 | let expiry = Self::extract_value_from_note(note, 3, "Expiry"); 331 | let color = Self::extract_value_from_note_opt(note, 4, "Color"); 332 | let billing_address = Self::extract_value_from_note(note, 5, "Billing Address"); 333 | 334 | Some(( 335 | name.to_string(), 336 | name_on_card, 337 | number, 338 | cvv, 339 | expiry, 340 | color, 341 | billing_address, 342 | e.get_uuid(), 343 | )) 344 | } 345 | 346 | fn get_node_note_values(node: NodePtr) -> (String, String, Uuid, Option) { 347 | let node = node.borrow(); 348 | let e = node.as_any().downcast_ref::().unwrap(); 349 | let content = e.get_notes().unwrap_or(""); 350 | let title = e.get_title().unwrap_or("(no title)"); 351 | let last_modified = e.get_times().get_last_modification(); 352 | 353 | ( 354 | title.to_string(), 355 | content.to_string(), 356 | e.get_uuid(), 357 | last_modified, 358 | ) 359 | } 360 | 361 | fn extract_value_from_note_opt(note: &str, line: usize, name: &str) -> Option { 362 | let no_value = &format!("(no {name} on card)"); 363 | note.lines() 364 | .nth(line) 365 | .unwrap_or(no_value) 366 | .split(&format!("{name}: ")) 367 | .nth(1) 368 | .map(|v| String::from(v)) 369 | } 370 | 371 | fn extract_value_from_note(note: &str, line: usize, name: &str) -> String { 372 | let no_value = String::from(&format!("(no {name} on card)")); 373 | Self::extract_value_from_note_opt(note, line, name).unwrap_or(no_value) 374 | } 375 | 376 | fn get_node_totp_values( 377 | node: NodePtr, 378 | ) -> Result< 379 | ( 380 | String, 381 | String, 382 | String, 383 | String, 384 | String, 385 | u64, 386 | u32, 387 | Uuid, 388 | Option, 389 | ), 390 | Error, 391 | > { 392 | let node = node.borrow(); 393 | let e = node 394 | .as_any() 395 | .downcast_ref::() 396 | .ok_or(Error::new("Failed to downcast keepass node"))?; 397 | let otp = e 398 | .get_otp() 399 | .map_err(|e| Error::new(&format!("Failed to get OTP from keepass node: {:?}", e)))?; 400 | let url = e 401 | .get_raw_otp_value() 402 | .ok_or(Error::new("Failed to get URL from keepass node"))?; 403 | let last_modified = e.get_times().get_last_modification(); 404 | Ok(( 405 | String::from(url), 406 | otp.label.to_string(), 407 | String::from(&otp.issuer), 408 | otp.get_secret(), 409 | otp.algorithm.to_string(), 410 | otp.period, 411 | otp.digits, 412 | e.get_uuid(), 413 | last_modified, 414 | )) 415 | } 416 | 417 | fn get_groups(&self) -> Vec { 418 | let root = self.get_root(); 419 | group_get_children(&root) 420 | .unwrap() 421 | .iter() 422 | .filter(|node| node_is_group(node)) 423 | .cloned() 424 | .collect() 425 | } 426 | 427 | fn find_group(&self, group_name: &str) -> Option { 428 | let groups = self.get_groups(); 429 | let group: Vec<&NodePtr> = groups 430 | .iter() 431 | .filter(|node| node_is_group(node)) 432 | .filter(|node| { 433 | if let Some(entry) = node.borrow().as_any().downcast_ref::() { 434 | entry.get_title().unwrap() == group_name 435 | } else { 436 | false 437 | } 438 | }) 439 | .collect(); 440 | if !group.is_empty() { 441 | Some(group[0].borrow().get_uuid()) 442 | } else { 443 | None 444 | } 445 | } 446 | 447 | fn create_password_entry( 448 | &mut self, 449 | parent_uuid: &Uuid, 450 | credentials: &Credential, 451 | ) -> keepass_ng::Result> { 452 | self.db 453 | .create_new_entry(parent_uuid.clone(), 0) 454 | .map(|node| { 455 | node.borrow_mut() 456 | .as_any_mut() 457 | .downcast_mut::() 458 | .map(|entry| { 459 | entry.set_title(Some(credentials.service())); 460 | entry.set_username(Some(credentials.username())); 461 | entry.set_password(Some(credentials.password())); 462 | entry.set_url(Some(&credentials.service())); 463 | entry.get_uuid() 464 | }) 465 | }) 466 | } 467 | 468 | fn create_totp_entry( 469 | &mut self, 470 | parent_uuid: &Uuid, 471 | totp: &Totp, 472 | ) -> Result, Error> { 473 | Ok(self.db.create_new_entry(*parent_uuid, 0).map(|node| { 474 | node.borrow_mut() 475 | .as_any_mut() 476 | .downcast_mut::() 477 | .map(|entry| { 478 | entry.set_title(Some(totp.label())); 479 | entry.set_otp(totp.url()); 480 | entry.get_uuid() 481 | }) 482 | })?) 483 | } 484 | 485 | fn create_payment_entry( 486 | &mut self, 487 | parent_uuid: &Uuid, 488 | payment: &PaymentCard, 489 | ) -> keepass_ng::Result> { 490 | self.db.create_new_entry(parent_uuid.clone(), 0).map(|node| { 491 | let note = format!("Name on card: {}\nNumber: {}\nCVV: {}\nExpiry: {}\nColor: {}\nBilling Address: {}", 492 | payment.name_on_card(), 493 | payment.number(), 494 | payment.cvv(), 495 | payment.expiry_str(), 496 | payment.color_str(), 497 | payment.billing_address().as_ref().map(|a| a.to_string()).unwrap_or("".to_string()) 498 | ); 499 | node.borrow_mut().as_any_mut().downcast_mut::().map(|entry| { 500 | entry.set_title(Some(payment.name())); 501 | entry.set_notes(Some(¬e)); 502 | entry.get_uuid() 503 | }) 504 | }) 505 | } 506 | 507 | fn create_note_entry( 508 | &mut self, 509 | parent_uuid: &Uuid, 510 | note: &Note, 511 | ) -> keepass_ng::Result> { 512 | self.db 513 | .create_new_entry(parent_uuid.clone(), 0) 514 | .map(|node| { 515 | node.borrow_mut() 516 | .as_any_mut() 517 | .downcast_mut::() 518 | .map(|entry| { 519 | entry.set_title(Some(note.title())); 520 | entry.set_notes(Some(note.content())); 521 | entry.get_uuid() 522 | }) 523 | }) 524 | } 525 | 526 | fn do_delete(&mut self, uuid: &Uuid, save: bool) -> Result<(), Error> { 527 | debug!("Deleting with uuid '{}'", uuid); 528 | self.db.remove_node_by_uuid(*uuid)?; 529 | if save { 530 | self.save_database()?; 531 | } 532 | Ok(()) 533 | } 534 | fn find_or_create_group(&mut self, group_name: &str) -> Uuid { 535 | self.find_group(group_name) 536 | .unwrap_or_else(|| self.create_group(self.get_root_uuid(), group_name).unwrap()) 537 | } 538 | 539 | fn update_entry(&mut self, uuid: Uuid, update_fn: F) -> Result<(), Error> 540 | where 541 | F: FnOnce(&mut Entry), 542 | { 543 | let node = self.db.search_node_by_uuid(uuid); 544 | 545 | if let Some(node_ref) = node { 546 | { 547 | let mut node = node_ref.borrow_mut(); 548 | if let Some(entry) = node.as_any_mut().downcast_mut::() { 549 | update_fn(entry); 550 | entry.update_history(); 551 | } else { 552 | return Err(Error { 553 | message: "Node is not an Entry".to_string(), 554 | }); 555 | } 556 | } 557 | self.save_database()?; 558 | Ok(()) 559 | } else { 560 | Err(Error { 561 | message: format!("Entry with uuid '{}' not found", uuid), 562 | }) 563 | } 564 | } 565 | } 566 | 567 | impl PasswordVault for KeepassVault { 568 | fn get_master_password(&self) -> String { 569 | self.password.clone() 570 | } 571 | 572 | fn grep(&self, grep: Option<&str>) -> Vec { 573 | self.load_credentials(grep) 574 | } 575 | 576 | fn save_credentials(&mut self, credentials: &Vec) -> Result { 577 | let group = self.find_or_create_group("Passwords"); 578 | for c in credentials { 579 | self.create_password_entry(&group, c)?; 580 | } 581 | self.save_database()?; 582 | Ok(credentials.len() as i8) 583 | } 584 | 585 | fn save_one_credential(&mut self, credentials: Credential) -> Result<(), Error> { 586 | self.save_credentials(&vec![credentials])?; 587 | Ok(()) 588 | } 589 | 590 | fn update_credential(&mut self, credential: Credential) -> Result<(), Error> { 591 | let uuid = credential.uuid(); 592 | self.update_entry(*uuid, |entry| { 593 | entry.set_title(Some(credential.service())); 594 | entry.set_username(Some(credential.username())); 595 | entry.set_password(Some(credential.password())); 596 | entry.set_url(Some(credential.service())); 597 | }) 598 | } 599 | 600 | fn delete_credentials(&mut self, uuid: &Uuid) -> Result<(), Error> { 601 | self.do_delete(uuid, true)?; 602 | Ok(()) 603 | } 604 | 605 | fn delete_matching(&mut self, grep: &str) -> Result { 606 | let root = self.get_root(); 607 | let matching: Vec = NodeIterator::new(&root) 608 | .filter(node_is_entry) 609 | .filter(|node| { 610 | let node = node.borrow(); 611 | let e = node.as_any().downcast_ref::().unwrap(); 612 | let username = e.get_username().unwrap_or("(no username)"); 613 | let service = e.get_url().unwrap_or("(no service)"); 614 | username.contains(grep) || service.contains(grep) 615 | }) 616 | .collect(); 617 | // delete 618 | for node in &matching { 619 | self.do_delete(&node.borrow().get_uuid(), false)?; 620 | } 621 | self.save_database()?; 622 | Ok(matching.len() as i8) 623 | } 624 | } 625 | 626 | impl PaymentVault for KeepassVault { 627 | fn find_payments(&self) -> Vec { 628 | self.load_payments() 629 | } 630 | 631 | fn save_payment(&mut self, payment: PaymentCard) -> Result<(), Error> { 632 | let group = self.find_or_create_group("Payments"); 633 | self.create_payment_entry(&group, &payment) 634 | .expect("Failed to save payment"); 635 | self.save_database()?; 636 | Ok(()) 637 | } 638 | 639 | fn delete_payment(&mut self, id: &Uuid) -> Result<(), Error> { 640 | self.do_delete(id, true)?; 641 | Ok(()) 642 | } 643 | 644 | fn update_payment(&mut self, payment: PaymentCard) -> Result<(), Error> { 645 | let uuid = payment.id(); 646 | self.update_entry(*uuid, |entry| { 647 | let note = format!( 648 | "Name on card: {}\nNumber: {}\nCVV: {}\nExpiry: {}\nColor: {}\nBilling Address: {}", 649 | payment.name_on_card(), 650 | payment.number(), 651 | payment.cvv(), 652 | payment.expiry_str(), 653 | payment.color_str(), 654 | payment 655 | .billing_address() 656 | .as_ref() 657 | .map(|a| a.to_string()) 658 | .unwrap_or("".to_string()) 659 | ); 660 | 661 | entry.set_title(Some(payment.name())); 662 | entry.set_notes(Some(¬e)); 663 | }) 664 | } 665 | } 666 | 667 | impl NoteVault for KeepassVault { 668 | fn find_notes(&self) -> Vec { 669 | self.load_notes() 670 | } 671 | 672 | fn save_note(&mut self, note: &Note) -> Result<(), Error> { 673 | let group = self.find_or_create_group("Notes"); 674 | self.create_note_entry(&group, ¬e) 675 | .expect("Failed to save note"); 676 | self.save_database()?; 677 | Ok(()) 678 | } 679 | 680 | fn delete_note(&mut self, id: &Uuid) -> Result<(), Error> { 681 | self.do_delete(id, true) 682 | } 683 | 684 | fn update_note(&mut self, note: Note) -> Result<(), Error> { 685 | let uuid = note.id(); 686 | self.update_entry(uuid, |entry| { 687 | entry.set_title(Some(note.title())); 688 | entry.set_notes(Some(note.content())); 689 | }) 690 | } 691 | } 692 | 693 | impl TotpVault for KeepassVault { 694 | fn find_totp(&self, grep: Option<&str>) -> Vec { 695 | self.load_totps(grep) 696 | } 697 | 698 | fn save_totp(&mut self, totp: &Totp) -> Result<(), Error> { 699 | let group = self.db.root.borrow().get_uuid(); 700 | self.create_totp_entry(&group, &totp) 701 | .expect("Failed to save TOTP"); 702 | self.save_database()?; 703 | Ok(()) 704 | } 705 | 706 | fn delete_totp(&mut self, uuid: &Uuid) -> Result<(), Error> { 707 | self.do_delete(uuid, true) 708 | } 709 | 710 | fn update_totp(&mut self, totp: Totp) -> Result<(), Error> { 711 | let uuid = totp.id(); 712 | self.update_entry(*uuid, |entry| { 713 | entry.set_title(Some(totp.label())); 714 | entry.set_otp(totp.url()); 715 | }) 716 | } 717 | } 718 | 719 | impl Vault for KeepassVault {} 720 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------