Skip to content

Commit ff7cd8d

Browse files
authored
fix(cli): harden updater key generation and signing (#16118)
* fix(cli): harden updater key generation and signing * cr
1 parent ece0df7 commit ff7cd8d

5 files changed

Lines changed: 122 additions & 53 deletions

File tree

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
"tauri-cli": patch:sec
3+
"@tauri-apps/cli": patch:sec
4+
---
5+
6+
`tauri signer generate --write-keys` now creates the private key with owner-only permissions (0600) on Unix and refuses to overwrite either the private or the public key file without `--force`. Updater signing now rejects file names containing tabs or newlines (which would corrupt the signature's trusted comment) and assumes an empty password instead of prompting when no password is given and stdin is not a terminal. `tauri signer` reports errors instead of panicking.

‎crates/tauri-cli/src/bundle.rs‎

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -298,9 +298,6 @@ fn sign_updaters(
298298
} else {
299299
private_key
300300
};
301-
if password.is_none() {
302-
log::info!("Decrypting updater signing key, expect a prompt for password")
303-
}
304301
let secret_key =
305302
updater_signature::secret_key(private_key, password).context("failed to decode secret key")?;
306303
let public_key = updater_signature::pub_key(pubkey).context("failed to decode pubkey")?;

‎crates/tauri-cli/src/helpers/updater_signature.rs‎

Lines changed: 108 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ use minisign::{
88
};
99
use 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
3547
pub 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\nIf 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\nIf 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:{}\tfile:{}",
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:{}\tfile:{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.
185199
pub 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\ntampered")).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\tfile: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]

‎crates/tauri-cli/src/signer/generate.rs‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
use crate::{
66
Result,
7+
error::Context,
78
helpers::updater_signature::{generate_key, save_keypair},
89
};
910
use clap::Parser;
@@ -34,12 +35,12 @@ pub fn command(mut options: Options) -> Result<()> {
3435
);
3536
options.password.replace("".into());
3637
}
37-
let keypair = generate_key(options.password).expect("Failed to generate key");
38+
let keypair = generate_key(options.password)?;
3839

3940
if let Some(output_path) = options.write_keys {
4041
let (secret_path, public_path) =
4142
save_keypair(options.force, output_path, &keypair.sk, &keypair.pk)
42-
.expect("Unable to write keypair");
43+
.context("unable to write keypair")?;
4344

4445
println!();
4546
println!("Your keypair was generated successfully:");

‎crates/tauri-cli/src/signer/sign.rs‎

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ use std::path::{Path, PathBuf};
66

77
use crate::{
88
Result,
9-
error::Context,
9+
error::{Context, ErrorExt},
1010
helpers::updater_signature::{secret_key, sign_file},
1111
};
1212
use base64::Engine;
@@ -84,7 +84,10 @@ pub fn command(mut options: Options) -> Result<()> {
8484
options = backward_env_vars(options);
8585

8686
options.private_key = if let Some(private_key) = options.private_key_path {
87-
Some(std::fs::read_to_string(Path::new(&private_key)).expect("Unable to extract private key"))
87+
Some(
88+
std::fs::read_to_string(Path::new(&private_key))
89+
.fs_context("failed to read private key file", private_key)?,
90+
)
8891
} else {
8992
options.private_key
9093
};
@@ -94,10 +97,6 @@ pub fn command(mut options: Options) -> Result<()> {
9497
crate::error::bail!("Key generation aborted: Unable to find the private key");
9598
};
9699

97-
if options.password.is_none() {
98-
println!("Signing without password.");
99-
}
100-
101100
if options.app_version.is_none() {
102101
println!(
103102
"Signing without an app version. Pass --app-version to bind this signature to a version; updaters configured with `requireSignedVersion` will reject this signature."

0 commit comments

Comments
 (0)