From 7151b9223961bcc47381c04d730d56ea5831fb9e Mon Sep 17 00:00:00 2001 From: Michael Vines Date: Tue, 19 Nov 2019 18:26:21 -0700 Subject: [PATCH] Don't create keypair files with r+go (#7051) --- cli/src/cli.rs | 4 ++-- sdk/src/signature.rs | 43 +++++++++++++++++++++++++++++++++++-------- 2 files changed, 37 insertions(+), 10 deletions(-) diff --git a/cli/src/cli.rs b/cli/src/cli.rs index f13b89a41..38b4ba857 100644 --- a/cli/src/cli.rs +++ b/cli/src/cli.rs @@ -1482,7 +1482,7 @@ mod tests { use serde_json::Value; use solana_client::mock_rpc_client_request::SIGNATURE; use solana_sdk::{ - signature::{gen_keypair_file, read_keypair_file}, + signature::{read_keypair_file, write_keypair_file}, transaction::TransactionError, }; use std::path::PathBuf; @@ -1540,7 +1540,7 @@ mod tests { // Test Balance Subcommand, incl pubkey and keypair-file inputs let keypair_file = make_tmp_path("keypair_file"); - gen_keypair_file(&keypair_file).unwrap(); + write_keypair_file(&Keypair::new(), &keypair_file).unwrap(); let keypair = read_keypair_file(&keypair_file).unwrap(); let test_balance = test_commands.clone().get_matches_from(vec![ "test", diff --git a/sdk/src/signature.rs b/sdk/src/signature.rs index da2394528..c25039810 100644 --- a/sdk/src/signature.rs +++ b/sdk/src/signature.rs @@ -9,7 +9,7 @@ use serde_json; use std::{ borrow::{Borrow, Cow}, error, fmt, - fs::{self, File}, + fs::{self, File, OpenOptions}, io::{Read, Write}, mem, path::Path, @@ -155,7 +155,22 @@ pub fn write_keypair_file( if let Some(outdir) = Path::new(outfile).parent() { fs::create_dir_all(outdir)?; } - let mut f = File::create(outfile)?; + + let mut f = { + #[cfg(not(unix))] + { + OpenOptions::new() + } + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + OpenOptions::new().mode(0o600) + } + } + .write(true) + .create_new(true) + .open(outfile)?; + write_keypair(keypair, &mut f) } @@ -170,10 +185,6 @@ pub fn keypair_from_seed(seed: &[u8]) -> Result> Ok(keypair) } -pub fn gen_keypair_file(outfile: &str) -> Result> { - write_keypair_file(&Keypair::new(), outfile) -} - #[cfg(test)] mod tests { use super::*; @@ -188,15 +199,31 @@ mod tests { } #[test] - fn test_gen_keypair_file() { + fn test_write_keypair_file() { let outfile = tmp_file_path("test_gen_keypair_file.json"); - let serialized_keypair = gen_keypair_file(&outfile).unwrap(); + let serialized_keypair = write_keypair_file(&Keypair::new(), &outfile).unwrap(); let keypair_vec: Vec = serde_json::from_str(&serialized_keypair).unwrap(); assert!(Path::new(&outfile).exists()); assert_eq!( keypair_vec, read_keypair_file(&outfile).unwrap().to_bytes().to_vec() ); + + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + assert_eq!( + File::open(&outfile) + .expect("open") + .metadata() + .expect("metadata") + .permissions() + .mode() + & 0o777, + 0o600 + ); + } + assert_eq!( read_keypair_file(&outfile).unwrap().pubkey().as_ref().len(), mem::size_of::()