From 40529b1d2ae32bf41f41a1418c7fc3d677f83698 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ga=C3=ABtan=20Lehmann?= Date: Sun, 4 Feb 2024 09:08:32 +0100 Subject: [PATCH] better protection of the key file it's created by default with read access only to the user and keygen refuses to override a file that already exists --- src/keygen.rs | 4 ++-- src/util.rs | 16 +++++++++++++++- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/src/keygen.rs b/src/keygen.rs index 2f90c15..3ef1c23 100644 --- a/src/keygen.rs +++ b/src/keygen.rs @@ -3,11 +3,11 @@ use age::x25519::Identity; use crate::cli::KeygenArgs; use crate::error::{IOResultExt, Result}; -use crate::util::stdout_or_file; +use crate::util::{stdout_or_file, stdout_or_private_file}; pub fn keygen(args: &KeygenArgs) -> Result<()> { let key = Identity::generate(); - let mut output = stdout_or_file(&args.output)?; + let mut output = stdout_or_private_file(&args.output)?; writeln!(output, "{}", key.to_string().expose_secret()).path_ctx(&args.output)?; info!("Public key: {}", key.to_public()); if let Some(ref public) = args.public { diff --git a/src/util.rs b/src/util.rs index 30fc7be..75bb03e 100644 --- a/src/util.rs +++ b/src/util.rs @@ -1,5 +1,7 @@ -use std::fs::File; +use std::fs::{File, OpenOptions}; use std::io::{stdin, stdout, BufRead, BufReader, Read, Write}; +#[cfg(unix)] +use std::os::unix::fs::OpenOptionsExt; use std::path::Path; use std::path::PathBuf; use std::str::FromStr; @@ -19,6 +21,18 @@ pub fn stdout_or_file(path: &Path) -> Result> { }) } +pub fn stdout_or_private_file(path: &Path) -> Result> { + Ok(if path == Path::new("-") { + Box::new(stdout()) + } else { + let mut file_opts = OpenOptions::new(); + file_opts.write(true).create_new(true); + #[cfg(unix)] + file_opts.mode(0o600); + Box::new(file_opts.open(path).path_ctx(path)?) + }) +} + pub fn stdin_or_file(path: &Path) -> Result>> { Ok(if path == Path::new("-") { BufReader::new(Box::new(stdin()))