Repository navigation
Expand file tree
/
Copy pathsecurity.rs
More file actions
424 lines (377 loc) · 14.8 KB
/
Copy pathsecurity.rs
File metadata and controls
424 lines (377 loc) · 14.8 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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
//! Module-specific security context and trust management
//!
//! This module provides security contexts for Script modules, including trust levels,
//! permission management, and signature verification for safe module loading.
use crate::module::{ModuleError, ModulePath};
use std::collections::HashMap;
use std::path::PathBuf;
/// Trust level for a module
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum TrustLevel {
/// Core system modules with full privileges
System,
/// Trusted modules with standard privileges
Trusted,
/// Untrusted modules with restricted privileges
Untrusted,
/// Sandboxed modules with minimal privileges
Sandbox,
/// Unknown trust level (default)
Unknown,
}
impl TrustLevel {
/// Returns true if this trust level allows the given capability
pub fn allows_capability(&self, capability: &ModuleCapability) -> bool {
match (self, capability) {
// System modules can do anything
(TrustLevel::System, _) => true,
// Trusted modules have most capabilities except system operations
(TrustLevel::Trusted, ModuleCapability::SystemCall) => false,
(TrustLevel::Trusted, ModuleCapability::UnsafeCode) => false,
(TrustLevel::Trusted, _) => true,
// Untrusted modules have limited capabilities
(TrustLevel::Untrusted, ModuleCapability::FileRead(_)) => true,
(TrustLevel::Untrusted, ModuleCapability::NetworkConnect(_)) => false,
(TrustLevel::Untrusted, ModuleCapability::FileWrite(_)) => false,
(TrustLevel::Untrusted, ModuleCapability::ProcessSpawn) => false,
(TrustLevel::Untrusted, ModuleCapability::FFICall) => false,
(TrustLevel::Untrusted, ModuleCapability::SystemCall) => false,
(TrustLevel::Untrusted, ModuleCapability::UnsafeCode) => false,
(TrustLevel::Untrusted, ModuleCapability::ResourceAllocation { .. }) => true,
// Sandboxed modules have minimal capabilities
(TrustLevel::Sandbox, ModuleCapability::ResourceAllocation { cpu_time, memory }) => {
// Very restricted resources for sandboxed modules
*cpu_time <= 1000 && *memory <= 10_000_000 // 10MB
}
(TrustLevel::Sandbox, _) => false,
// Unknown trust level defaults to no capabilities
(TrustLevel::Unknown, _) => false,
}
}
/// Get the maximum resource limits for this trust level
pub fn resource_limits(&self) -> ResourceLimits {
match self {
TrustLevel::System => ResourceLimits::unlimited(),
TrustLevel::Trusted => ResourceLimits {
max_memory: 1_000_000_000, // 1GB
max_cpu_time: 60_000, // 60 seconds
max_file_handles: 100,
max_network_connections: 50,
max_threads: 10,
},
TrustLevel::Untrusted => ResourceLimits {
max_memory: 100_000_000, // 100MB
max_cpu_time: 10_000, // 10 seconds
max_file_handles: 10,
max_network_connections: 0,
max_threads: 1,
},
TrustLevel::Sandbox => ResourceLimits {
max_memory: 10_000_000, // 10MB
max_cpu_time: 1_000, // 1 second
max_file_handles: 0,
max_network_connections: 0,
max_threads: 0,
},
TrustLevel::Unknown => ResourceLimits {
max_memory: 10_000_000, // 10MB - conservative default
max_cpu_time: 1_000, // 1 second
max_file_handles: 0,
max_network_connections: 0,
max_threads: 0,
},
}
}
}
/// Capabilities that a module might request
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum ModuleCapability {
/// Read access to specific file paths
FileRead(PathBuf),
/// Write access to specific file paths
FileWrite(PathBuf),
/// Network connection to specific hosts
NetworkConnect(String),
/// Ability to spawn processes
ProcessSpawn,
/// Ability to call FFI functions
FFICall,
/// Ability to make system calls
SystemCall,
/// Ability to execute unsafe code
UnsafeCode,
/// Resource allocation limits
ResourceAllocation { cpu_time: u64, memory: usize },
}
/// Resource limits for a module
#[derive(Debug, Clone)]
pub struct ResourceLimits {
pub max_memory: usize,
pub max_cpu_time: u64,
pub max_file_handles: usize,
pub max_network_connections: usize,
pub max_threads: usize,
}
impl ResourceLimits {
/// Create unlimited resource limits (for system modules)
pub fn unlimited() -> Self {
ResourceLimits {
max_memory: usize::MAX,
max_cpu_time: u64::MAX,
max_file_handles: usize::MAX,
max_network_connections: usize::MAX,
max_threads: usize::MAX,
}
}
}
/// Security context for a module
#[derive(Debug, Clone)]
pub struct ModuleSecurityContext {
/// Module path
pub module_path: ModulePath,
/// Trust level
pub trust_level: TrustLevel,
/// Granted capabilities
pub capabilities: Vec<ModuleCapability>,
/// Resource limits
pub resource_limits: ResourceLimits,
/// Module signature (for verification)
pub signature: Option<ModuleSignature>,
/// Parent module that loaded this module
pub parent_module: Option<ModulePath>,
}
impl ModuleSecurityContext {
/// Create a new security context for a module
pub fn new(module_path: ModulePath, trust_level: TrustLevel) -> Self {
let resource_limits = trust_level.resource_limits();
ModuleSecurityContext {
module_path,
trust_level,
capabilities: Vec::new(),
resource_limits,
signature: None,
parent_module: None,
}
}
/// Check if a capability is allowed
pub fn check_capability(&self, capability: &ModuleCapability) -> Result<(), ModuleError> {
// First check trust level
if !self.trust_level.allows_capability(capability) {
return Err(ModuleError::security_violation(format!(
"Module {} with trust level {:?} cannot use capability {:?}",
self.module_path, self.trust_level, capability
)));
}
// Then check explicit capabilities
if self.capabilities.contains(capability) {
Ok(())
} else {
Err(ModuleError::security_violation(format!(
"Module {} does not have capability {:?}",
self.module_path, capability
)))
}
}
/// Add a capability to this context
pub fn grant_capability(&mut self, capability: ModuleCapability) -> Result<(), ModuleError> {
// Check if trust level allows this capability
if !self.trust_level.allows_capability(&capability) {
return Err(ModuleError::security_violation(format!(
"Cannot grant capability {:?} to module with trust level {:?}",
capability, self.trust_level
)));
}
if !self.capabilities.contains(&capability) {
self.capabilities.push(capability);
}
Ok(())
}
}
/// Module signature for verification
#[derive(Debug, Clone)]
pub struct ModuleSignature {
/// Cryptographic hash of the module content
pub content_hash: Vec<u8>,
/// Digital signature
pub signature: Vec<u8>,
/// Public key ID used for signing
pub key_id: String,
}
/// Module security manager
pub struct ModuleSecurityManager {
/// Security contexts for loaded modules
pub contexts: HashMap<ModulePath, ModuleSecurityContext>,
/// Default trust level for new modules
default_trust_level: TrustLevel,
/// Trusted module patterns
trusted_patterns: Vec<String>,
/// System module patterns
system_patterns: Vec<String>,
}
impl ModuleSecurityManager {
/// Create a new module security manager
pub fn new() -> Self {
ModuleSecurityManager {
contexts: HashMap::new(),
default_trust_level: TrustLevel::Untrusted,
trusted_patterns: vec![],
system_patterns: vec!["std.*".to_string(), "core.*".to_string()],
}
}
/// Get or create security context for a module
pub fn get_or_create_context(
&mut self,
module_path: &ModulePath,
) -> &mut ModuleSecurityContext {
let trust_level = self.determine_trust_level(module_path);
self.contexts
.entry(module_path.clone())
.or_insert_with(|| ModuleSecurityContext::new(module_path.clone(), trust_level))
}
/// Determine trust level for a module based on patterns
fn determine_trust_level(&self, module_path: &ModulePath) -> TrustLevel {
let path_str = module_path.to_string();
// Check system patterns
for pattern in &self.system_patterns {
if Self::matches_pattern(&path_str, pattern) {
return TrustLevel::System;
}
}
// Check trusted patterns
for pattern in &self.trusted_patterns {
if Self::matches_pattern(&path_str, pattern) {
return TrustLevel::Trusted;
}
}
self.default_trust_level
}
/// Simple pattern matching (supports * wildcard)
fn matches_pattern(path: &str, pattern: &str) -> bool {
if pattern.ends_with('*') {
let prefix = &pattern[..pattern.len() - 1];
path.starts_with(prefix)
} else {
path == pattern
}
}
/// Add a trusted module pattern
pub fn add_trusted_pattern(&mut self, pattern: String) {
self.trusted_patterns.push(pattern);
}
/// Add a system module pattern
pub fn add_system_pattern(&mut self, pattern: String) {
self.system_patterns.push(pattern);
}
/// Set default trust level for new modules
pub fn set_default_trust_level(&mut self, level: TrustLevel) {
self.default_trust_level = level;
}
/// Check if a module can import from another module
pub fn check_import_permission(
&self,
importer: &ModulePath,
imported: &ModulePath,
) -> Result<(), ModuleError> {
let importer_ctx = self.contexts.get(importer).ok_or_else(|| {
ModuleError::security_violation(format!(
"No security context for importing module {}",
importer
))
})?;
let imported_ctx = self.contexts.get(imported).ok_or_else(|| {
ModuleError::security_violation(format!(
"No security context for imported module {}",
imported
))
})?;
// Sandbox modules cannot import from outside their sandbox
if importer_ctx.trust_level == TrustLevel::Sandbox {
if imported_ctx.trust_level != TrustLevel::Sandbox {
return Err(ModuleError::security_violation(format!(
"Sandboxed module {} cannot import from non-sandboxed module {}",
importer, imported
)));
}
}
// Untrusted modules cannot import system modules
if importer_ctx.trust_level == TrustLevel::Untrusted
&& imported_ctx.trust_level == TrustLevel::System
{
return Err(ModuleError::security_violation(format!(
"Untrusted module {} cannot import system module {}",
importer, imported
)));
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_trust_level_capabilities() {
// System level allows everything
assert!(TrustLevel::System.allows_capability(&ModuleCapability::SystemCall));
assert!(TrustLevel::System.allows_capability(&ModuleCapability::UnsafeCode));
// Trusted level allows most things
assert!(TrustLevel::Trusted.allows_capability(&ModuleCapability::FileRead(PathBuf::new())));
assert!(TrustLevel::Trusted
.allows_capability(&ModuleCapability::NetworkConnect("example.com".to_string())));
assert!(!TrustLevel::Trusted.allows_capability(&ModuleCapability::SystemCall));
// Untrusted level is restricted
assert!(
TrustLevel::Untrusted.allows_capability(&ModuleCapability::FileRead(PathBuf::new()))
);
assert!(
!TrustLevel::Untrusted.allows_capability(&ModuleCapability::FileWrite(PathBuf::new()))
);
assert!(!TrustLevel::Untrusted
.allows_capability(&ModuleCapability::NetworkConnect("example.com".to_string())));
// Sandbox level is highly restricted
assert!(!TrustLevel::Sandbox.allows_capability(&ModuleCapability::FileRead(PathBuf::new())));
assert!(
TrustLevel::Sandbox.allows_capability(&ModuleCapability::ResourceAllocation {
cpu_time: 500,
memory: 5_000_000
})
);
}
#[test]
fn test_module_security_context() {
let module_path = ModulePath::from_string("test.module").unwrap();
let mut ctx = ModuleSecurityContext::new(module_path.clone(), TrustLevel::Trusted);
// Can grant allowed capabilities
assert!(ctx
.grant_capability(ModuleCapability::FileRead(PathBuf::new()))
.is_ok());
assert!(ctx
.grant_capability(ModuleCapability::NetworkConnect("example.com".to_string()))
.is_ok());
// Cannot grant disallowed capabilities
assert!(ctx.grant_capability(ModuleCapability::SystemCall).is_err());
// Check capability works
assert!(ctx
.check_capability(&ModuleCapability::FileRead(PathBuf::new()))
.is_ok());
assert!(ctx
.check_capability(&ModuleCapability::ProcessSpawn)
.is_err());
}
#[test]
fn test_module_security_manager() {
let mut manager = ModuleSecurityManager::new();
// System modules get system trust level
let std_path = ModulePath::from_string("std.io").unwrap();
let std_ctx = manager.get_or_create_context(&std_path);
assert_eq!(std_ctx.trust_level, TrustLevel::System);
// Regular modules get default trust level
let user_path = ModulePath::from_string("myapp.module").unwrap();
let user_ctx = manager.get_or_create_context(&user_path);
assert_eq!(user_ctx.trust_level, TrustLevel::Untrusted);
// Add trusted pattern
manager.add_trusted_pattern("mycompany.*".to_string());
let company_path = ModulePath::from_string("mycompany.utils").unwrap();
let company_ctx = manager.get_or_create_context(&company_path);
assert_eq!(company_ctx.trust_level, TrustLevel::Trusted);
}
}