Repository navigation
Expand file tree
/
Copy pathpath_security.rs
More file actions
364 lines (306 loc) · 12.1 KB
/
Copy pathpath_security.rs
File metadata and controls
364 lines (306 loc) · 12.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
//! Path security validation for module resolution
//!
//! This module provides comprehensive path validation to prevent
//! path traversal attacks, symlink exploits, and other path-based vulnerabilities.
use crate::module::{ModuleError, ModuleResult};
use std::collections::HashSet;
use std::path::{Component, Path, PathBuf};
/// Path security validator with strict validation rules
#[derive(Debug)]
pub struct PathSecurityValidator {
/// Absolute path to project root
project_root: PathBuf,
/// Maximum allowed path length
max_path_length: usize,
/// Allowed file extensions
allowed_extensions: HashSet<String>,
/// Forbidden path patterns
forbidden_patterns: Vec<String>,
/// Whether to follow symlinks
allow_symlinks: bool,
}
impl PathSecurityValidator {
/// Create a new path security validator
pub fn new(project_root: PathBuf) -> ModuleResult<Self> {
// Ensure project root is absolute and canonical
let canonical_root = project_root.canonicalize().map_err(|e| {
ModuleError::security_violation(format!("Failed to canonicalize project root: {}", e))
})?;
let mut allowed_extensions = HashSet::new();
allowed_extensions.insert("script".to_string());
allowed_extensions.insert("scripts".to_string());
let forbidden_patterns = vec![
"..".to_string(),
"~".to_string(),
"$".to_string(),
"%".to_string(),
"\\".to_string(),
];
Ok(PathSecurityValidator {
project_root: canonical_root,
max_path_length: 255,
allowed_extensions,
forbidden_patterns,
allow_symlinks: false,
})
}
/// Validate a module path for security issues
pub fn validate_module_path(&self, path: &str) -> ModuleResult<PathBuf> {
// Step 1: Basic validation
self.validate_path_format(path)?;
// Step 2: Check for forbidden patterns
self.check_forbidden_patterns(path)?;
// Step 3: Construct safe path
let safe_path = self.construct_safe_path(path)?;
// Step 4: Validate file extension
self.validate_extension(&safe_path)?;
// Step 5: Ensure path stays within project bounds
self.validate_within_bounds(&safe_path)?;
// Step 6: Check symlink safety
if !self.allow_symlinks {
self.validate_no_symlinks(&safe_path)?;
}
Ok(safe_path)
}
/// Validate basic path format
fn validate_path_format(&self, path: &str) -> ModuleResult<()> {
// Check path length
if path.is_empty() {
return Err(ModuleError::security_violation("Empty module path"));
}
if path.len() > self.max_path_length {
return Err(ModuleError::security_violation(format!(
"Path too long: {} (max: {})",
path.len(),
self.max_path_length
)));
}
// Reject absolute paths
if path.starts_with('/') || path.starts_with('\\') {
return Err(ModuleError::security_violation(
"Absolute paths are not allowed",
));
}
// Check for null bytes
if path.contains('\0') {
return Err(ModuleError::security_violation("Path contains null bytes"));
}
// Validate characters
for ch in path.chars() {
match ch {
'a'..='z' | 'A'..='Z' | '0'..='9' | '_' | '-' | '.' | '/' => {}
_ => {
return Err(ModuleError::security_violation(format!(
"Invalid character in path: '{}'",
ch
)));
}
}
}
Ok(())
}
/// Check for forbidden patterns
fn check_forbidden_patterns(&self, path: &str) -> ModuleResult<()> {
for pattern in &self.forbidden_patterns {
if path.contains(pattern) {
return Err(ModuleError::security_violation(format!(
"Forbidden pattern '{}' in path",
pattern
)));
}
}
// Additional checks for path traversal attempts
let components: Vec<&str> = path.split('/').collect();
for component in components {
if component == ".." || component == "." {
return Err(ModuleError::security_violation(
"Path traversal attempt detected",
));
}
if component.is_empty() {
return Err(ModuleError::security_violation("Empty path component"));
}
}
Ok(())
}
/// Construct a safe path within project bounds
fn construct_safe_path(&self, path: &str) -> ModuleResult<PathBuf> {
let mut safe_path = self.project_root.clone();
// Parse path components safely
let path_buf = PathBuf::from(path);
for component in path_buf.components() {
match component {
Component::Normal(name) => {
safe_path.push(name);
}
_ => {
return Err(ModuleError::security_violation(format!(
"Invalid path component: {:?}",
component
)));
}
}
}
// Add .script extension if not present
if safe_path.extension().is_none() {
safe_path.set_extension("script");
}
Ok(safe_path)
}
/// Validate file extension
fn validate_extension(&self, path: &Path) -> ModuleResult<()> {
let extension = path
.extension()
.and_then(|ext| ext.to_str())
.ok_or_else(|| ModuleError::security_violation("Invalid or missing file extension"))?;
if !self.allowed_extensions.contains(extension) {
return Err(ModuleError::security_violation(format!(
"Forbidden file extension: .{}",
extension
)));
}
Ok(())
}
/// Ensure path stays within project bounds
fn validate_within_bounds(&self, path: &Path) -> ModuleResult<()> {
// Canonicalize to resolve any remaining .. or symlinks
let canonical = path.canonicalize().map_err(|e| {
ModuleError::security_violation(format!("Failed to canonicalize path: {}", e))
})?;
// Check if canonical path is within project root
if !canonical.starts_with(&self.project_root) {
return Err(ModuleError::security_violation(
"Path escapes project boundary",
));
}
Ok(())
}
/// Validate no symlinks in path
fn validate_no_symlinks(&self, path: &Path) -> ModuleResult<()> {
// Check each component for symlinks
let mut current = PathBuf::new();
for component in path.components() {
current.push(component);
if current.exists() && current.is_symlink() {
return Err(ModuleError::security_violation(format!(
"Symlink detected in path: {:?}",
current
)));
}
}
Ok(())
}
/// Get a safe display path (relative to project root)
pub fn safe_display_path(&self, path: &Path) -> String {
if let Ok(relative) = path.strip_prefix(&self.project_root) {
relative.display().to_string()
} else {
"<external>".to_string()
}
}
}
/// Module path sanitizer for safe path operations
pub struct ModulePathSanitizer;
impl ModulePathSanitizer {
/// Sanitize a module identifier for use in paths
pub fn sanitize_module_name(name: &str) -> ModuleResult<String> {
if name.is_empty() {
return Err(ModuleError::security_violation("Empty module name"));
}
if name.len() > 64 {
return Err(ModuleError::security_violation(
"Module name too long (max: 64 characters)",
));
}
let mut sanitized = String::with_capacity(name.len());
for ch in name.chars() {
match ch {
'a'..='z' | 'A'..='Z' | '0'..='9' | '_' => sanitized.push(ch),
'-' | '.' => sanitized.push('_'),
_ => {
return Err(ModuleError::security_violation(format!(
"Invalid character in module name: '{}'",
ch
)));
}
}
}
// Check for reserved names
let reserved = ["script", "mod", "lib", "bin", "test", "bench"];
if reserved.contains(&sanitized.as_str()) {
return Err(ModuleError::security_violation(format!(
"Reserved module name: {}",
sanitized
)));
}
Ok(sanitized)
}
/// Convert module path segments to safe file path
pub fn module_path_to_file_path(segments: &[String]) -> ModuleResult<String> {
if segments.is_empty() {
return Err(ModuleError::security_violation("Empty module path"));
}
let mut path_parts = Vec::with_capacity(segments.len());
for segment in segments {
let sanitized = Self::sanitize_module_name(segment)?;
path_parts.push(sanitized);
}
Ok(path_parts.join("/"))
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
use tempfile::TempDir;
#[test]
fn test_path_traversal_protection() {
let temp_dir = TempDir::new().unwrap();
let validator = PathSecurityValidator::new(temp_dir.path().to_path_buf()).unwrap();
// Test various path traversal attempts
assert!(validator.validate_module_path("../etc/passwd").is_err());
assert!(validator.validate_module_path("../../root").is_err());
assert!(validator.validate_module_path("./../../etc").is_err());
assert!(validator.validate_module_path("foo/../../../bar").is_err());
assert!(validator.validate_module_path("foo/..\\..\\bar").is_err());
}
#[test]
fn test_absolute_path_rejection() {
let temp_dir = TempDir::new().unwrap();
let validator = PathSecurityValidator::new(temp_dir.path().to_path_buf()).unwrap();
assert!(validator.validate_module_path("/etc/passwd").is_err());
assert!(validator
.validate_module_path("\\windows\\system32")
.is_err());
assert!(validator.validate_module_path("C:\\malicious").is_err());
}
#[test]
fn test_forbidden_patterns() {
let temp_dir = TempDir::new().unwrap();
let validator = PathSecurityValidator::new(temp_dir.path().to_path_buf()).unwrap();
assert!(validator.validate_module_path("~/.ssh/id_rsa").is_err());
assert!(validator.validate_module_path("$HOME/secrets").is_err());
assert!(validator.validate_module_path("%APPDATA%/config").is_err());
}
#[test]
fn test_valid_module_paths() {
let temp_dir = TempDir::new().unwrap();
let validator = PathSecurityValidator::new(temp_dir.path().to_path_buf()).unwrap();
// Create test directories
fs::create_dir_all(temp_dir.path().join("src/utils")).unwrap();
fs::write(temp_dir.path().join("src/utils/helpers.script"), "").unwrap();
// Test valid paths
assert!(validator.validate_module_path("src/utils/helpers").is_ok());
assert!(validator.validate_module_path("lib/core").is_ok());
assert!(validator.validate_module_path("app/main").is_ok());
}
#[test]
fn test_module_name_sanitization() {
assert!(ModulePathSanitizer::sanitize_module_name("valid_module123").is_ok());
assert!(ModulePathSanitizer::sanitize_module_name("ValidModule").is_ok());
assert!(ModulePathSanitizer::sanitize_module_name("../evil").is_err());
assert!(ModulePathSanitizer::sanitize_module_name("evil$module").is_err());
assert!(ModulePathSanitizer::sanitize_module_name("").is_err());
assert!(ModulePathSanitizer::sanitize_module_name(&"x".repeat(100)).is_err());
}
}