This is an interesting security design challenge. I need to implement a capability-based security model (similar to some research operating systems like KeyKOS or seL4) for a toy filesystem. Let me break down the requirements:
- Capability-Based Security: Instead of traditional ACLs, processes must have tokens (capabilities) to access resources
- Token Inheritance: Child processes should inherit capabilities from parent processes
- Token Revocation: There should be a mechanism to revoke capabilities
- Unix-like operations: Should support common filesystem operations
Key concepts to implement:
- Capability Objects: Tokens that grant specific permissions
- Processes: With capability lists
- Resources: Filesystem objects that require capabilities for access
- Capability Inheritance: Parent passes capabilities to children
- Capability Revocation: Mechanisms to revoke previously granted capabilities
I'll implement this with the following components:
Capability class: Represents a token with specific rights
Resource class: Filesystem object that requires capabilities
Process class: Represents a running process with a set of capabilities
FileSystem class: Manages the filesystem and enforces capability checks
- Supporting classes for operations and results
Let me design a comprehensive implementation:
from enum import Enum, Flag
from dataclasses import dataclass, field
from typing import Dict, List, Set, Optional, Tuple
from uuid import uuid4
from datetime import datetime
import json
# ==================== Capability Model ====================
class CapabilityRight(Flag):
"""Individual rights that can be held in a capability"""
READ = 1 # Can read resource
WRITE = 2 # Can write/modify resource
EXECUTE = 4 # Can execute/access resource
DELETE = 8 # Can delete resource
GRANT = 16 # Can grant capability to others
REVOKE = 32 # Can revoke capabilities
ADMIN = 64 # Administrative access
Now I need to define the resource types and the capability structure itself. Resources can be files, directories, or devices, and each capability is an unforgeable token tied to a specific resource and holder. The capability tracks when it was issued, whether it has an expiration date, and if it's been revoked.
class ResourceType(Enum):
"""Types of filesystem resources"""
FILE = "file"
DIRECTORY = "directory"
DEVICE = "device"
@dataclass
class Capability:
"""
A capability token that grants specific rights on a resource.
Each capability is unforgeable and can only be used by its holder.
"""
resource_id: str
rights: CapabilityRight
holder_id: str # Process ID that holds this capability
issued_at: datetime = field(default_factory=datetime.now)
expires_at: Optional[datetime] = None
revoked: bool = False
Each capability gets a unique ID and I need methods to validate it—checking if it's been revoked or has expired—and to verify what rights it actually grants. The has_right method checks for individual permissions while has_all_rights ensures all requested permissions are present.
capability_id: str = field(default_factory=lambda: str(uuid4()))
def is_valid(self) -> bool:
"""Check if capability is still valid"""
if self.revoked:
return False
if self.expires_at and datetime.now() > self.expires_at:
return False
return True
def has_right(self, right: CapabilityRight) -> bool:
"""Check if capability grants a specific right"""
return bool(self.rights & right)
def has_all_rights(self, rights: CapabilityRight) -> bool:
"""Check if capability grants all specified rights"""
return (self.rights & rights) == rights
def __repr__(self):
return (f"Cap({self.resource_id[:8]}..., "
f"rights={self.rights.name}, valid={self.is_valid()})")
@dataclass
class CapabilityGrant:
"""Record of a capability grant operation"""
from_process: str
to_process: str
capability_id: str
rights_granted: CapabilityRight
timestamp: datetime = field(default_factory=datetime.now)
grant_id: str = field(default_factory=lambda: str(uuid4()))
# ==================== Resource Model ====================
@dataclass
class Resource:
"""Represents a filesystem resource"""
resource_id: str
name: str
resource_type: ResourceType
owner_id: str # Process that created it
content: str = ""
created_at: datetime = field(default_factory=datetime.now)
modified_at: datetime = field(default_factory=datetime.now)
children: Dict[str, str] = field(default_factory=dict) # name -> resource_id
metadata: Dict = field(default_factory=dict)
def __repr__(self):
return f"{self.resource_type.value}({self.name})"
# ==================== Process Model ====================
@dataclass
class ProcessContext:
"""Execution
A process needs to track its capabilities and any grants it's made or received. I can retrieve valid capabilities for a specific resource and check if the process holds particular rights. The list_capabilities method filters to only active, non-expired capabilities.
process_id: str
parent_id: Optional[str]
capabilities: List[Capability] = field(default_factory=list)
grants_received: List[CapabilityGrant] = field(default_factory=list)
grants_made: List[CapabilityGrant] = field(default_factory=list)
created_at: datetime = field(default_factory=datetime.now)
def get_capability(self, resource_id: str) -> Optional[Capability]:
"""Get a valid capability for a resource"""
for cap in self.capabilities:
if cap.resource_id == resource_id and cap.is_valid():
return cap
return None
def has_right(self, resource_id: str, right: CapabilityRight) -> bool:
"""Check if process has specific right on resource"""
cap = self.get_capability(resource_id)
return cap is not None and cap.has_right(right)
def add_capability(self, capability: Capability):
"""Add a capability to the process"""
self.capabilities.append(capability)
def list_capabilities(self) -> List[Capability]:
"""Get all valid capabilities"""
return [c for c in self.capabilities if c.is_valid()]
# ==================== Operations ====================
class OperationType(Enum):
READ = "read"
WRITE = "write"
DELETE = "delete"
EXECUTE = "execute"
GRANT = "grant"
REVOKE = "revoke"
CREATE = "create"
@dataclass
class OperationResult:
"""Result of a filesystem operation"""
success: bool
operation_type: OperationType
resource_id: str
process_id: str
message: str
timestamp: datetime = field(default_factory=datetime.now)
details: Dict = field(default_factory=dict)
def __repr__(self):
status = "✓" if self.success else "✗"
return (f"{status} {self.operation_type.value}({self.resource_id[:8]}) "
f"by {self.process_id[:8]}: {self.message}")
# ==================== Audit Log ====================
@dataclass
class AuditLogEntry:
"""Record of security-relevant events"""
timestamp: datetime
event_type: str
process_id: str
resource_id: Optional[str]
details: str
success: bool
entry_id: str = field(default_factory=lambda: str(uuid4()))
def __repr__(self):
return f"[{self.timestamp.strftime('%H:%M:%S')}] {self.event_type}: {self.details}"
# ==================== Capability-Based Filesystem ====================
class CapabilityFileSystem:
"""
A filesystem implementation using capability-based security.
Processes must possess capabilities to access resources.
"""
def __init__(self):
self.processes: Dict[str, ProcessContext] = {}
self.resources
The filesystem maintains process and resource registries along with an audit log and revocation chains to track capability dependencies. During initialization, I create a root process with full permissions on the root resource. When spawning child processes, I can inherit all parent capabilities or select specific ones, tracking each inherited capability as a dependent in the revocation chain. The audit log records all security-relevant operations for accountability. False
)
return None
# Verify process has write capability on parent
process = self.processes[process_id]
if not process.has_right(parent_id, CapabilityRight.WRITE):
self._audit_log_entry(
"create_resource", process_id, parent_id,
f"No WRITE capability on parent",
False
)
return None
# Instantiate the resource
resource_id = f"r_{uuid4().hex[:8]}"
resource = Resource(
resource_id=resource_id,
name=name,
resource_type=resource_type,
owner_id=process_id
)
self.resources[resource_id] = resource
parent.children[name] = resource_id
I'm checking that the process has the necessary write permission before allowing resource creation, then generating a unique identifier and storing the new resource in the system while linking it to its parent directory.
Now I need to grant the creator complete control over the newly created resource by assigning all capability rights, register the capability in the system, and log the successful creation. The read_resource method then validates that both the process and resource exist before attempting to retrieve the content.
For read operations, I check whether the requesting process holds READ capability on the target resource. If the capability check fails, I deny access and log the denial. On success, I return the resource content along with an audit entry noting how many bytes were read.
Now for write operations, I follow a similar pattern: first validating that both the process and resource exist, then verifying the process has WRITE capability before allowing the modification. If authorization fails, I log the denial and return an error result.
When the write succeeds, I update the resource content and timestamp, log the operation with the number of bytes written, and return a successful result. The delete operation begins with the same existence checks for the process.
I need to verify the resource exists, then check if the process has DELETE capability. If not, I log the denial and return failure. If the process lacks the necessary right, the operation is rejected.
Once those checks pass, I remove the resource from its parent's children (unless it's the root resource), delete it from the resources dictionary, log the successful deletion, and return a success result.
Now for granting capabilities between processes, I need to verify both the source and destination processes exist in the system before proceeding with the capability transfer.
I should check that the resource itself is registered, then retrieve both process objects. The grantor must possess a capability for that resource that includes the GRANT right—if not, the operation fails and gets logged. Additionally, a process cannot delegate rights it doesn't already have, so I need to validate that the grantor's capability encompasses all the rights being transferred.
Once those checks pass, I create a new capability object with the requested rights and assign it to the recipient process. I maintain the revocation chain by linking the new capability to its parent, then record the grant transaction in the grantor's history. having capability revoked
resource_id: Resource to revoke access to
Returns:
(success, message)
"""
if revoker_id not in self.processes:
return False, "Revoker process not found"
if holder_id not in self.processes:
return False, "Holder process not found"
if resource_id not in self.resources:
return False, "Resource not found"
revoker = self.processes[revoker_id]
holder = self.processes[holder_id]
resource = self.resources[resource_id]
# Check revocation rights
if revoker_id != resource.owner_id:
revoker_cap = revoker.get_capability(resource_id)
if r
I need to see more of the next thinking to complete this partial thought. The revocation rights check is incomplete - I can't determine what condition is being evaluated or what happens next without seeing the rest of the logic. chains[capability_id]:
for process in self.processes.values():
for cap in process.capabilities:
if cap.capability_id == dependent_id:
cap.revoked = True
count += self._cascade_revoke(dependent_id)
return count
def get_process_capabilities(self, process_id: str) -> List[Capability]:
"""Get all valid capabilities held by a process"""
if process_id not in self.processes:
return []
return self.processes[process_id].list_capabilities()
def list_resources(self, process_id: str,
parent_id: Optional[str] = None) -> OperationResult:
"""List resources
The cascade revocation traverses the dependency chain, marking each derived capability as revoked and recursively processing its dependents to propagate the revocation throughout the hierarchy. Once all dependent capabilities are processed, the total count is returned. The helper methods retrieve capabilities for a given process and support hierarchical resource listing.
For resource enumeration, the method first validates that both the process and parent directory exist, then checks whether the requesting process holds READ rights on the parent. It iterates through child resources, filtering to only those the process has some capability over, and begins constructing metadata for each accessible child.
The operation returns successfully with a list of visible children, including their names, IDs, and resource types. Additionally, there's a helper function to retrieve process metadata, which gathers information like creation timestamp, total capability count, and details about each capability the process holds, including the resource it grants access to and its validity status. = fs.create_resource(root, "document.txt", ResourceType.FILE)
print(f"✓ Created file: {file1[:8]}...")
result = fs.write_resource(root, file1, "Hello, World!")
print(f"✓ {result}")
result = fs.read_resource(root, file1)
print(f"✓ {result}")
print(f" Content: {result.details['content']}")
# 2. CHILD PROCESS CREATION WITH FULL INHERITANCE
print("\n[2] CHILD PROCESS WITH FULL CAPABILITY INHERITANCE")
print("-" * 70)
child1 = fs.spawn_process(root)
print(f"✓ Created child process: {child1[:8]}...")
The root process creates a file resource and performs read/write operations on it. Then a child process is spawned that inherits all capabilities from its parent.
info = fs.get_process_info(child1)
print(f"✓ Child inherited {info['capabilities_count']} capabilities")
result = fs.read_resource(child1, file1)
print(f"✓ Child read file: {result.message}")
# 3. SELECTIVE CAPABILITY INHERITANCE
print("\n[3] SELECTIVE CAPABILITY INHERITANCE")
print("-" * 70)
file2 = fs.create_resource(root, "secret.txt", ResourceType.FILE)
fs.write_resource(root, file2, "Secret data")
print(f"✓ Created secret file: {file2[:8]}...")
# Get root's capabilities
root_caps = fs.get_process_capabilities(root)
cap_ids = [c.capability_id for c in root_caps[:1]] # Only first capability
child2 = fs.spawn_process(root, inherited_capabilities=cap_ids)
print(f"✓ Created child with selective inheritance")
info = fs.
I can verify the child process successfully inherited all capabilities and can access the parent's resources. Then I create a second file and spawn another child with restricted capabilities—passing only the first capability from the parent's set rather than the full inheritance.
Now I check that child2 has the limited capability count, then move into testing capability granting between peer processes. I spawn two sibling processes and verify that one can read inherited resources while the other cannot, then demonstrate how the first peer can explicitly grant its capability to the second peer using the grant_capability function.
After the grant succeeds, I confirm the second peer now has access to the resource. Then I test permission restriction by creating a new process and granting it only READ rights, verifying it can read but respecting the limited permission scope.
Next, I verify that child5 cannot write to the file since only READ was granted, and it also cannot grant capabilities to other processes since it lacks the GRANT right. Then I move into testing resource creation by child processes, where child1 creates a new directory to demonstrate that spawned processes can generate their own resources.
After that, I test capability revocation by checking child4's capabilities before and after revoking its access to file1. The revocation is attempted first by child3, but if that fails, root performs it instead. Once revoked, I confirm child4 can no longer read the file.
Then I move into cascade revocation testing by creating a delegation chain from root through child7, child8, and child9. I verify each process in the chain can initially read file1, then proceed to test what happens when revoking at different points in the chain.
When I revoke the capability from root to child7, I check how this impacts all three child processes—whether child7 loses access immediately, and whether child8 and child9 retain or lose their inherited capabilities. Finally, I examine the security audit log to trace all the operations that occurred during testing.
Then I retrieve detailed process information for both the root and child1 processes, including their creation timestamps, capability counts, and the number of grants each has made or received.
After displaying the child process details, the demonstration concludes with a completion message. Following that, a new test function begins to validate security violations, initializing a fresh capability filesystem and creating a protected file resource to verify that unauthorized access attempts are properly blocked. don't have")
child2 = fs.spawn_process(root, inherited_capabilities=[])
success, msg = fs.grant_capability(child, child2, file1, CapabilityRight.READ)
assert not success, "Should not allow grant without GRANT capability"
print(f"✓ BLOCKED: {msg}\n")
print("[TEST 5] Cannot grant beyond your rights")
# Give child READ only
fs.grant_capability(root, child, file1, CapabilityRight.READ)
child3 = fs.spawn_process(root, inherited_capabilities=[])
# Try to grant WRITE
success, msg = fs.grant_capability(
child, child3, file1,
CapabilityRight.READ | CapabilityRight.WRITE
)
assert not success
The tests verify that processes can't delegate capabilities they don't possess, and can't escalate permissions beyond what they've been granted. A process with only READ access attempting to grant WRITE permissions should fail. class ProcessCapabilityAudit:
"""Detailed audit trail for a specific process"""
def init(self, process_id: str):
self.process_id = process_id
self.capability_grants: List[CapabilityGrant] = []
self.capability_revocations: List[Tuple[str, datetime]] = []
def add_grant(self, grant: CapabilityGrant):
self.capability_grants.append(grant)
def add_revocation(self, capability_id: str):
self.capability_revocations.append((capability_id, datetime.now()))
I'm tracking grants and revocations with timestamps to maintain a complete history of capability changes for each process. This gives me visibility into what permissions were granted when and what was later removed.
Capability-Based Security Model for Toy Filesystem
I'll implement a comprehensive capability-based security system with token inheritance, revocation, and cascading effects.
from enum import Enum, Flag
from dataclasses import dataclass, field
from typing import Dict, List, Set, Optional, Tuple
from uuid import uuid4
from datetime import datetime, timedelta
import json
# ==================== Core Security Model ====================
class CapabilityRight(Flag):
"""Individual rights that can be held in a capability"""
READ = 1 # Can read resource
WRITE = 2 # Can write/modify resource
EXECUTE = 4 # Can execute/access resource
DELETE = 8 # Can delete resource
GRANT = 16 # Can grant capability to others
REVOKE = 32 # Can revoke capabilities
ADMIN = 64 # Administrative access
class ResourceType(Enum):
"""Types of filesystem resources"""
FILE = "file"
DIRECTORY = "directory"
DEVICE = "device"
@dataclass
class Capability:
"""
An unforgeable token granting specific rights on a resource.
Capabilities are the basis of all access control.
"""
resource_id: str
rights: CapabilityRight
holder_id: str # Process ID that holds this capability
issued_at: datetime = field(default_factory=datetime.now)
parent_cap_id: Optional[str] = None # For tracking delegation chain
expires_at: Optional[datetime] = None
revoked: bool = False
capability_id: str = field(default_factory=lambda: str(uuid4()))
def is_valid(self) -> bool:
"""Check if capability is still valid"""
if self.revoked:
return False
if self.expires_at and datetime.now() > self.expires_at:
return False
return True
def has_right(self, right: CapabilityRight) -> bool:
"""Check if capability grants a specific right"""
return bool(self.rights & right)
def has_all_rights(self, rights: CapabilityRight) -> bool:
"""Check if capability grants all specified rights"""
return (self.rights & rights) == rights
def __repr__(self):
status = "✓" if self.is_valid() else "✗"
rights_str = "+".join([r.name for r in CapabilityRight if self.rights & r])
return f"{status}Cap({rights_str}@{self.resource_id[:6]})"
@dataclass
class Resource:
"""Represents a filesystem resource"""
resource_id: str
name: str
resource_type: ResourceType
owner_id: str # Process that created it
content: str = ""
created_at: datetime = field(default_factory=datetime.now)
modified_at: datetime = field(default_factory=datetime.now)
children: Dict[str, str] = field(default_factory=dict) # name -> resource_id
metadata: Dict = field(default_factory=dict)
def __repr__(self):
return f"{self.resource_type.value}({self.name})"
@dataclass
class ProcessContext:
"""Execution context for a process"""
process_id: str
parent_id: Optional[str]
capabilities: List[Capability] = field(default_factory=list)
grants_received: List['CapabilityGrant'] = field(default_factory=list)
grants_made: List['CapabilityGrant'] = field(default_factory=list)
created_at: datetime = field(default_factory=datetime.now)
terminated: bool = False
def get_capability(self, resource_id: str) -> Optional[Capability]:
"""Get a valid capability for a resource"""
for cap in self.capabilities:
if cap.resource_id == resource_id and cap.is_valid():
return cap
return None
def has_right(self, resource_id: str, right: CapabilityRight) -> bool:
"""Check if process has specific right on resource"""
cap = self.get_capability(resource_id)
return cap is not None and cap.has_right(right)
def list_capabilities(self) -> List[Capability]:
"""Get all valid capabilities"""
return [c for c in self.capabilities if c.is_valid()]
@dataclass
class CapabilityGrant:
"""Record of a capability grant operation"""
from_process: str
to_process: str
capability_id: str
rights_granted: CapabilityRight
timestamp: datetime = field(default_factory=datetime.now)
grant_id: str = field(default_factory=lambda: str(uuid4()))
@dataclass
class AuditLogEntry:
"""Security-relevant event record"""
timestamp: datetime
event_type: str
process_id: str
resource_id: Optional[str]
details: str
success: bool
entry_id: str = field(default_factory=lambda: str(uuid4()))
@dataclass
class OperationResult:
"""Result of a filesystem operation"""
success: bool
event_type: str
resource_id: str
process_id: str
message: str
timestamp: datetime = field(default_factory=datetime.now)
details: Dict = field(default_factory=dict)
# ==================== Capability-Based Filesystem ====================
class CapabilityFileSystem:
"""
Filesystem using capability-based security instead of ACLs.
All access is mediated through unforgeable capability tokens.
"""
def __init__(self):
self.processes: Dict[str, ProcessContext] = {}
self.resources: Dict[str, Resource] = {}
self.audit_log: List[AuditLogEntry] = []
self.revocation_chains: Dict[str, Set[str]] = {} # capability_id -> dependent_ids
self.delegation_depth: Dict[str, int] = {} # capability_id -> delegation_count
self._init_root()
def _init_root(self):
"""Initialize root process and resource"""
root_id = "p_root"
root_resource_id = "r_root"
root_process = ProcessContext(process_id=root_id, parent_id=None)
self.processes[root_id] = root_process
root_resource = Resource(
resource_id=root_resource_id,
name="/",
resource_type=ResourceType.DIRECTORY,
owner_id=root_id
)
self.resources[root_resource_id] = root_resource
# Root gets full capabilities
root_cap = Capability(
resource_id=root_resource_id,
rights=(CapabilityRight.READ | CapabilityRight.WRITE |
CapabilityRight.EXECUTE | CapabilityRight.DELETE |
CapabilityRight.GRANT | CapabilityRight.REVOKE |
CapabilityRight.ADMIN),
holder_id=root_id
)
root_process.capabilities.append(root_cap)
self.revocation_chains[root_cap.capability_id] = set()
self.delegation_depth[root_cap.capability_id] = 0
def _audit_log(self, event_type: str, process_id: str,
resource_id: Optional[str], details: str, success: bool):
"""Add entry to audit log"""
entry = AuditLogEntry(
timestamp=datetime.now(),
event_type=event_type,
process_id=process_id,
resource_id=resource_id,
details=details,
success=success
)
self.audit_log.append(entry)
def spawn_process(self, parent_id: str,
inherited_capabilities: Optional[List[str]] = None,
drop_revoke_right: bool = False) -> Optional[str]:
"""
Spawn a child process with capability inheritance.
Args:
parent_id: Parent process ID
inherited_capabilities: Specific capability IDs to inherit (None = all)
drop_revoke_right: Remove REVOKE right from inherited capabilities
Returns:
New process ID or None if failed
"""
if parent_id not in self.processes:
self._audit_log(
"spawn_process", parent_id, None,
"Parent process not found", False
)
return None
parent = self.processes[parent_id]
child_id = f"p_{uuid4().hex[:8]}"
child_process = ProcessContext(process_id=child_id, parent_id=parent_id)
# Determine which capabilities to inherit
source_caps = parent.list_capabilities()
caps_to_inherit = source_caps if inherited_capabilities is None else [
c for c in source_caps if c.capability_id in inherited_capabilities
]
# Inherit capabilities
for parent_cap in caps_to_inherit:
# Create new capability for child
new_rights = parent_cap.rights
# Optionally drop REVOKE right
if drop_revoke_right:
new_rights = new_rights & ~CapabilityRight.REVOKE
child_cap = Capability(
resource_id=parent_cap.resource_id,
rights=new_rights,
holder_id=child_id,
parent_cap_id=parent_cap.capability_id,
expires_at=parent_cap.expires_at,
capability_id=str(uuid4())
)
child_process.capabilities.append(child_cap)
# Track revocation chain
if parent_cap.capability_id not in self.revocation_chains:
self.revocation_chains[parent_cap.capability_id] = set()
self.revocation_chains[parent_cap.capability_id].add(child_cap.capability_id)
self.revocation_chains[child_cap.capability_id] = set()
# Track delegation depth
parent_depth = self.delegation_depth.get(parent_cap.capability_id, 0)
self.delegation_depth[child_cap.capability_id] = parent_depth + 1
self.processes[child_id] = child_process
self._audit_log(
"spawn_process", parent_id, None,
f"Created process {child_id} with {len(caps_to_inherit)} capabilities",
True
)
return child_id
def create_resource(self, process_id: str, name: str,
resource_type: ResourceType,
parent_id: Optional[str] = None) -> Optional[str]:
"""Create a new filesystem resource"""
if process_id not in self.processes:
return None
if parent_id is None:
parent_id = "r_root"
if parent_id not in self.resources:
self._audit_log(
"create_resource", process_id, None,
f"Parent {parent_id} not found", False
)
return None
process = self.processes[process_id]
parent = self.resources[parent_id]
# Check WRITE capability on parent
if not process.has_right(parent_id, CapabilityRight.WRITE):
self._audit_log(
"create_resource", process_id, parent_id,
"Denied: No WRITE capability", False
)
return None
# Create resource
resource_id = f"r_{uuid4().hex[:8]}"
resource = Resource(
resource_id=resource_id,
name=name,
resource_type=resource_type,
owner_id=process_id
)
self.resources[resource_id] = resource
parent.children[name] = resource_id
# Grant creator full capabilities
creator_cap = Capability(
resource_id=resource_id,
rights=(CapabilityRight.READ | CapabilityRight.WRITE |
CapabilityRight.EXECUTE | CapabilityRight.DELETE |
CapabilityRight.GRANT | CapabilityRight.REVOKE),
holder_id=process_id
)
process.capabilities.append(creator_cap)
self.revocation_chains[creator_cap.capability_id] = set()
self.delegation_depth[creator_cap.capability_id] = 0
self._audit_log(
"create_resource", process_id, resource_id,
f"Created {resource_type.value} '{name}'", True
)
return resource_id
def read_resource(self, process_id: str, resource_id: str) -> OperationResult:
"""Read resource content"""
if process_id not in self.processes:
msg = "Process not found"
self._audit_log("read", process_id, resource_id, msg, False)
return OperationResult(False, "read", resource_id, process_id, msg)
if resource_id not in self.resources:
msg = "Resource not found"
self._audit_log("read", process_id, resource_id, msg, False)
return OperationResult(False, "read", resource_id, process_id, msg)
process = self.processes[process_id]
resource = self.resources[resource_id]
# Check READ capability
if not process.has_right(resource_id, CapabilityRight.READ):
msg = "Denied: No READ capability"
self._audit_log("read", process_id, resource_id, msg, False)
return OperationResult(False, "read", resource_id, process_id, msg)
self._audit_log(
"read", process_id, resource_id,
f"Read {len(resource.content)} bytes", True
)
return OperationResult(
True, "read", resource_id, process_id, "Read successful",
details={"content": resource.content, "size": len(resource.content)}
)
def write_resource(self, process_id: str, resource_id: str,
content: str) -> OperationResult:
"""Write to resource"""
if process_id not in self.processes:
return OperationResult(False, "write", resource_id, process_id,
"Process not found")
if resource_id not in self.resources:
return OperationResult(False, "write", resource_id, process_id,
"Resource not found")
process = self.processes[process_id]
resource = self.resources[resource_id]
# Check WRITE capability
if not process.has_right(resource_id, CapabilityRight.WRITE):
self._audit_log("write", process_id, resource_id,
"Denied: No WRITE capability", False)
return OperationResult(False, "write", resource_id, process_id,
"Denied: No WRITE capability")
old_content = resource.content
resource.content = content
resource.modified_at = datetime.now()
self._audit_log("write", process_id, resource_id,
f"Wrote {len(content)} bytes", True)
return OperationResult(
True, "write", resource_id, process_id, "Write successful",
details={"size": len(content)}
)
def delete_resource(self, process_id: str, resource_id: str) -> OperationResult:
"""Delete a resource"""
if process_id not in self.processes:
return OperationResult(False, "delete", resource_id, process_id,
"Process not found")
if resource_id not in self.resources:
return OperationResult(False, "delete", resource_id, process_id,
"Resource not found")
process = self.processes[process_id]
resource = self.resources[resource_id]
# Check DELETE capability
if not process.has_right(resource_id, CapabilityRight.DELETE):
self._audit_log("delete", process_id, resource_id,
"Denied: No DELETE capability", False)
return OperationResult(False, "delete", resource_id, process_id,
"Denied: No DELETE capability")
# Remove from parent
for other_resource in self.resources.values():
if resource_id in other_resource.children.values():
del other_resource.children[
[k for k, v in other_resource.children.items()
if v == resource_id][0]
]
del self.resources[resource_id]
self._audit_log("delete", process_id, resource_id, "Deleted", True)
return OperationResult(
True, "delete", resource_id, process_id, "Delete successful"
)
def grant_capability(self, from_process_id: str, to_process_id: str,
resource_id: str, rights: CapabilityRight,
max_delegation_depth: Optional[int] = None) -> Tuple[bool, str]:
"""
Grant capability from one process to another.
Cannot grant rights you don't possess.
Args:
from_process_id: Granting process
to_process_id: Recipient process
resource_id: Resource capability is for
rights: Rights to grant
max_delegation_depth: Maximum delegation chain length
Returns:
(success, message)
"""
if from_process_id not in self.processes:
return False, "Granting process not found"
if to_process_id not in self.processes:
return False, "Recipient process not found"
if resource_id not in self.resources:
return False, "Resource not found"
from_process = self.processes[from_process_id]
to_process = self.processes[to_process_id]
# Get grantor's capability
grantor_cap = from_process.get_capability(resource_id)
if grantor_cap is None:
self._audit_log("grant_capability", from_process_id, resource_id,
"No capability to grant", False)
return False, "You don't have a capability to grant"
# Check GRANT right
if not grantor_cap.has_right(CapabilityRight.GRANT):
self._audit_log("grant_capability", from_process_id, resource_id,
"Denied: No GRANT capability", False)
return False, "No GRANT right"
# Can't grant rights you don't have
if not grantor_cap.has_all_rights(rights):
self._audit_log("grant_capability", from_process_id, resource_id,
"Attempt to grant unrestricted rights", False)
return False, "Cannot grant rights beyond what you possess"
# Check delegation depth limits
current_depth = self.delegation_depth.get(grantor_cap.capability_id, 0)
if max_delegation_depth and current_depth >= max_delegation_depth:
return False, f"Delegation depth limit ({max_delegation_depth}) exceeded"
# Create new capability
new_cap = Capability(
resource_id=resource_id,
rights=rights,
holder_id=to_process_id,
parent_cap_id=grantor_cap.capability_id,
expires_at=grantor_cap.expires_at,
capability_id=str(uuid4())
)
to_process.capabilities.append(new_cap)
# Track revocation chain
if grantor_cap.capability_id not in self.revocation_chains:
self.revocation_chains[grantor_cap.capability_id] = set()
self.revocation_chains[grantor_cap.capability_id].add(new_cap.capability_id)
self.revocation_chains[new_cap.capability_id] = set()
self.delegation_depth[new_cap.capability_id] = current_depth + 1
# Record grant
grant = CapabilityGrant(
from_process=from_process_id,
to_process=to_process_id,
capability_id=new_cap.capability_id,
rights_granted=rights
)
from_process.grants_made.append(grant)
to_process.grants_received.append(grant)
rights_str = "+".join([r.name for r in CapabilityRight if rights & r])
self._audit_log("grant_capability", from_process_id, resource_id,
f"Granted {rights_str} to {to_process_id}", True)
return True, f"Granted {rights_str}"
def revoke_capability(self, revoker_id: str, holder_id: str,
resource_id: str, cascade: bool = True) -> Tuple[bool, str]:
"""
Revoke capability. Only resource owner or holders with REVOKE right can revoke.
Optionally cascades revocation to derived capabilities.
Args:
revoker_id: Process performing revocation
holder_id: Process having capability revoked
resource_id: Resource to revoke access to
cascade: Whether to cascade revocation to derived capabilities
Returns:
(success, message)
"""
if revoker_id not in self.processes:
return False, "Revoker process not found"
if holder_id not in self.processes:
return False, "Holder process not found"
if resource_id not in self.resources:
return False, "Resource not found"
revoker = self.processes[revoker_id]
holder = self.processes[holder_id]
resource = self.resources[resource_id]
# Check revocation authority
is_owner = revoker_id == resource.owner_id
has_revoke_right = revoker.has_right(resource_id, CapabilityRight.REVOKE)
if not (is_owner or has_revoke_right):
self._audit_log("revoke_capability", revoker_id, resource_id,
"Denied: No revocation authority", False)
return False, "No authority to revoke"
# Find capability to revoke
target_cap = next(
(c for c in holder.capabilities if c.resource_id == resource_id),
None
)
if target_cap is None or not target_cap.is_valid():
return False, "No valid capability to revoke"
# Revoke the capability
target_cap.revoked = True
revoked_count = 1
# Cascade revocation if requested
if cascade:
revoked_count += self._cascade_revoke(target_cap.capability_id)
self._audit_log("revoke_capability", revoker_id, resource_id,
f"Revoked capability ({revoked_count} total revoked)", True)
return True, f"Revoked {revoked_count} capability/capabilities"
def _cascade_revoke(self, capability_id: str) -> int:
"""
Recursively revoke all capabilities derived from given capability.
Returns count of revoked capabilities.
"""
count = 0
if capability_id in self.revocation_chains:
for dependent_id in self.revocation_chains[capability_id]:
for process in self.processes.values():
for cap in process.capabilities:
if cap.capability_id == dependent_id and not cap.revoked:
cap.revoked = True
count += 1 + self._cascade_revoke(dependent_id)
return count
def list_resources(self, process_id: str,
parent_id: Optional[str] = None) -> OperationResult:
"""List resources in a directory that process has access to"""
if process_id not in self.processes:
return OperationResult(False, "list", "", process_id,
"Process not found")
if parent_id is None:
parent_id = "r_root"
if parent_id not in self.resources:
return OperationResult(False, "list", parent_id, process_id,
"Parent not found")
process = self.processes[process_id]
parent = self.resources[parent_id]
# Check READ on directory
if not process.has_right(parent_id, CapabilityRight.READ):
return OperationResult(False, "list", parent_id, process_id,
"No READ capability on directory")
# List visible children
children = []
for name, child_id in parent.children.items():
if child_id in self.resources and process.get_capability(child_id):
child = self.resources[child_id]
children.append({
"name": name,
"id": child_id[:8],
"type": child.resource_type.value
})
return OperationResult(
True, "list", parent_id, process_id,
f"Listed {len(children)} resources",
details={"children": children}
)
def get_capability_chain(self, process_id: str,
resource_id: str) -> Optional[List[Dict]]:
"""Get the delegation chain for a capability"""
if process_id not in self.processes:
return None
process = self.processes[process_id]
cap = process.get_capability(resource_id)
if cap is None:
return None
chain = [{
"holder": process_id,
"capability_id": cap.capability_id,
"rights": cap.rights.name,
"depth": self.delegation_depth.get(cap.capability_id, 0)
}]
# Trace back to parent
current_cap = cap
while current_cap.parent_cap_id:
parent_cap_id = current_cap.parent_cap_id
# Find parent cap
found = False
for p in self.processes.values():
for c in p.capabilities:
if c.capability_id == parent_cap_id:
chain.insert(0, {
"holder": p.process_id,
"capability_id": c.capability_id,
"rights": c.rights.name,
"depth": self.delegation_depth.get(c.capability_id, 0)
})
current_cap = c
found = True
break
if found:
break
if not found:
break
return chain
def get_process_info(self, process_id: str) -> Optional[Dict]:
"""Get detailed process information"""
if process_id not in self.processes:
return None
process = self.processes[process_id]
caps = process.list_capabilities()
return {
"process_id": process_id,
"parent_id": process.parent_id,
"created_at": process.created_at.isoformat(),
"valid_capabilities": len(caps),
"total_capabilities": len(process.capabilities),
"capabilities": [
{
"id": c.capability_id[:8],
"resource": c.resource_id[:8],
"rights": "+".join([r.name for r in CapabilityRight if c.rights & r]),
"valid": c.is_valid(),
"depth": self.delegation_depth.get(c.capability_id, 0)
}
for c in process.capabilities
],
"grants_made": len(process.grants_made),
"grants_received": len(process.grants_received)
}
def audit_log_summary(self, limit: int = 20) -> List[str]:
"""Get recent audit log entries"""
entries = []
for entry in self.audit_log[-limit:]:
status = "✓" if entry.success else "✗"
resource_str = entry.resource_id[:8] if entry.resource_id else "N/A"
process_str = entry.process_id[:8]
entries.append(
f"{status} {entry.event_type:20} | "
f"Process {process_str} | Resource {resource_str} | {entry.details}"
)
return entries
# ==================== Demonstration ====================
def demo_basic_operations():
"""Basic filesystem operations with capability checking"""
print("\n" + "="*80)
print("1. BASIC OPERATIONS - Capability Enforcement")
print("="*80)
fs = CapabilityFileSystem()
root = "p_root"
# Create resources
file1 = fs.create_resource(root, "document.txt", ResourceType.FILE)
print(f"✓ Root created file: {file1[:8]}...")
result = fs.write_resource(root, file1, "Hello, Secure World!")
print(f"✓ Root wrote to file: {result.message}")
result = fs.read_resource(root, file1)
print(f"✓ Root read file: {result.details['content']}")
def demo_capability_inheritance():
"""Child process inheriting capabilities"""
print("\n" + "="*80)
print("2. CAPABILITY INHERITANCE - Child Processes")
print("="*80)
fs = CapabilityFileSystem()
root = "p_root"
# Create resources
file1 = fs.create_resource(root, "data.txt", ResourceType.FILE)
fs.write_resource(root, file1, "Important data")
# Full inheritance
child1 = fs.spawn_process(root)
print(f"✓ Created child with full inheritance")
info = fs.get_process_info(child1)
print(f" Child has {info['valid_capabilities']} valid capabilities")
result = fs.read_resource(child1, file1)
print(f" Child can read: {result.success}")
# Selective inheritance
root_caps = fs.get_process_capabilities(root)
root_cap_ids = [c.capability_id for c in root_caps]
child2 = fs.spawn_process(root, inherited_capabilities=root_cap_ids[:1])
print(f"\n✓ Created child with selective inheritance (1 capability)")
info = fs.get_process_info(child2)
print(f" Child has {info['valid_capabilities']} valid capabilities")
# Limited inheritance with dropped REVOKE
child3 = fs.spawn_process(root, drop_revoke_right=True)
print(f"\n✓ Created child without REVOKE right")
info = fs.get_process_info(child3)
for cap in info['capabilities']:
if 'REVOKE' in cap['rights']:
print(f" ERROR: Child has REVOKE!")
else:
print(f" ✓ REVOKE properly removed from capabilities")
def demo_process_get_process_capabilities(fs, process_id):
"""Helper to get process capabilities"""
if process_id not in fs.processes:
return []
return fs.processes[process_id].list_capabilities()
def demo_capability_granting():
"""Process granting capabilities to other processes"""
print("\n" + "="*80)
print("3. CAPABILITY GRANTING - Process to Process")
print("="*80)
fs = CapabilityFileSystem()
root = "p_root"
# Setup
file1 = fs.create_resource(root, "shared.txt", ResourceType.FILE)
fs.write_resource(root, file1, "Shared resource")
# Create two child processes
child1 = fs.spawn_process(root)
child2 = fs.spawn_process(root)
print(f"✓ Created two child processes")
# Child1 can read (inherited)
result = fs.read_resource(child1, file1)
print(f" Child1 can read: {result.success}")
# Grant READ to child2 from root
success, msg = fs.grant_capability(root, child2, file1, CapabilityRight.READ)
print(f"\n✓ Root granted READ to Child2: {msg}")
result = fs.read_resource(child2, file1)
print(f" Child2 can now read: {result.success}")
# Child1 grants its capability to child2
success, msg = fs.grant_capability(child1, child2, file1, CapabilityRight.WRITE)
print(f"\n✓ Child1 granted WRITE to Child2: {msg}")
# Show capability chain
chain = fs.get_capability_chain(child2, file1)
if chain:
print(f"\n Capability chain for Child2->File1:")
for step in chain:
print(f" - {step['holder'][:8]}: {step['rights']} (depth {step['depth']})")
def demo_permission_restriction():
"""Testing that you can't grant more than you have"""
print("\n" + "="*80)
print("4. PERMISSION RESTRICTION - Least Privilege Principle")
print("="*80)
fs = CapabilityFileSystem()
root = "p_root"
file1 = fs.create_resource(root, "protected.txt", ResourceType.FILE)
child1 = fs.spawn_process(root)
child2 = fs.spawn_process(root)
# Grant only READ to child1
fs.grant_capability(root, child1, file1, CapabilityRight.READ)
print(f"✓ Child1 has READ capability only")
# Try to grant WRITE
success, msg = fs.grant_capability(child1, child2, file1,
CapabilityRight.READ | CapabilityRight.WRITE)
print(f"✗ Child1 cannot grant WRITE (doesn't have it): {msg}")
# Try without GRANT right by removing it
child3 = fs.spawn_process(root)
# Remove GRANT right from a capability
for cap in fs.get_process_capabilities(child3):
if cap.resource_id == file1:
cap.rights = cap.rights & ~CapabilityRight.GRANT
child4 = fs.spawn_process(root)
success, msg = fs.grant_capability(child3, child4, file1, CapabilityRight.READ)
print(f"✗ Child3 cannot grant (no GRANT right): {msg}")
def demo_revocation():
"""Capability revocation and cascading effects"""
print("\n" + "="*80)
print("5. CAPABILITY REVOCATION - Cascading Revocation")
print("="*80)
fs = CapabilityFileSystem()
root = "p_root"
file1 = fs.create_resource(root, "revokable.txt", ResourceType.FILE)
fs.write_resource(root, file1, "Data")
# Create chain: root -> child1 -> child2 -> child3
child1 = fs.spawn_process(root)
child2 = fs.spawn_process(child1)
child3 = fs.spawn_process(child2)
print(f"✓ Created delegation chain: root->child1->child2->child3")
# Verify all can access
print(f"\n Before revocation:")
for child, name in [(child1, "child1"), (child2, "child2"), (child3, "child3")]:
result = fs.read_resource(child, file1)
print(f" {name}: {'✓' if result.success else '✗'}")
# Revoke from middle (child1)
success, msg = fs.revoke_capability(root, child1, file1)
print(f"\n✓ Revoked from child1: {msg}")
# Check cascade effect
print(f"\n After revocation:")
for child, name in [(child1, "child1"), (child2, "child2"), (child3, "child3")]:
result = fs.read_resource(child, file1)
print(f" {name}: {'✓' if result.success else '✗'}")
def demo_access_denial():
"""Unauthorized access attempts"""
print("\n" + "="*80)
print("6. ACCESS DENIAL - Security Violations Blocked")
print("="*80)
fs = CapabilityFileSystem()
root = "p_root"
file1 = fs.create_resource(root, "restricted.txt", ResourceType.FILE)
fs.write_resource(root, file1, "Secret")
# Child with no capabilities
child = fs.spawn_process(root, inherited_capabilities=[])
print(f"✓ Created process with no capabilities")
tests = [
("READ", lambda: fs.read_resource(child, file1)),
("WRITE", lambda: fs.write_resource(child, file1, "Hacked")),
("DELETE", lambda: fs.delete_resource(child, file1)),
]
for name, operation in tests:
result = operation()
print(f" {name}: {'✓ Denied' if not result.success else '✗ ALLOWED!'} - {result.message}")
def demo_audit_trail():
"""Security audit log"""
print("\n" + "="*80)
print("7. AUDIT TRAIL - Security Event Logging")
print("="*80)
fs = CapabilityFileSystem()
root = "p_root"
# Perform operations
file1 = fs.create_resource(root, "audit_test.txt", ResourceType.FILE)
fs.write_resource(root, file1, "Test data")
child = fs.spawn_process(root)
fs.read_resource(child, file1)
# Try unauthorized access
child2 = fs.spawn_process(root, inherited_capabilities=[])
fs.read_resource(child2, file1)
# Show audit log
print(f"\n Recent security events:")
for entry in fs.audit_log_summary(limit=10):
print(f" {entry}")
def run_all_demos():
"""Run all demonstrations"""
demo_basic_operations()
demo_capability_inheritance()
demo_capability_granting()
demo_permission_restriction()
demo_revocation()
demo_access_denial()
demo_audit_trail()
print("\n" + "="*80)
print("ALL DEMONSTRATIONS COMPLETE")
print("="*80 + "\n")
if __name__ == "__main__":
run_all_demos()
Key Features
1. Capability-Based Model
- Unforgeable tokens granting specific rights
- Rights cannot be forged or escalated
2. Inheritance
- Full or selective capability passing to children
- Optional right dropping (e.g., remove REVOKE)
- Tracks delegation chains
3. Capability Granting
- Process can grant capabilities it possesses
- Cannot grant rights it doesn't have
- Prevents privilege escalation
4. Revocation System
- Cascading revocation down delegation chains
- Resource owner can always revoke
- REVOKE right holders can revoke
5. Security Enforcement
- All filesystem operations checked
- Audit logging of security events
- Clear denial messages
6. Advanced Features
- Delegation depth tracking
- Expiration timestamps
- Capability chain visualization
- Detailed audit trails
This implementation provides a robust capability-based security model suitable for research or educational purposes!