Capstone: Build a Secure Password Manager
For the closing capstone, you'll build a command-line password manager that puts every security idea from this module on the table: master key derivation, authenticated encryption, secure memory handling, and a CLI that doesn't get in the way.
Architecture
The password manager has four layers:
- Vault: An encrypted file storing all credentials
- Crypto Engine: Key derivation, encryption, and decryption
- Secure Memory: Zeroing sensitive data after use
- CLI Interface: Commands for add, get, list, remove
Data Model
use serde::{Serialize, Deserialize};use std::collections::HashMap;use zeroize::Zeroizing; // with zeroize's "serde" feature enabled
#[derive(Serialize, Deserialize, Debug)]pub struct Vault { pub entries: HashMap<String, Credential>, pub created_at: String, pub modified_at: String,}
#[derive(Serialize, Deserialize, Debug, Clone)]pub struct Credential { pub username: String, pub password: Zeroizing<String>, // wiped when the Credential is dropped pub url: Option<String>, pub notes: Option<String>, pub created_at: String,}
impl Vault { pub fn new() -> Self { let now = chrono::Utc::now().to_rfc3339(); Vault { entries: HashMap::new(), created_at: now.clone(), modified_at: now, } }
pub fn add(&mut self, name: String, cred: Credential) { self.modified_at = chrono::Utc::now().to_rfc3339(); self.entries.insert(name, cred); }
pub fn get(&self, name: &str) -> Option<&Credential> { self.entries.get(name) }
pub fn remove(&mut self, name: &str) -> bool { self.modified_at = chrono::Utc::now().to_rfc3339(); self.entries.remove(name).is_some() }
pub fn list(&self) -> Vec<&String> { let mut names: Vec<_> = self.entries.keys().collect(); names.sort(); names }}Crypto Engine
use argon2::Argon2;use ring::aead::{self, Aad, LessSafeKey, Nonce, UnboundKey, AES_256_GCM};use ring::rand::{SecureRandom, SystemRandom};use zeroize::{Zeroize, Zeroizing};
const SALT_LEN: usize = 32;const NONCE_LEN: usize = 12;const KEY_LEN: usize = 32;
pub struct CryptoEngine { key: [u8; KEY_LEN], rng: SystemRandom,}
impl CryptoEngine { pub fn from_password(password: &str, salt: &[u8; SALT_LEN]) -> Self { let mut key = [0u8; KEY_LEN];
// Argon2::default() is Argon2id with the crate's default cost // (19 MiB of memory, 2 passes, 1 lane) Argon2::default() .hash_password_into(password.as_bytes(), salt, &mut key) .expect("Argon2 key derivation failed");
CryptoEngine { key, rng: SystemRandom::new(), } }
// `aad` is authenticated but not encrypted: the file header goes here, // so any edit to it makes decryption fail pub fn encrypt(&self, plaintext: &[u8], aad: &[u8]) -> Vec<u8> { let unbound_key = UnboundKey::new(&AES_256_GCM, &self.key).unwrap(); let key = LessSafeKey::new(unbound_key);
let mut nonce_bytes = [0u8; NONCE_LEN]; self.rng.fill(&mut nonce_bytes).unwrap(); let nonce = Nonce::assume_unique_for_key(nonce_bytes);
let mut ciphertext = plaintext.to_vec(); key.seal_in_place_append_tag(nonce, Aad::from(aad), &mut ciphertext) .unwrap();
let mut result = Vec::with_capacity(NONCE_LEN + ciphertext.len()); result.extend_from_slice(&nonce_bytes); result.extend_from_slice(&ciphertext); result }
pub fn decrypt(&self, data: &[u8], aad: &[u8]) -> Result<Zeroizing<Vec<u8>>, &'static str> { if data.len() < NONCE_LEN + aead::AES_256_GCM.tag_len() { return Err("Data too short"); }
let (nonce_bytes, ciphertext) = data.split_at(NONCE_LEN); let nonce_array: [u8; NONCE_LEN] = nonce_bytes .try_into() .map_err(|_| "Invalid nonce")?; let nonce = Nonce::assume_unique_for_key(nonce_array);
let unbound_key = UnboundKey::new(&AES_256_GCM, &self.key) .map_err(|_| "Invalid key")?; let key = LessSafeKey::new(unbound_key);
// Decrypt in a buffer that wipes itself, and shrink it to the plaintext let mut buf = Zeroizing::new(ciphertext.to_vec()); let plain_len = key.open_in_place(nonce, Aad::from(aad), &mut buf) .map_err(|_| "Decryption failed (wrong password or tampered file)")? .len(); buf[plain_len..].zeroize(); buf.truncate(plain_len); Ok(buf) }
pub fn generate_salt() -> [u8; SALT_LEN] { let rng = SystemRandom::new(); let mut salt = [0u8; SALT_LEN]; rng.fill(&mut salt).unwrap(); salt }}Argon2id is memory-hard. Each guess at the master password costs 19 MiB of RAM as well as CPU time, which is what blunts GPUs: they have thousands of cores but nowhere near enough fast memory to give each one its own 19 MiB. PBKDF2 with a high iteration count (OWASP suggests 600,000 for PBKDF2-HMAC-SHA256) is the fallback when Argon2 isn't available, but it only costs compute, which GPUs have in abundance.
Secure Memory with zeroize
The zeroize crate scrubs sensitive bytes out of RAM before the allocator gets to recycle them. Two tools cover most of it: Zeroizing<T> wraps a value and wipes it on drop, and a manual Drop handles fields like the key:
use zeroize::{Zeroize, Zeroizing};
impl Drop for CryptoEngine { fn drop(&mut self) { self.key.zeroize(); }}
// Every secret the program holds goes in a wrapper that wipes itself:// the master password, the serialised vault, the decrypted plaintextfn example(master: Zeroizing<String>) { let json: Zeroizing<String> = Zeroizing::new(String::from("{...}")); drop((master, json)); // both wiped here, not left for the allocator}Zeroing is best effort. It clears the buffers you can see, but a String that reallocated as it grew has already left an old copy behind, and the OS may have swapped a page to disk. It shrinks the window; it can't close it.
Vault File Format
use std::fs::{self, OpenOptions};use std::io::Write;use std::os::unix::fs::OpenOptionsExt;use std::path::Path;use zeroize::Zeroizing;
const MAGIC: &[u8; 4] = b"VPWD";const VERSION: u8 = 1;const PREFIX_LEN: usize = 4 + 1 + SALT_LEN; // magic, version, saltconst HEADER_LEN: usize = PREFIX_LEN + 4; // plus the u32 length field
pub struct VaultFile;
impl VaultFile { fn prefix(salt: &[u8; SALT_LEN]) -> Vec<u8> { let mut p = Vec::with_capacity(PREFIX_LEN); p.extend_from_slice(MAGIC); p.push(VERSION); p.extend_from_slice(salt); p }
pub fn save(vault: &Vault, engine: &CryptoEngine, salt: &[u8; SALT_LEN], path: &Path) -> Result<(), Box<dyn std::error::Error>> { let json = Zeroizing::new(serde_json::to_string(vault)?); let prefix = Self::prefix(salt); // The header is bound to the ciphertext as AAD let encrypted = engine.encrypt(json.as_bytes(), &prefix);
let mut file_data = prefix; file_data.extend_from_slice(&u32::try_from(encrypted.len())?.to_le_bytes()); file_data.extend_from_slice(&encrypted);
// Write a private temp file, flush it to disk, then rename over the // old vault: a crash leaves either the old file or the new one let tmp = path.with_extension("tmp"); let mut f = OpenOptions::new() .write(true).create_new(true).mode(0o600) .open(&tmp)?; f.write_all(&file_data)?; f.sync_all()?; fs::rename(&tmp, path)?; Ok(()) }
pub fn load(path: &Path, password: &str) -> Result<(Vault, CryptoEngine, [u8; SALT_LEN]), Box<dyn std::error::Error>> { let data = fs::read(path)?;
if data.len() < HEADER_LEN { return Err("File too short".into()); }
if &data[0..4] != MAGIC { return Err("Invalid vault file".into()); }
if data[4] != VERSION { return Err(format!("Unsupported version: {}", data[4]).into()); }
let salt: [u8; SALT_LEN] = data[5..PREFIX_LEN].try_into()?; let len_bytes: [u8; 4] = data[PREFIX_LEN..HEADER_LEN].try_into()?; let encrypted_len = u32::from_le_bytes(len_bytes) as usize;
// Never trust a length read from the file let end = HEADER_LEN.checked_add(encrypted_len).ok_or("Bad length")?; let encrypted = data.get(HEADER_LEN..end).ok_or("Truncated vault file")?;
let engine = CryptoEngine::from_password(password, &salt); let decrypted = engine.decrypt(encrypted, &data[..PREFIX_LEN]) .map_err(|e| -> Box<dyn std::error::Error> { e.into() })?;
let vault: Vault = serde_json::from_slice(&decrypted)?; Ok((vault, engine, salt)) }}The prefix (magic, version, salt) travels in the clear, but because it's passed to the cipher as AAD, changing a single byte of it makes decryption fail. The length field isn't covered, so load checks it against the bytes actually in the file.
Attack your own format before someone else does. A first draft of load sliced data[HEADER_LEN..HEADER_LEN + encrypted_len] straight from the length field, and the file is exactly the part an attacker can edit. The runner strips out the crypto and throws four doctored files at that slicing code, next to the checked version load now uses.
CLI Interface
use zeroize::Zeroizing;
// rpassword turns off terminal echo while you typefn read_password(prompt: &str) -> Zeroizing<String> { Zeroizing::new(rpassword::prompt_password(prompt).expect("failed to read password"))}
fn read_line(prompt: &str) -> String { use std::io::Write; eprint!("{}", prompt); std::io::stderr().flush().unwrap(); let mut line = String::new(); std::io::stdin().read_line(&mut line).unwrap(); line.trim().to_string()}
fn main() { let args: Vec<String> = std::env::args().collect(); let vault_path = std::path::Path::new("vault.pwdb");
match args.get(1).map(|s| s.as_str()) { Some("init") => { let password = read_password("Master password: "); let confirm = read_password("Confirm password: "); if *password != *confirm { eprintln!("Passwords do not match."); std::process::exit(1); }
let salt = CryptoEngine::generate_salt(); let engine = CryptoEngine::from_password(&password, &salt); let vault = Vault::new();
VaultFile::save(&vault, &engine, &salt, vault_path).unwrap(); println!("Vault created."); }
Some("add") => { let name = args.get(2).expect("Usage: pwmgr add <name>"); let password = read_password("Master password: "); let (mut vault, engine, salt) = VaultFile::load(vault_path, &password).unwrap();
let username = read_line("Username: "); let entry_password = read_password("Password for entry: ");
vault.add(name.clone(), Credential { username, password: entry_password, url: None, notes: None, created_at: chrono::Utc::now().to_rfc3339(), });
VaultFile::save(&vault, &engine, &salt, vault_path).unwrap(); println!("Added '{}'.", name); }
Some("get") => { let name = args.get(2).expect("Usage: pwmgr get <name>"); let password = read_password("Master password: "); let (vault, _, _) = VaultFile::load(vault_path, &password).unwrap();
match vault.get(name) { Some(cred) => { println!("Username: {}", cred.username); println!("Password: {}", *cred.password); } None => println!("No entry found for '{}'.", name), } }
Some("list") => { let password = read_password("Master password: "); let (vault, _, _) = VaultFile::load(vault_path, &password).unwrap();
let names = vault.list(); if names.is_empty() { println!("Vault is empty."); } else { for name in names { println!(" {}", name); } } }
_ => { println!("Usage: pwmgr <init|add|get|list> [name]"); } }}What You Built
This password manager demonstrates:
- Argon2id for key derivation from a master password
- AES-256-GCM for authenticated encryption of the vault, with the file header bound in as associated data
- Secure random for salt and nonce generation
- zeroize for wiping the derived key, the master password, the serialised vault and stored passwords from memory (on a best-effort basis)
- A versioned file format with magic bytes and salt storage, a length field that's checked before it's trusted, and atomic saves to a file only you can read
That wraps the security-focused Rust module. You've now got the toolkit for software that's memory-safe (the type system handles it) and cryptographically sound (well-reviewed libraries, used the way their authors intended).