//! seal-device: put this Mac on an object as a device that may open its vault, //! without the Mac app. Signs in once (keeping the device credential in //! --token-file, mode 600), then runs one vault pass: the Mac's key is minted //! into the login Keychain and published, and the pass says `waiting` with the //! fingerprint to approve in Keys › Devices, or `open`. //! //! seal-device --base --device-id --name \ //! --token-file [--key-file ] [--phone-file --code-file ] //! [--recovery-code-file ] //! //! --recovery-code-file names a file holding the person's recovery code: a Mac //! still waiting opens the vault with it and writes its own row approved, with //! no phone at hand (e2e rulings R7c). The code is read, used and dropped. //! //! --devices list names every device key the object holds (id, name, //! fingerprint, whether it opens the vault). --approve lets a //! waiting device in from this Mac, once this Mac opens the vault: the wrap is //! written for that device's published key and its fingerprint is printed, to //! be matched against the one the device shows. //! //! Nothing secret is printed: no credential, no code, no number. use std::os::unix::fs::OpenOptionsExt; use std::io::Write; use std::path::PathBuf; use std::process::ExitCode; use cotton_mac::object::ObjectClient; use cotton_mac::vault::{tool_keyring, ImporterVault, Pass}; const USAGE: &str = "seal-device --base --device-id --name --token-file [--key-file ] [--phone-file --code-file ] [--recovery-code-file ] [--devices list] [--approve ] [--refuse-row ]..."; struct Args { base: String, device_id: String, name: String, token_file: PathBuf, key_file: Option, phone_file: Option, code_file: Option, recovery_code_file: Option, devices: bool, approve: Option, refuse_rows: Vec, } fn parse(argv: &[String]) -> Result { let (mut base, mut device_id, mut name, mut token_file, mut phone_file, mut code_file) = (None, None, None, None, None, None); let mut key_file = None; let mut recovery_code_file = None; let (mut devices, mut approve) = (false, None); let mut refuse_rows = Vec::new(); let mut it = argv.iter(); while let Some(flag) = it.next() { let value = it.next().ok_or_else(|| format!("{flag} needs a value"))?.clone(); match flag.as_str() { "--base" => base = Some(value.trim_end_matches('/').to_string()), "--device-id" => device_id = Some(value), "--name" => name = Some(value), "--token-file" => token_file = Some(PathBuf::from(value)), "--key-file" => key_file = Some(PathBuf::from(value)), "--phone-file" => phone_file = Some(PathBuf::from(value)), "--code-file" => code_file = Some(PathBuf::from(value)), "--recovery-code-file" => recovery_code_file = Some(PathBuf::from(value)), "--devices" => devices = true, "--approve" => approve = Some(value), "--refuse-row" => refuse_rows.push(value), other => return Err(format!("unknown argument {other}")), } } Ok(Args { base: base.ok_or("--base is needed")?, device_id: device_id.ok_or("--device-id is needed")?, name: name.ok_or("--name is needed")?, token_file: token_file.ok_or("--token-file is needed")?, key_file, phone_file, code_file, recovery_code_file, devices, approve, refuse_rows, }) } fn held(path: &PathBuf) -> Result { Ok(std::fs::read_to_string(path).map_err(|e| format!("{} could not be read: {e}", path.display()))?.trim().to_string()) } fn go(args: Args) -> Result { let bare = ObjectClient::new(args.base.clone(), None).map_err(|e| e.to_string())?; if !args.token_file.exists() { let phone = held(args.phone_file.as_ref().ok_or("no credential kept yet: --phone-file and --code-file are needed")?)?; let code_file = args.code_file.as_ref().ok_or("no credential kept yet: --code-file is needed")?; // A code that is texted exists only after the asking: a code file that is not there yet is // waited for, ten minutes at most, so the person can read the text and hand the code over. let waits = !code_file.exists(); let asked = bare.ask_code(&phone, &args.device_id).map_err(|e| format!("the code could not be asked: {e}"))?; if waits { println!("code asked: waiting for {}", code_file.display()); let until = std::time::Instant::now() + std::time::Duration::from_secs(600); while !code_file.exists() { if std::time::Instant::now() > until { return Err("no code came in ten minutes".into()); } std::thread::sleep(std::time::Duration::from_secs(2)); } } let code = held(code_file)?; let signed = bare.sign_in(&asked.database_id, &asked.challenge_id, &code, &args.device_id).map_err(|e| format!("the sign-in was refused: {e}"))?; let mut file = std::fs::OpenOptions::new() .write(true) .create_new(true) .mode(0o600) .open(&args.token_file) .map_err(|e| format!("{} could not be written: {e}", args.token_file.display()))?; file.write_all(signed.credential.as_bytes()).map_err(|e| e.to_string())?; println!("signed in: database {}", signed.database_id); } let object = bare.with_token(Some(held(&args.token_file)?)); let keyring = tool_keyring(&args.device_id, args.key_file.as_deref()); let vault = ImporterVault::new(keyring.as_ref(), &args.device_id, &args.name); let fingerprint = vault.fingerprint().map_err(|e| e.to_string())?; let mut pass = vault.pass(&object).map_err(|e| e.to_string())?; if let (Pass::Waiting { .. }, Some(file)) = (&pass, &args.recovery_code_file) { let code = zeroize::Zeroizing::new(held(file)?); vault.open_by_code(&object, &object, &code).map_err(|e| format!("the recovery code did not open the vault: {e}"))?; pass = vault.pass(&object).map_err(|e| e.to_string())?; } let line = pass.line(&fingerprint); println!("vault {}: fingerprint {} ({})", line.state, fingerprint, line.detail); if let Some(other) = &args.approve { let approved = vault.approve(&object, other).map_err(|e| e.to_string())?; println!("approved {other}: fingerprint {approved}"); } for row in &args.refuse_rows { refuse_row(&object, row)?; } if args.devices { list(&object)?; } Ok(matches!(pass, Pass::Open(_))) } /// Turn one waiting request away by its row id: the row goes, and the device may ask again. A row that opens the vault is left alone. fn refuse_row(object: &ObjectClient, row_id: &str) -> Result<(), String> { let mut cursor: Option = None; loop { let page = object.sync_page(0, &[cotton_mac::vault::VAULT_KEY_TABLE], cursor.as_deref()).map_err(|e| e.to_string())?; for row in page.get("rows").and_then(|rows| rows.as_array()).into_iter().flatten() { if row.get("id").and_then(|id| id.as_str()) != Some(row_id) || row.get("deleted").and_then(|d| d.as_bool()) == Some(true) { continue; } if row.get("data").and_then(|d| d.get("wrapped_vmk")).and_then(|v| v.as_str()).is_some() { return Err(format!("row {row_id} opens the vault; it is not refused here")); } object.act(cotton_mac::object::Act::Delete, cotton_mac::vault::VAULT_KEY_TABLE, row_id, &serde_json::json!({})).map_err(|e| e.to_string())?; println!("refused row {row_id}"); return Ok(()); } match page.get("next").and_then(|next| next.as_str()) { Some(next) => cursor = Some(next.to_string()), None => return Err(format!("no waiting row {row_id}")), } } } /// Every device key the object holds: id, name, fingerprint, and whether the vault key is wrapped for it. fn list(object: &ObjectClient) -> Result<(), String> { let mut cursor: Option = None; loop { let page = object.sync_page(0, &[cotton_mac::vault::VAULT_KEY_TABLE], cursor.as_deref()).map_err(|e| e.to_string())?; for row in page.get("rows").and_then(|rows| rows.as_array()).into_iter().flatten() { if row.get("deleted").and_then(|d| d.as_bool()) == Some(true) { continue; } let Some(data) = row.get("data").and_then(|d| d.as_object()) else { continue }; let text = |key: &str| data.get(key).and_then(|v| v.as_str()).unwrap_or_default(); let state = if data.get("wrapped_vmk").and_then(|v| v.as_str()).is_some() { "opens" } else { "waiting" }; let print = cotton_core::vault::wrap::fingerprint(text("public_key")).unwrap_or_default(); let stamp = |key: &str| row.get(key).map(|v| v.to_string()).unwrap_or_default(); println!("device {} | {} | {} | {} | row {} | made {} | changed {}", text("device_id"), text("name"), print, state, stamp("id"), stamp("created_at"), stamp("updated_at")); } match page.get("next").and_then(|next| next.as_str()) { Some(next) => cursor = Some(next.to_string()), None => return Ok(()), } } } fn main() -> ExitCode { let argv: Vec = std::env::args().skip(1).collect(); let args = match parse(&argv) { Ok(args) => args, Err(why) => { eprintln!("{why}\n{USAGE}"); return ExitCode::from(2); } }; match go(args) { Ok(true) => ExitCode::SUCCESS, Ok(false) => ExitCode::from(1), Err(why) => { eprintln!("seal-device: {why}"); ExitCode::from(3) } } }