Skip to content

Commit 7ebbb21

Browse files
rustez-cli: drop --password, read it from a file, stop deriving Debug over it (#55)
* rustez-cli: drop --password, read it from a file, stop deriving Debug over it --password put the device password in argv, visible to every other process on the host via ps and preserved in shell history. The existing $RUSTEZ_PASSWORD/--key-file/interactive-prompt fallbacks already covered the safer cases; only the flag itself needed to go. Replaced it with --password-file <PATH>, read through the same regular-file/non-symlink/mode-0600 checks the codebase already applies to other credential files (mirroring rustmistmcp's validate_credential_file). Precedence is now file > env > key > prompt. ConnOpts keeps its Debug derive rather than getting a hand-written one: with the password flag gone, password_file is the only credential- adjacent field left on the struct, and it holds a path, not a secret. Documented the invariant on the struct so a future field addition doesn't reopen this quietly. Verified: cargo test -p rustez-cli (32 passed, including new coverage for the trailing-newline strip, the empty/wrong-mode/symlink refusals, and the file > env precedence); cargo clippy -p rustez-cli --all-targets (clean); cargo tree -p rustez-cli -e normal has no tempfile entry (test fixture dependency only, dev-dependencies). Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> * rustez-cli: fix fmt, stop leaking password via vsrx integration test args - cargo fmt --all: reformat write_password_file's signature to fit rustfmt's line width, fixing the red Formatting CI job on PR #55. - Percy review F1: the ignored vSRX integration test still passed the device password as `-p`/`--password`, the exact CLI-arg leak this PR removes, and it no longer parses since the flag is gone. Pass it via RUSTEZ_PASSWORD instead. - Percy review F2: add a regression test asserting `-p`/`--password` are rejected by the parser, so the flag can't be silently reintroduced. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
1 parent c848131 commit 7ebbb21

5 files changed

Lines changed: 177 additions & 26 deletions

File tree

‎README.md‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,7 @@ automatically.
9797

9898
```bash
9999
# Gather device facts
100-
rustez facts 10.0.0.1 -u admin -p secret
100+
rustez facts 10.0.0.1 -u admin --password-file /path/to/password-0600
101101

102102
# Run a show command
103103
rustez rpc 10.0.0.1 "show interfaces terse" -u admin
@@ -131,10 +131,11 @@ Each error `kind` maps to a distinct exit code: `usage`=1, `connect`=2, `auth`=3
131131

132132
### Credentials
133133

134-
Password resolution precedence: `-p/--password` (warns — visible in the process
135-
list) → `$RUSTEZ_PASSWORD` → `--key-file <PATH>` (key-based auth) → interactive
136-
no-echo prompt (when stdin is a TTY). Prefer `$RUSTEZ_PASSWORD` or `--key-file`
137-
over `-p`.
134+
Password resolution precedence: `--password-file <PATH>` (must be a regular,
135+
non-symlink file at mode 0600) → `$RUSTEZ_PASSWORD` → `--key-file <PATH>`
136+
(key-based auth) → interactive no-echo prompt (when stdin is a TTY). There is
137+
no `--password` flag: a password given as a CLI argument is visible to every
138+
other process on the host via `ps`, and to anyone with shell-history access.
138139

139140
### Host-key verification
140141

‎rustez-cli/Cargo.toml‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,3 +17,7 @@ clap = { version = "4", features = ["derive"] }
1717
serde = { version = "1", features = ["derive"] }
1818
serde_json = "1"
1919
rpassword = "7"
20+
21+
[dev-dependencies]
22+
# Test-only: fixtures for --password-file's permission and symlink checks.
23+
tempfile = "3"

‎rustez-cli/src/cli.rs‎

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,16 +26,24 @@ pub enum Command {
2626
}
2727

2828
/// Connection options shared by every command.
29+
///
30+
/// No field here may hold a resolved password: the value itself lives only in
31+
/// `$RUSTEZ_PASSWORD`, in the file named by `password_file`, or in what an
32+
/// interactive prompt reads — never in a CLI argument, which `ps` and shell
33+
/// history both make visible to anyone on the same host. That is also why
34+
/// `derive(Debug)` is safe to keep here: `password_file` is a path, not a
35+
/// secret, and there is nothing else on this struct that is.
2936
#[derive(Args, Debug)]
3037
pub struct ConnOpts {
3138
/// Device hostname or IP.
3239
pub host: String,
3340
/// Login username.
3441
#[arg(short, long)]
3542
pub user: String,
36-
/// Login password (insecure: visible in process list — prefer $RUSTEZ_PASSWORD).
37-
#[arg(short, long)]
38-
pub password: Option<String>,
43+
/// Path to a file holding the login password. Must be a regular,
44+
/// non-symlink file at mode 0600.
45+
#[arg(long)]
46+
pub password_file: Option<String>,
3947
/// NETCONF port (library default if unset).
4048
#[arg(long)]
4149
pub port: Option<u16>,
@@ -321,4 +329,15 @@ mod tests {
321329
_ => panic!("expected config"),
322330
}
323331
}
332+
333+
/// Regression (MEC-33/MEC-59): a password must never be accepted as a CLI
334+
/// argument, where `ps` and shell history expose it to the whole host.
335+
#[test]
336+
fn password_flag_is_rejected() {
337+
for flag in ["-p", "--password"] {
338+
let res =
339+
Cli::try_parse_from(["rustez", "facts", "10.0.0.1", "-u", "admin", flag, "x"]);
340+
assert!(res.is_err(), "{flag} must not be accepted");
341+
}
342+
}
324343
}

‎rustez-cli/src/connect.rs‎

Lines changed: 144 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -19,16 +19,22 @@ pub enum PasswordPlan {
1919
KeyOnly,
2020
}
2121

22-
/// Decide how to obtain the password. Precedence: flag > env > key > prompt.
22+
/// Decide how to obtain the password. Precedence: file > env > key > prompt.
23+
///
24+
/// `file` is the password file's already-read, already-validated contents —
25+
/// this function makes no I/O calls, which is what keeps it plain and
26+
/// testable. There is deliberately no CLI-flag source: a flag value is
27+
/// visible to every other process on the host via `ps`, and to anyone with
28+
/// shell history access.
2329
///
2430
/// Returns a `usage` error when no source is available and stdin is not a TTY.
2531
pub fn plan_password(
26-
flag: Option<&str>,
32+
file: Option<&str>,
2733
env: Option<&str>,
2834
has_key: bool,
2935
is_tty: bool,
3036
) -> Result<PasswordPlan, CliError> {
31-
if let Some(p) = flag {
37+
if let Some(p) = file {
3238
return Ok(PasswordPlan::Use(p.to_string()));
3339
}
3440
if let Some(e) = env {
@@ -42,10 +48,65 @@ pub fn plan_password(
4248
}
4349
Err(CliError::new(
4450
ErrorKind::Usage,
45-
"no password provided and stdin is not a TTY; set $RUSTEZ_PASSWORD or use --key-file",
51+
"no password provided and stdin is not a TTY; set $RUSTEZ_PASSWORD, \
52+
--password-file <PATH>, or use --key-file",
4653
))
4754
}
4855

56+
/// Read and validate a password file: a regular, non-symlink file at exactly
57+
/// mode 0600, holding valid UTF-8 with at most one trailing line ending
58+
/// stripped.
59+
///
60+
/// The permission and symlink checks match the credential-file convention
61+
/// used elsewhere at Mechub (e.g. rustmistmcp's `validate_credential_file`):
62+
/// a password file left group- or world-readable, or reached through a
63+
/// symlink an attacker can redirect, defeats the point of moving the secret
64+
/// out of the CLI argument in the first place.
65+
fn read_password_file(path: &str) -> Result<String, CliError> {
66+
let usage = |message: String| CliError::new(ErrorKind::Usage, message);
67+
68+
let metadata = std::fs::symlink_metadata(path)
69+
.map_err(|e| usage(format!("--password-file {path}: {e}")))?;
70+
if metadata.file_type().is_symlink() {
71+
return Err(usage(format!(
72+
"--password-file {path} must not be a symlink"
73+
)));
74+
}
75+
if !metadata.file_type().is_file() {
76+
return Err(usage(format!(
77+
"--password-file {path} must be a regular file"
78+
)));
79+
}
80+
#[cfg(unix)]
81+
{
82+
use std::os::unix::fs::PermissionsExt;
83+
let mode = metadata.permissions().mode() & 0o777;
84+
if mode != 0o600 {
85+
return Err(usage(format!(
86+
"--password-file {path} must be mode 0600, found {mode:o}"
87+
)));
88+
}
89+
}
90+
91+
let raw = std::fs::read(path).map_err(|e| usage(format!("--password-file {path}: {e}")))?;
92+
let mut text = String::from_utf8(raw)
93+
.map_err(|_| usage(format!("--password-file {path} is not valid UTF-8")))?;
94+
// Strip at most one trailing line ending: a password file written with an
95+
// editor ordinarily ends in one, and a password legitimately ending in a
96+
// real newline or other whitespace byte is indistinguishable from that at
97+
// this layer, so trimming more would silently change the credential.
98+
if text.ends_with('\n') {
99+
text.pop();
100+
if text.ends_with('\r') {
101+
text.pop();
102+
}
103+
}
104+
if text.is_empty() {
105+
return Err(usage(format!("--password-file {path} is empty")));
106+
}
107+
Ok(text)
108+
}
109+
49110
/// Map host-key CLI flags to a verification policy. `None` => library default (RejectAll).
50111
pub fn host_key_policy(conn: &ConnOpts) -> Option<HostKeyVerification> {
51112
if let Some(fp) = &conn.host_key_fingerprint {
@@ -65,16 +126,15 @@ pub fn host_key_policy(conn: &ConnOpts) -> Option<HostKeyVerification> {
65126
/// `gather_facts` controls whether facts are auto-gathered on open (true for
66127
/// the `facts` command, false for `rpc`/`config` to save three RPCs).
67128
pub async fn build_device(conn: &ConnOpts, gather_facts: bool) -> Result<Device, CliError> {
68-
if conn.password.is_some() {
69-
eprintln!(
70-
"warning: --password is visible in the process list; prefer $RUSTEZ_PASSWORD or --key-file"
71-
);
72-
}
73-
129+
let file_pw = conn
130+
.password_file
131+
.as_deref()
132+
.map(read_password_file)
133+
.transpose()?;
74134
let env_pw = std::env::var("RUSTEZ_PASSWORD").ok();
75135
let has_key = conn.key_file.is_some();
76136
let is_tty = std::io::stdin().is_terminal();
77-
let plan = plan_password(conn.password.as_deref(), env_pw.as_deref(), has_key, is_tty)?;
137+
let plan = plan_password(file_pw.as_deref(), env_pw.as_deref(), has_key, is_tty)?;
78138

79139
let password = match plan {
80140
PasswordPlan::Use(p) => Some(p),
@@ -119,13 +179,13 @@ mod tests {
119179
use super::*;
120180

121181
#[test]
122-
fn flag_password_takes_precedence() {
123-
let plan = plan_password(Some("flagpw"), Some("envpw"), false, false).unwrap();
124-
assert_eq!(plan, PasswordPlan::Use("flagpw".into()));
182+
fn file_password_takes_precedence() {
183+
let plan = plan_password(Some("filepw"), Some("envpw"), false, false).unwrap();
184+
assert_eq!(plan, PasswordPlan::Use("filepw".into()));
125185
}
126186

127187
#[test]
128-
fn env_password_used_when_no_flag() {
188+
fn env_password_used_when_no_file() {
129189
let plan = plan_password(None, Some("envpw"), false, false).unwrap();
130190
assert_eq!(plan, PasswordPlan::Use("envpw".into()));
131191
}
@@ -168,7 +228,7 @@ mod tests {
168228
let mut conn = ConnOpts {
169229
host: "h".into(),
170230
user: "u".into(),
171-
password: None,
231+
password_file: None,
172232
port: None,
173233
key_file: None,
174234
host_key_fingerprint: None,
@@ -180,4 +240,72 @@ mod tests {
180240
tweak(&mut conn);
181241
conn
182242
}
243+
244+
#[cfg(unix)]
245+
fn write_password_file(
246+
dir: &std::path::Path,
247+
name: &str,
248+
contents: &[u8],
249+
mode: u32,
250+
) -> String {
251+
use std::os::unix::fs::PermissionsExt;
252+
let path = dir.join(name);
253+
std::fs::write(&path, contents).unwrap();
254+
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(mode)).unwrap();
255+
path.to_str().unwrap().to_owned()
256+
}
257+
258+
#[cfg(unix)]
259+
#[test]
260+
fn password_file_strips_one_trailing_newline() {
261+
let dir = tempfile::tempdir().unwrap();
262+
let path = write_password_file(dir.path(), "pw", b"hunter2\n", 0o600);
263+
assert_eq!(read_password_file(&path).unwrap(), "hunter2");
264+
}
265+
266+
#[cfg(unix)]
267+
#[test]
268+
fn password_file_keeps_internal_and_non_newline_whitespace() {
269+
let dir = tempfile::tempdir().unwrap();
270+
let path = write_password_file(dir.path(), "pw", b"trailing space \n", 0o600);
271+
assert_eq!(read_password_file(&path).unwrap(), "trailing space ");
272+
}
273+
274+
#[cfg(unix)]
275+
#[test]
276+
fn password_file_at_0644_is_refused() {
277+
let dir = tempfile::tempdir().unwrap();
278+
let path = write_password_file(dir.path(), "pw", b"hunter2\n", 0o644);
279+
let err = read_password_file(&path).unwrap_err();
280+
assert_eq!(err.kind, ErrorKind::Usage);
281+
assert!(err.message.contains("0600"));
282+
}
283+
284+
#[cfg(unix)]
285+
#[test]
286+
fn empty_password_file_is_refused() {
287+
let dir = tempfile::tempdir().unwrap();
288+
let path = write_password_file(dir.path(), "pw", b"", 0o600);
289+
let err = read_password_file(&path).unwrap_err();
290+
assert_eq!(err.kind, ErrorKind::Usage);
291+
assert!(err.message.contains("empty"));
292+
}
293+
294+
#[cfg(unix)]
295+
#[test]
296+
fn symlinked_password_file_is_refused() {
297+
let dir = tempfile::tempdir().unwrap();
298+
let real = write_password_file(dir.path(), "real-pw", b"hunter2\n", 0o600);
299+
let link = dir.path().join("linked-pw");
300+
std::os::unix::fs::symlink(&real, &link).unwrap();
301+
let err = read_password_file(link.to_str().unwrap()).unwrap_err();
302+
assert_eq!(err.kind, ErrorKind::Usage);
303+
assert!(err.message.contains("symlink"));
304+
}
305+
306+
#[test]
307+
fn missing_password_file_is_a_usage_error() {
308+
let err = read_password_file("/nonexistent/rustez-password-file").unwrap_err();
309+
assert_eq!(err.kind, ErrorKind::Usage);
310+
}
183311
}

‎rustez-cli/tests/cli_integration.rs‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,11 +23,10 @@ fn facts_json_against_vsrx() {
2323
&host,
2424
"-u",
2525
&user,
26-
"-p",
27-
&pass,
2826
"--accept-any-host-key",
2927
"--json",
3028
])
29+
.env("RUSTEZ_PASSWORD", &pass)
3130
.output()
3231
.expect("failed to run rustez-cli");
3332

0 commit comments

Comments
 (0)