@@ -8,7 +8,7 @@ use minisign::{
88} ;
99use std:: {
1010 fs:: { self , File , OpenOptions } ,
11- io:: { BufReader , BufWriter , Write } ,
11+ io:: { BufReader , IsTerminal , Write } ,
1212 path:: { Path , PathBuf } ,
1313 str,
1414 time:: { SystemTime , UNIX_EPOCH } ,
@@ -23,20 +23,39 @@ pub struct KeyPair {
2323 pub sk : String ,
2424}
2525
26- fn create_file ( path : & Path ) -> crate :: Result < BufWriter < File > > {
27- if let Some ( parent) = path. parent ( ) {
28- fs:: create_dir_all ( parent) . fs_context ( "failed to create directory" , parent. to_path_buf ( ) ) ?;
26+ /// Writes the secret key to `path`, making sure it is only readable by the current user on Unix.
27+ fn write_secret_key ( path : & Path , contents : & str ) -> std:: io:: Result < ( ) > {
28+ let mut options = OpenOptions :: new ( ) ;
29+ options. write ( true ) . create ( true ) . truncate ( true ) ;
30+ #[ cfg( unix) ]
31+ {
32+ use std:: os:: unix:: fs:: OpenOptionsExt ;
33+ options. mode ( 0o600 ) ;
34+ }
35+ let mut file = options. open ( path) ?;
36+ // the mode above only applies to newly created files, so also restrict an existing one
37+ #[ cfg( unix) ]
38+ {
39+ use std:: os:: unix:: fs:: PermissionsExt ;
40+ file. set_permissions ( fs:: Permissions :: from_mode ( 0o600 ) ) ?;
2941 }
30- let file = File :: create ( path ) . fs_context ( "failed to create file" , path . to_path_buf ( ) ) ?;
31- Ok ( BufWriter :: new ( file) )
42+ file. write_all ( contents . as_bytes ( ) ) ?;
43+ file. flush ( )
3244}
3345
3446/// Generate base64 encoded keypair
3547pub fn generate_key ( password : Option < String > ) -> crate :: Result < KeyPair > {
36- let KP { pk, sk } = KP :: generate_encrypted_keypair ( password) . unwrap ( ) ;
37-
38- let pk_box_str = pk. to_box ( ) . unwrap ( ) . to_string ( ) ;
39- let sk_box_str = sk. to_box ( None ) . unwrap ( ) . to_string ( ) ;
48+ let KP { pk, sk } =
49+ KP :: generate_encrypted_keypair ( password) . context ( "failed to generate key pair" ) ?;
50+
51+ let pk_box_str = pk
52+ . to_box ( )
53+ . context ( "failed to encode public key" ) ?
54+ . to_string ( ) ;
55+ let sk_box_str = sk
56+ . to_box ( None )
57+ . context ( "failed to encode secret key" ) ?
58+ . to_string ( ) ;
4059
4160 let encoded_pk = base64:: engine:: general_purpose:: STANDARD . encode ( pk_box_str) ;
4261 let encoded_sk = base64:: engine:: general_purpose:: STANDARD . encode ( sk_box_str) ;
@@ -72,34 +91,23 @@ where
7291 let pubkey_path = format ! ( "{}.pub" , sk_path. display( ) ) ;
7392 let pk_path = Path :: new ( & pubkey_path) ;
7493
75- if sk_path. exists ( ) {
76- if !force {
77- crate :: error:: bail!(
78- "Key generation aborted:\n {} already exists\n If you really want to overwrite the existing key pair, add the --force switch to force this operation." ,
79- sk_path. display( )
80- ) ;
81- } else {
82- std:: fs:: remove_file ( sk_path)
83- . fs_context ( "failed to remove secret key file" , sk_path. to_path_buf ( ) ) ?;
94+ if !force {
95+ for path in [ sk_path, pk_path] {
96+ if path. exists ( ) {
97+ crate :: error:: bail!(
98+ "Key generation aborted:\n {} already exists\n If you really want to overwrite the existing key pair, add the --force switch to force this operation." ,
99+ path. display( )
100+ ) ;
101+ }
84102 }
85103 }
86104
87- if pk_path. exists ( ) {
88- std:: fs:: remove_file ( pk_path)
89- . fs_context ( "failed to remove public key file" , pk_path. to_path_buf ( ) ) ?;
105+ if let Some ( parent) = sk_path. parent ( ) {
106+ fs:: create_dir_all ( parent) . fs_context ( "failed to create directory" , parent. to_path_buf ( ) ) ?;
90107 }
91108
92- let write_file = |mut writer : BufWriter < File > , contents : & str | -> std:: io:: Result < ( ) > {
93- write ! ( writer, "{contents:}" ) ?;
94- writer. flush ( ) ?;
95- Ok ( ( ) )
96- } ;
97-
98- write_file ( create_file ( sk_path) ?, key)
99- . fs_context ( "failed to write secret key" , sk_path. to_path_buf ( ) ) ?;
100-
101- write_file ( create_file ( pk_path) ?, pubkey)
102- . fs_context ( "failed to write public key" , pk_path. to_path_buf ( ) ) ?;
109+ write_secret_key ( sk_path, key) . fs_context ( "failed to write secret key" , sk_path. to_path_buf ( ) ) ?;
110+ fs:: write ( pk_path, pubkey) . fs_context ( "failed to write public key" , pk_path. to_path_buf ( ) ) ?;
103111
104112 Ok ( (
105113 fs:: canonicalize ( sk_path) . fs_context (
@@ -139,14 +147,19 @@ where
139147 bin_path. with_extension ( "sig" )
140148 } ;
141149
142- let mut trusted_comment = format ! (
143- "timestamp:{}\t file:{}" ,
144- unix_timestamp( ) ,
145- bin_path. file_name( ) . unwrap( ) . to_string_lossy( )
146- ) ;
150+ let file_name = bin_path
151+ . file_name ( )
152+ . with_context ( || format ! ( "{} is not a file path" , bin_path. display( ) ) ) ?
153+ . to_string_lossy ( ) ;
154+ // the trusted comment is a single line of tab separated fields, so a value carrying
155+ // either separator would produce a signature we cannot parse back
156+ if file_name. contains ( [ '\t' , '\r' , '\n' ] ) {
157+ crate :: error:: bail!(
158+ "the file {file_name:?} cannot be signed because its name contains a tab or newline"
159+ ) ;
160+ }
161+ let mut trusted_comment = format ! ( "timestamp:{}\t file:{file_name}" , unix_timestamp( ) ) ;
147162 if let Some ( version) = version {
148- // the trusted comment is a single line of tab separated fields, so a version carrying
149- // either separator would produce a signature we cannot parse back
150163 if version. contains ( [ '\t' , '\r' , '\n' ] ) {
151164 crate :: error:: bail!(
152165 "the app version {version:?} cannot be signed because it contains a tab or newline"
@@ -181,14 +194,24 @@ where
181194
182195/// Gets the updater secret key from the given private key and password.
183196///
184- /// If `password` is `None`, a password is going to be prompted interactively.
197+ /// If `password` is `None`, a password is going to be prompted interactively,
198+ /// or an empty password is assumed when stdin is not a terminal.
185199pub fn secret_key < S : AsRef < [ u8 ] > > (
186200 private_key : S ,
187- password : Option < String > ,
201+ mut password : Option < String > ,
188202) -> crate :: Result < SecretKey > {
189203 let decoded_secret = decode_key ( private_key) . context ( "failed to decode base64 secret key" ) ?;
190204 let sk_box =
191205 SecretKeyBox :: from_string ( & decoded_secret) . context ( "failed to load updater private key" ) ?;
206+ if password. is_none ( ) {
207+ if std:: io:: stdin ( ) . is_terminal ( ) {
208+ log:: info!( "Decrypting updater private key, expect a prompt for password" ) ;
209+ } else {
210+ // the password prompt needs a terminal, so assume the key has no password
211+ log:: info!( "No updater private key password provided, assuming an empty password" ) ;
212+ password. replace ( String :: new ( ) ) ;
213+ }
214+ }
192215 let sk = sk_box
193216 . into_secret_key ( password)
194217 . context ( "incorrect updater private key password" ) ?;
@@ -284,6 +307,49 @@ mod tests {
284307 assert ! ( sign_file( & secret_key, & path, Some ( "1.0.0\n tampered" ) ) . is_err( ) ) ;
285308 }
286309
310+ #[ test]
311+ fn rejects_file_name_that_breaks_the_trusted_comment ( ) {
312+ let dir = tempfile:: tempdir ( ) . unwrap ( ) ;
313+ // the name is validated before the file is opened, so it does not need to exist
314+ // (Windows does not allow tabs in file names at all)
315+ let path = dir. path ( ) . join ( "app\t file:evil.txt" ) ;
316+
317+ let secret_key =
318+ secret_key ( PRIVATE_KEY , Some ( "" . into ( ) ) ) . expect ( "failed to resolve secret key" ) ;
319+ let Err ( error) = sign_file ( & secret_key, & path, None ) else {
320+ panic ! ( "expected signing to fail" ) ;
321+ } ;
322+ assert ! ( error. to_string( ) . contains( "tab or newline" ) , "{error}" ) ;
323+ }
324+
325+ #[ test]
326+ fn save_keypair_refuses_to_overwrite_without_force ( ) {
327+ let dir = tempfile:: tempdir ( ) . unwrap ( ) ;
328+ let sk_path = dir. path ( ) . join ( "key" ) ;
329+ let pk_path = dir. path ( ) . join ( "key.pub" ) ;
330+
331+ // only the public key exists: it must be kept
332+ std:: fs:: write ( & pk_path, "old public" ) . unwrap ( ) ;
333+ assert ! ( save_keypair( false , & sk_path, "secret" , "public" ) . is_err( ) ) ;
334+ assert_eq ! ( std:: fs:: read_to_string( & pk_path) . unwrap( ) , "old public" ) ;
335+ assert ! ( !sk_path. exists( ) ) ;
336+
337+ save_keypair ( true , & sk_path, "secret" , "public" ) . unwrap ( ) ;
338+ assert_eq ! ( std:: fs:: read_to_string( & sk_path) . unwrap( ) , "secret" ) ;
339+ assert_eq ! ( std:: fs:: read_to_string( & pk_path) . unwrap( ) , "public" ) ;
340+
341+ assert ! ( save_keypair( false , & sk_path, "secret2" , "public2" ) . is_err( ) ) ;
342+ assert_eq ! ( std:: fs:: read_to_string( & sk_path) . unwrap( ) , "secret" ) ;
343+
344+ #[ cfg( unix) ]
345+ {
346+ use std:: os:: unix:: fs:: PermissionsExt ;
347+ let mode = |p : & Path | std:: fs:: metadata ( p) . unwrap ( ) . permissions ( ) . mode ( ) & 0o777 ;
348+ assert_eq ! ( mode( & sk_path) , 0o600 ) ;
349+ assert_eq ! ( mode( & pk_path) , 0o644 ) ;
350+ }
351+ }
352+
287353 // This tests the newly generated keys with empty string password works
288354 // minisign >=0.7.4,<=0.8.0 generate keys unencrypted if the password is empty but is marked encrypted hence unusable
289355 #[ test]
0 commit comments