fix(pamsave): close credential and policy injection

- Require exact username matching when replacing PAM secrets.
- Confine policy staging and validate decoded TOML values.
- Add the validated password-substring exploit for Neo automation.
This commit is contained in:
TakuyaYagam1 committed 2026-11-29 13:09:03 +03:00
1 parent 2a9632774d
commit 96314809c8
5 files changed
+311 -41

No files matched your search

+41 -3
View File
@@ -19,10 +19,17 @@ struct Job {
static DEPLOY_QUEUE: std::sync::OnceLock<mpsc::UnboundedSender<Job>> = std::sync::OnceLock::new();
pub fn stage(name: &str, content: &str) -> ApiResult<PathBuf> {
let path = snippets_dir().join(name);
if let Some(parent) = path.parent() {
fs::create_dir_all(parent).map_err(|_| ApiError::Async)?;
let mut components = Path::new(name).components();
if name.contains('\\')
|| !matches!(components.next(), Some(Component::Normal(_)))
|| components.next().is_some()
{
return Err(ApiError::BadRequest(
"policy name must be a plain file name".to_string(),
));
}
let path = snippets_dir().join(name);
fs::write(&path, content).map_err(|_| ApiError::Async)?;
Ok(path)
}
@@ -121,3 +128,34 @@ fn env_dir(key: &str, default: &str) -> PathBuf {
}
#[cfg(test)]
mod tests {
use std::fs;
use std::time::{SystemTime, UNIX_EPOCH};
use super::stage;
#[test]
fn stage_rejects_parent_directory_traversal() {
let suffix = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos();
let root = std::env::temp_dir().join(format!(
"pamsave-stage-{}-{suffix}",
std::process::id()
));
let snippets = root.join("snippets");
let escaped = root.join("escaped");
fs::create_dir_all(&snippets).unwrap();
std::env::set_var("PAMSAVE_SNIPPETS_DIR", &snippets);
let result = stage("../escaped", "attacker-controlled");
std::env::remove_var("PAMSAVE_SNIPPETS_DIR");
assert!(result.is_err());
assert!(!escaped.exists());
fs::remove_dir_all(root).unwrap();
}
}
+87 -26
View File
@@ -7,6 +7,9 @@ pub const EXTERNAL_RIGHTS_MAX: usize = 50;
pub const FILE_RIGHTS_MAX: usize = 50;
pub const INCLUDE_MAX: usize = 10;
pub const SNIPPETS_DIR: &str = "/etc/pamsave/snippets";
const USERNAME_MAX_LEN: usize = 30;
const FILE_NAME_MAX_LEN: usize = 100;
const INCLUDE_NAME_MAX_LEN: usize = 100;
#[derive(Debug, Clone, Deserialize)]
pub struct PolicyConfig {
@@ -50,12 +53,15 @@ pub fn compile(content: &str) -> ApiResult<CompiledPolicy> {
)));
}
let mut external_rights: Vec<String> = config
.external_rights
.iter()
.map(|right| right.username.trim().to_string())
.filter(|username| !username.is_empty())
.collect();
let mut external_rights = Vec::with_capacity(config.external_rights.len());
for right in &config.external_rights {
let username = right.username.trim();
if username.is_empty() {
continue;
}
validate_registry_value(username, USERNAME_MAX_LEN)?;
external_rights.push(username.to_string());
}
if external_rights.len() > EXTERNAL_RIGHTS_MAX {
return Err(ApiError::BadRequest(format!(
"policy must contain at most {EXTERNAL_RIGHTS_MAX} external rights"
@@ -64,17 +70,17 @@ pub fn compile(content: &str) -> ApiResult<CompiledPolicy> {
external_rights.sort();
external_rights.dedup();
let mut file_rights: Vec<(String, String)> = config
.file_rights
.iter()
.map(|right| {
(
right.username.trim().to_string(),
right.file.trim().to_string(),
)
})
.filter(|(username, file)| !username.is_empty() && !file.is_empty())
.collect();
let mut file_rights = Vec::with_capacity(config.file_rights.len());
for right in &config.file_rights {
let username = right.username.trim();
let file = right.file.trim();
if username.is_empty() || file.is_empty() {
continue;
}
validate_registry_value(username, USERNAME_MAX_LEN)?;
validate_registry_value(file, FILE_NAME_MAX_LEN)?;
file_rights.push((username.to_string(), file.to_string()));
}
if file_rights.len() > FILE_RIGHTS_MAX {
return Err(ApiError::BadRequest(format!(
"policy must contain at most {FILE_RIGHTS_MAX} file rights"
@@ -83,12 +89,15 @@ pub fn compile(content: &str) -> ApiResult<CompiledPolicy> {
file_rights.sort();
file_rights.dedup();
let includes: Vec<String> = config
.include
.iter()
.map(|name| name.trim().to_string())
.filter(|name| !name.is_empty())
.collect();
let mut includes = Vec::with_capacity(config.include.len());
for name in &config.include {
let name = name.trim();
if name.is_empty() {
continue;
}
validate_include_name(name)?;
includes.push(name.to_string());
}
if includes.len() > INCLUDE_MAX {
return Err(ApiError::BadRequest(format!(
"policy must contain at most {INCLUDE_MAX} include entries"
@@ -97,9 +106,15 @@ pub fn compile(content: &str) -> ApiResult<CompiledPolicy> {
let mut service_stack = String::new();
for name in &includes {
service_stack.push_str(&format!(
"auth include {SNIPPETS_DIR}/{name}\naccount include {SNIPPETS_DIR}/{name}\n"
));
service_stack.push_str("auth include ");
service_stack.push_str(SNIPPETS_DIR);
service_stack.push('/');
service_stack.push_str(name);
service_stack.push_str("\naccount include ");
service_stack.push_str(SNIPPETS_DIR);
service_stack.push('/');
service_stack.push_str(name);
service_stack.push('\n');
}
service_stack.push_str("auth required pam_pamsave.so\naccount required pam_pamsave.so\n");
@@ -110,4 +125,50 @@ pub fn compile(content: &str) -> ApiResult<CompiledPolicy> {
})
}
fn validate_registry_value(value: &str, max_len: usize) -> ApiResult<()> {
if value.len() > max_len {
return Err(ApiError::BadRequest(format!(
"value must be at most {max_len} characters"
)));
}
if value.contains(':') || value.chars().any(char::is_control) {
return Err(ApiError::BadRequest(
"value must not contain registry delimiters".to_string(),
));
}
Ok(())
}
fn validate_include_name(name: &str) -> ApiResult<()> {
if name.len() > INCLUDE_NAME_MAX_LEN
|| name.contains("..")
|| !name
.chars()
.all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '-' | '_' | '.'))
{
return Err(ApiError::BadRequest(
"include name contains invalid characters".to_string(),
));
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::compile;
#[test]
fn compile_rejects_decoded_registry_delimiters() {
let content = r#"
version = 1
[[file_rights]]
username = "attacker"
file = "prefix\nattacker\u003Avictim-workspace\nsuffix"
"#;
assert!(compile(content).is_err());
}
}
+49 -4
View File
@@ -29,18 +29,31 @@ pub fn update(username: &str, new_password: &str) -> ApiResult<()> {
let hasher = ShaCrypt::default();
let hash = hasher
.hash_password(new_password.as_bytes())
.map_err(|_| ApiError::Async)?;
.map_err(|_| ApiError::Async)?
.to_string();
let path = secrets_path();
let content = std::fs::read_to_string(&path).map_err(|_| ApiError::Async)?;
let mut updated = content.clone();
let mut updated = String::with_capacity(content.len() + hash.len());
let mut replaced = false;
for line in content.lines() {
let Some((user, _)) = line.split_once(':') else {
updated.push_str(line);
updated.push('\n');
continue;
};
if user.contains(username) {
updated.push_str(&format!("{user}:{hash}\n"));
if user == username {
if !replaced {
updated.push_str(user);
updated.push(':');
updated.push_str(&hash);
updated.push('\n');
replaced = true;
}
} else {
updated.push_str(line);
updated.push('\n');
}
}
@@ -59,3 +72,35 @@ fn secrets_path() -> PathBuf {
.unwrap_or_else(|_| DEFAULT_SECRETS_PATH.to_string())
.into()
}
#[cfg(test)]
mod tests {
use std::fs;
use std::time::{SystemTime, UNIX_EPOCH};
use super::update;
#[test]
fn update_replaces_only_the_exact_username() {
let suffix = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos();
let path = std::env::temp_dir().join(format!(
"pamsave-secrets-{}-{suffix}",
std::process::id()
));
fs::write(&path, "alice:old\nchecker_alice:victim\n").unwrap();
std::env::set_var("PAMSAVE_SECRETS_PATH", &path);
update("alice", "new-password").unwrap();
std::env::remove_var("PAMSAVE_SECRETS_PATH");
let content = fs::read_to_string(&path).unwrap();
fs::remove_file(path).unwrap();
let lines: Vec<_> = content.lines().collect();
assert_eq!(lines.len(), 2);
assert!(lines[0].starts_with("alice:$6$"));
assert_eq!(lines[1], "checker_alice:victim");
}
}
@@ -27,17 +27,15 @@ pub async fn create(
}
pam::validator::validate_raw(&req.content)?;
let compiled = pam::policy::compile(&req.content);
let compiled = pam::policy::compile(&req.content)?;
pam::deploy::stage(name, &req.content)?;
if let Ok(compiled) = &compiled {
for username in &compiled.external_rights {
pam::memberships::append(username, workspace_id)?;
}
for (username, file) in &compiled.file_rights {
pam::memberships::append_file_grant(username, workspace_id, file)?;
}
for username in &compiled.external_rights {
pam::memberships::append(username, workspace_id)?;
}
for (username, file) in &compiled.file_rights {
pam::memberships::append_file_grant(username, workspace_id, file)?;
}
let stored = AuthPolicyRepository::create(pool, workspace_id, name).await;