Skip to content

Commit

Permalink
better protection of the key file
Browse files Browse the repository at this point in the history
it's created by default with read access only to the user and keygen
refuses to override a file that already exists
  • Loading branch information
glehmann committed Feb 4, 2024
1 parent 7235042 commit 3d9dba2
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 3 deletions.
4 changes: 2 additions & 2 deletions src/keygen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
16 changes: 15 additions & 1 deletion src/util.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -19,6 +21,18 @@ pub fn stdout_or_file(path: &Path) -> Result<Box<dyn Write>> {
})
}

pub fn stdout_or_private_file(path: &Path) -> Result<Box<dyn Write>> {
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(0o500);
Box::new(file_opts.open(path).path_ctx(path)?)
})
}

pub fn stdin_or_file(path: &Path) -> Result<BufReader<Box<dyn Read>>> {
Ok(if path == Path::new("-") {
BufReader::new(Box::new(stdin()))
Expand Down

0 comments on commit 3d9dba2

Please sign in to comment.