mirror of
https://github.com/telemt/telemt.git
synced 2026-10-29 12:07:15 +03:00
Descriptor-anchored Secured Filesystem Operations
This commit is contained in:
+40
-81
@@ -1,23 +1,30 @@
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::hash::{DefaultHasher, Hash, Hasher};
|
||||
use std::io::Read;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
#[cfg(unix)]
|
||||
use std::os::unix::fs::{MetadataExt, OpenOptionsExt};
|
||||
|
||||
use crate::error::{ProxyError, Result};
|
||||
|
||||
const MAX_CONFIG_SOURCE_BYTES: usize = 8 * 1024 * 1024;
|
||||
|
||||
pub(super) fn normalize_config_path(path: &Path) -> PathBuf {
|
||||
path.canonicalize().unwrap_or_else(|_| {
|
||||
if path.is_absolute() {
|
||||
path.to_path_buf()
|
||||
} else {
|
||||
std::env::current_dir()
|
||||
.map(|cwd| cwd.join(path))
|
||||
.unwrap_or_else(|_| path.to_path_buf())
|
||||
let absolute = if path.is_absolute() {
|
||||
path.to_path_buf()
|
||||
} else {
|
||||
std::env::current_dir()
|
||||
.map(|cwd| cwd.join(path))
|
||||
.unwrap_or_else(|_| path.to_path_buf())
|
||||
};
|
||||
let mut normalized = PathBuf::new();
|
||||
for component in absolute.components() {
|
||||
match component {
|
||||
std::path::Component::CurDir => {}
|
||||
std::path::Component::ParentDir => {
|
||||
normalized.pop();
|
||||
}
|
||||
component => normalized.push(component.as_os_str()),
|
||||
}
|
||||
})
|
||||
}
|
||||
normalized
|
||||
}
|
||||
|
||||
pub(super) fn hash_rendered_snapshot(rendered: &str) -> u64 {
|
||||
@@ -27,73 +34,28 @@ pub(super) fn hash_rendered_snapshot(rendered: &str) -> u64 {
|
||||
}
|
||||
|
||||
pub(super) fn read_config_source(path: &Path) -> Result<(PathBuf, String)> {
|
||||
let mut options = std::fs::OpenOptions::new();
|
||||
options.read(true);
|
||||
#[cfg(unix)]
|
||||
options.custom_flags(libc::O_CLOEXEC);
|
||||
let mut file = options
|
||||
.open(path)
|
||||
let bytes = crate::util::secure_fs::read_regular_limited(path, MAX_CONFIG_SOURCE_BYTES)
|
||||
.map_err(|error| ProxyError::Config(error.to_string()))?;
|
||||
let opened_metadata = file
|
||||
.metadata()
|
||||
.map_err(|error| ProxyError::Config(error.to_string()))?;
|
||||
if !opened_metadata.is_file() {
|
||||
#[cfg(not(unix))]
|
||||
let bytes = std::fs::read(path).map_err(|error| ProxyError::Config(error.to_string()))?;
|
||||
if bytes.len() > MAX_CONFIG_SOURCE_BYTES {
|
||||
return Err(ProxyError::Config(format!(
|
||||
"config source `{}` must be a regular file",
|
||||
path.display()
|
||||
"config source `{}` exceeds {} bytes",
|
||||
path.display(),
|
||||
MAX_CONFIG_SOURCE_BYTES
|
||||
)));
|
||||
}
|
||||
let contents = String::from_utf8(bytes).map_err(|error| {
|
||||
ProxyError::Config(format!(
|
||||
"config source `{}` is not valid UTF-8: {error}",
|
||||
path.display()
|
||||
))
|
||||
})?;
|
||||
let normalized = normalize_config_path(path);
|
||||
let current_metadata = std::fs::metadata(&normalized)
|
||||
.map_err(|error| ProxyError::Config(error.to_string()))?;
|
||||
if !same_file_identity(&opened_metadata, ¤t_metadata) {
|
||||
return Err(ProxyError::Config(format!(
|
||||
"config source `{}` changed while it was opened",
|
||||
path.display()
|
||||
)));
|
||||
}
|
||||
let mut contents = String::new();
|
||||
file.read_to_string(&mut contents)
|
||||
.map_err(|error| ProxyError::Config(error.to_string()))?;
|
||||
let completed_metadata = file
|
||||
.metadata()
|
||||
.map_err(|error| ProxyError::Config(error.to_string()))?;
|
||||
if !same_file_version(&opened_metadata, &completed_metadata) {
|
||||
return Err(ProxyError::Config(format!(
|
||||
"config source `{}` changed while it was read",
|
||||
path.display()
|
||||
)));
|
||||
}
|
||||
Ok((normalized, contents))
|
||||
}
|
||||
|
||||
fn same_file_identity(left: &std::fs::Metadata, right: &std::fs::Metadata) -> bool {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
left.dev() == right.dev() && left.ino() == right.ino()
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
{
|
||||
left.len() == right.len() && left.modified().ok() == right.modified().ok()
|
||||
}
|
||||
}
|
||||
|
||||
fn same_file_version(left: &std::fs::Metadata, right: &std::fs::Metadata) -> bool {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
same_file_identity(left, right)
|
||||
&& left.len() == right.len()
|
||||
&& left.mtime() == right.mtime()
|
||||
&& left.mtime_nsec() == right.mtime_nsec()
|
||||
&& left.ctime() == right.ctime()
|
||||
&& left.ctime_nsec() == right.ctime_nsec()
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
{
|
||||
same_file_identity(left, right)
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn preprocess_includes(
|
||||
content: &str,
|
||||
base_dir: &Path,
|
||||
@@ -113,20 +75,17 @@ pub(super) fn preprocess_includes(
|
||||
if let Some(rest) = rest.strip_prefix('=') {
|
||||
let path_str = rest.trim().trim_matches('"');
|
||||
let resolved = base_dir.join(path_str);
|
||||
let normalized = normalize_config_path(&resolved);
|
||||
let cached = source_contents.get(&normalized).cloned();
|
||||
let (normalized, included) = if let Some(included) =
|
||||
source_overrides.get(&normalized).cloned().or(cached)
|
||||
{
|
||||
(normalized, included)
|
||||
} else {
|
||||
read_config_source(&resolved)?
|
||||
};
|
||||
let (normalized, disk_contents) = read_config_source(&resolved)?;
|
||||
let included = source_overrides
|
||||
.get(&normalized)
|
||||
.cloned()
|
||||
.or_else(|| source_contents.get(&normalized).cloned())
|
||||
.unwrap_or(disk_contents);
|
||||
source_files.insert(normalized.clone());
|
||||
source_contents
|
||||
.entry(normalized)
|
||||
.entry(normalized.clone())
|
||||
.or_insert_with(|| included.clone());
|
||||
let included_dir = resolved.parent().unwrap_or(base_dir);
|
||||
let included_dir = normalized.parent().unwrap_or(base_dir);
|
||||
output.push_str(&preprocess_includes(
|
||||
&included,
|
||||
included_dir,
|
||||
|
||||
@@ -12,6 +12,7 @@ const ACCESS_SECRET_BYTES: usize = 16;
|
||||
pub(crate) struct UserAuthSnapshot {
|
||||
entries: Vec<UserAuthEntry>,
|
||||
by_name: HashMap<String, u32>,
|
||||
by_hint_key: HashMap<u64, Vec<u32>>,
|
||||
sni_index: HashMap<u64, Vec<u32>>,
|
||||
sni_initial_index: HashMap<u8, Vec<u32>>,
|
||||
}
|
||||
@@ -22,16 +23,21 @@ pub(crate) struct UserAuthEntry {
|
||||
pub(crate) secret: [u8; ACCESS_SECRET_BYTES],
|
||||
/// Stable secret identity used by process-wide admission fencing.
|
||||
pub(crate) credential_id: [u8; 16],
|
||||
/// Stable compact key used only to resolve bounded authentication hints.
|
||||
pub(crate) hint_key: u64,
|
||||
}
|
||||
|
||||
impl UserAuthSnapshot {
|
||||
pub(super) fn from_users(users: &HashMap<String, String>) -> Result<Self> {
|
||||
let mut entries = Vec::with_capacity(users.len());
|
||||
let mut by_name = HashMap::with_capacity(users.len());
|
||||
let mut by_hint_key = HashMap::with_capacity(users.len());
|
||||
let mut sni_index = HashMap::with_capacity(users.len());
|
||||
let mut sni_initial_index = HashMap::with_capacity(users.len());
|
||||
|
||||
for (user, secret_hex) in users {
|
||||
let mut ordered_users = users.iter().collect::<Vec<_>>();
|
||||
ordered_users.sort_unstable_by(|(left, _), (right, _)| left.cmp(right));
|
||||
for (user, secret_hex) in ordered_users {
|
||||
let decoded = hex::decode(secret_hex).map_err(|_| ProxyError::InvalidSecret {
|
||||
user: user.clone(),
|
||||
reason: "Must be 32 hex characters".to_string(),
|
||||
@@ -52,12 +58,27 @@ impl UserAuthSnapshot {
|
||||
let digest = sha256(&secret);
|
||||
let mut credential_id = [0; 16];
|
||||
credential_id.copy_from_slice(&digest[..16]);
|
||||
let hint_key = u64::from_le_bytes([
|
||||
credential_id[0],
|
||||
credential_id[1],
|
||||
credential_id[2],
|
||||
credential_id[3],
|
||||
credential_id[4],
|
||||
credential_id[5],
|
||||
credential_id[6],
|
||||
credential_id[7],
|
||||
]) | 1;
|
||||
entries.push(UserAuthEntry {
|
||||
user: user.clone(),
|
||||
secret,
|
||||
credential_id,
|
||||
hint_key,
|
||||
});
|
||||
by_name.insert(user.clone(), user_id);
|
||||
by_hint_key
|
||||
.entry(hint_key)
|
||||
.or_insert_with(Vec::new)
|
||||
.push(user_id);
|
||||
sni_index
|
||||
.entry(Self::sni_lookup_hash(user))
|
||||
.or_insert_with(Vec::new)
|
||||
@@ -77,6 +98,7 @@ impl UserAuthSnapshot {
|
||||
Ok(Self {
|
||||
entries,
|
||||
by_name,
|
||||
by_hint_key,
|
||||
sni_index,
|
||||
sni_initial_index,
|
||||
})
|
||||
@@ -101,6 +123,10 @@ impl UserAuthSnapshot {
|
||||
.map(|entry| entry.credential_id)
|
||||
}
|
||||
|
||||
pub(crate) fn candidate_ids_by_hint_key(&self, hint_key: u64) -> Option<&[u32]> {
|
||||
self.by_hint_key.get(&hint_key).map(Vec::as_slice)
|
||||
}
|
||||
|
||||
pub(crate) fn sni_candidates(&self, sni: &str) -> Option<&[u32]> {
|
||||
self.sni_index
|
||||
.get(&Self::sni_lookup_hash(sni))
|
||||
@@ -123,3 +149,48 @@ impl UserAuthSnapshot {
|
||||
hasher.finish()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn credential_hint_survives_positional_id_shift() {
|
||||
let mut initial = HashMap::new();
|
||||
initial.insert(
|
||||
"alice".to_string(),
|
||||
"11111111111111111111111111111111".to_string(),
|
||||
);
|
||||
initial.insert(
|
||||
"bob".to_string(),
|
||||
"22222222222222222222222222222222".to_string(),
|
||||
);
|
||||
let initial = UserAuthSnapshot::from_users(&initial).unwrap();
|
||||
let initial_id = initial.user_id_by_name("alice").unwrap();
|
||||
let hint_key = initial.entry_by_id(initial_id).unwrap().hint_key;
|
||||
|
||||
let mut reloaded = HashMap::new();
|
||||
reloaded.insert(
|
||||
"aaron".to_string(),
|
||||
"33333333333333333333333333333333".to_string(),
|
||||
);
|
||||
reloaded.insert(
|
||||
"alice".to_string(),
|
||||
"11111111111111111111111111111111".to_string(),
|
||||
);
|
||||
reloaded.insert(
|
||||
"bob".to_string(),
|
||||
"22222222222222222222222222222222".to_string(),
|
||||
);
|
||||
let reloaded = UserAuthSnapshot::from_users(&reloaded).unwrap();
|
||||
let reloaded_id = reloaded.user_id_by_name("alice").unwrap();
|
||||
|
||||
assert_ne!(initial_id, reloaded_id);
|
||||
assert!(
|
||||
reloaded
|
||||
.candidate_ids_by_hint_key(hint_key)
|
||||
.unwrap()
|
||||
.contains(&reloaded_id)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,6 +23,8 @@ use hmac::{Hmac, Mac};
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
use super::*;
|
||||
#[cfg(unix)]
|
||||
use crate::util::secure_fs::open_dir_nofollow;
|
||||
|
||||
// Path-based static snapshot fallback for platforms without directory descriptors.
|
||||
#[cfg(not(unix))]
|
||||
@@ -247,16 +249,17 @@ fn load_static_site(
|
||||
|
||||
#[cfg(unix)]
|
||||
fn open_static_root(root: &Path) -> Result<Dir> {
|
||||
Dir::open(
|
||||
root,
|
||||
OFlag::O_RDONLY | OFlag::O_DIRECTORY | OFlag::O_NOFOLLOW | OFlag::O_CLOEXEC,
|
||||
Mode::empty(),
|
||||
)
|
||||
.map_err(|error| {
|
||||
let descriptor = open_dir_nofollow(root).map_err(|error| {
|
||||
ProxyError::Config(format!(
|
||||
"WEB static directory `{}` must be a real directory, not a symlink: {error}",
|
||||
root.display()
|
||||
))
|
||||
})?;
|
||||
Dir::from_fd(descriptor).map_err(|error| {
|
||||
ProxyError::Config(format!(
|
||||
"failed to read WEB static directory `{}`: {error}",
|
||||
root.display()
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user