A robust Python-based sandbox environment for executing untrusted code with comprehensive resource limits, process isolation, and real-time monitoring capabilities.
- Overview
- Features
- Architecture
- Directory Structure
- Installation
- Usage
- Configuration
- Monitoring & Analysis
- Security Features
- Examples
- Troubleshooting
- Contributing
- License
This sandbox environment provides a secure, isolated execution environment for running Python scripts with strict resource constraints. It implements multiple layers of security including process isolation, resource limits, file system restrictions, and comprehensive monitoring.
- Resource Control: CPU time and memory usage limits
- Process Isolation: Fork-based process separation
- File System Security: Chroot jail implementation
- Real-time Monitoring: Live CPU and memory tracking
- Persistent Logging: Timestamped execution logs
- Visual Analytics: Memory usage graphs and statistics
β CPU Time Limiting
- Set maximum CPU execution time in seconds
- Automatic process termination on timeout
- Uses
resource.setrlimit(RLIMIT_CPU)
β Memory Limiting
- Control maximum memory allocation (MB)
- Prevents memory exhaustion attacks
- Uses
resource.setrlimit(RLIMIT_AS)
β Process Isolation
- Fork-based execution in child process
- Parent process monitoring and control
- Clean separation of execution contexts
β File System Isolation
- Chroot jail implementation
- Restricts file system access
- Optional --no-chroot mode for testing
β Real-time Monitoring
- Live CPU percentage tracking
- Memory usage monitoring (MB)
- 0.1-second polling interval
β Comprehensive Logging
- Timestamped log files (YYYYMMDD_HHMMSS)
- Detailed execution metrics
- Process lifecycle tracking
- Exit status recording
π Memory Visualization
- Generate PNG graphs of memory usage over time
- Track memory trends during execution
- Identify memory spikes and patterns
π Statistical Analysis
- Average CPU and memory usage
- Peak resource consumption
- Process duration metrics
- Visual ASCII charts
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β SANDBOX ENVIRONMENT β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β ββββββββββββββββββ βββββββββββββββββββ β
β β Parent Process βββββββββββ€ User Command β β
β β (Monitor) β βββββββββββββββββββ β
β ββββββββββ¬βββββββββ β
β β β
β β fork() β
β βΌ β
β ββββββββββββββββββββββββββββββββββββββββββ β
β β Child Process (Sandboxed) β β
β ββββββββββββββββββββββββββββββββββββββββββ€ β
β β 1. Set Resource Limits (CPU/Memory) β β
β β 2. Apply Chroot Jail (Optional) β β
β β 3. Execute User Code β β
β β 4. Report Status β β
β ββββββββββββββββββββββββββββββββββββββββββ β
β β β
β β Real-time Monitoring (psutil) β
β βΌ β
β ββββββββββββββββββββββββββββββββββββββββββ β
β β Monitoring & Logging System β β
β ββββββββββββββββββββββββββββββββββββββββββ€ β
β β β’ CPU Usage Tracking β β
β β β’ Memory Usage Tracking β β
β β β’ Timestamped Logging β β
β β β’ Process State Management β β
β ββββββββββββββββββββββββββββββββββββββββββ β
β β β
β βΌ β
β ββββββββββββββββββββββββββββββββββββββββββ β
β β Log Files & Reports β β
β β logs/sandbox_run_YYYYMMDD_HHMMSS.log β β
β ββββββββββββββββββββββββββββββββββββββββββ β
β β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
User Command
β
βΌ
Parse Arguments (--cpu, --mem, --no-chroot)
β
βΌ
Fork Process
βββββββββββββββββββ
β β
βΌ βΌ
Parent Process Child Process
(Monitor) (Execute)
β β
β ββ Set CPU Limit
β ββ Set Memory Limit
β ββ Apply Chroot (optional)
β ββ Execute Code
β ββ Exit with Status
β
ββ Monitor CPU/Memory (0.1s intervals)
ββ Log Metrics
ββ Check Timeout
ββ Wait for Child & Report
sandbox_project/
β
βββ π README.md # This file - Complete project documentation
βββ π SETUP_INSTRUCTIONS.md # Detailed setup and installation guide
βββ π GITHUB_PUSH_INSTRUCTIONS.md # Git and GitHub setup instructions
βββ π IMPLEMENTATION_STATUS.md # Feature implementation status
βββ π requirements.txt # Python dependencies list
βββ π .gitignore # Git ignore configuration
β
βββ π§ setup_sandbox.sh # Automated sandbox setup script
βββ π§ setup_jail.sh # Chroot jail setup helper
βββ π§ test_script.py # Sample test script (infinite loop)
β
βββ π src/ # Main source code directory
β βββ π __init__.py # Package initialization
β βββ π sandbox.py # Main sandbox implementation (with chroot)
β β # β’ Resource limiting
β β # β’ Process isolation
β β # β’ Chroot jail support
β β # β’ Real-time monitoring
β β # β’ Logging system
β β
β βββ π sandbox_test.py # Test sandbox (optional chroot)
β # β’ --no-chroot flag support
β # β’ Testing without root privileges
β
βββ π tests/ # Test directory
β βββ π __init__.py # Test package initialization
β
βββ π docs/ # Documentation directory
β βββ π logging_visualization.md # Logging system documentation
β β # β’ Log format specification
β β # β’ Visualization guide
β β # β’ Analysis tools usage
β β
β βββ π setup_guide.md # Detailed setup guide
β # β’ System requirements
β # β’ Installation steps
β # β’ Configuration options
β
βββ π logs/ # Execution logs (auto-generated, gitignored)
β βββ sandbox_run_YYYYMMDD_HHMMSS.log # Timestamped execution logs
β # Format: sandbox_run_20251011_143022.log
β
βββ π sandbox_root/ # Chroot jail directory (gitignored)
β βββ python3 # Python binary (copied)
β βββ test_script.py # Scripts to execute
β βββ (additional binaries/libs) # Required libraries
β
βββ π venv/ # Virtual environment (gitignored)
β βββ (Python packages) # Isolated dependencies
β
βββ π visualize_log.py # Memory usage graph generator
β # β’ Parses log files
β # β’ Creates PNG graphs
β # β’ Shows memory trends
β
βββ π analyze_log.py # Log analysis and statistics tool
# β’ CPU/Memory statistics
# β’ Peak usage detection
# β’ ASCII chart visualization
| File | Purpose | Key Functions |
|---|---|---|
src/sandbox.py |
Main sandbox implementation | Resource limits, process isolation, chroot jail, monitoring |
src/sandbox_test.py |
Test version with optional chroot | Same as sandbox.py + --no-chroot flag |
visualize_log.py |
Memory usage visualization | Parses logs, generates graphs (PNG) |
analyze_log.py |
Log analysis tool | Statistics, peak detection, ASCII charts |
setup_jail.sh |
Chroot setup automation | Creates jail, copies binaries |
test_script.py |
Sample test script | Infinite loop for testing limits |
requirements.txt |
Python dependencies | psutil, matplotlib, etc. |
- Python: 3.12 or higher
- Operating System: Linux (Ubuntu/Debian recommended)
- Privileges: Root access required for chroot functionality
- Disk Space: ~500MB (including dependencies)
# Check Python version
python3 --version # Should be 3.12+
# Required system tools
sudo apt update
sudo apt install python3 python3-pip python3-venv git# 1. Clone the repository
git clone git@github.com:Divyansh-9/sandbox-project.git
cd sandbox-project
# 2. Create virtual environment
python3 -m venv venv
source venv/bin/activate # On Linux/Mac
# OR
venv\Scripts\activate # On Windows
# 3. Install dependencies
pip install -r requirements.txt
# 4. Create necessary directories
mkdir -p logs sandbox_root
# 5. (Optional) Setup chroot jail
bash setup_jail.shThe project requires the following Python packages:
psutil==7.1.0 # Process and system monitoring
matplotlib==3.10.6 # Graph generation
numpy==2.2.1 # Numerical operations
# Activate virtual environment first
source venv/bin/activate
# Run sandbox with default limits
python3 src/sandbox.py --cpu 5 --mem 50 python3 test_script.py
# Run with custom limits
python3 src/sandbox.py --cpu 10 --mem 100 python3 your_script.pyUsage: python3 src/sandbox.py [OPTIONS] COMMAND
Options:
--cpu SECONDS CPU time limit in seconds (default: 5)
--mem MEGABYTES Memory limit in megabytes (default: 50)
--no-chroot Disable chroot isolation (for testing)
Arguments:
COMMAND The command to execute in the sandbox
Example: python3 script.py
Examples:
python3 src/sandbox.py --cpu 5 --mem 50 python3 test_script.py
python3 src/sandbox_test.py --cpu 10 --mem 100 --no-chroot python3 script.py
# Use sandbox_test.py with --no-chroot flag
python3 src/sandbox_test.py --cpu 5 --mem 50 --no-chroot python3 test_script.py# Set CPU time limit (in seconds)
--cpu 5 # Process will be terminated after 5 seconds of CPU timeHow it works:
- Uses
resource.RLIMIT_CPU - Kills process when CPU time exceeds limit
- Timeout protection adds 2 extra seconds for graceful shutdown
# Set memory limit (in megabytes)
--mem 50 # Process can use maximum 50MB of memoryHow it works:
- Uses
resource.RLIMIT_AS(address space) - Prevents memory allocation beyond limit
- Protects against memory exhaustion attacks
Logs are automatically created in the logs/ directory with the format:
logs/sandbox_run_YYYYMMDD_HHMMSS.log
Log Contents:
- Start timestamp
- PID of sandboxed process
- Real-time CPU and memory metrics
- Exit status and signal information
- End timestamp
Generate memory usage graphs from log files:
# Generate graph for latest log
python3 visualize_log.py logs/sandbox_run_20251011_143022.log
# Output: memory_usage_graph.pngAnalyze logs with detailed statistics:
# Analyze a specific log file
python3 analyze_log.py logs/sandbox_run_20251011_143022.logβββββββββββββββββββββββββββββββββββββββ
β Security Layer 1: Process β
β Isolation (fork) β
βββββββββββββββββββββββββββββββββββββββ€
β β Separate process space β
β β Independent execution context β
β β Parent-child communication β
βββββββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββ
β Security Layer 2: Resource β
β Limiting β
βββββββββββββββββββββββββββββββββββββββ€
β β CPU time restrictions β
β β Memory allocation limits β
β β Automatic termination β
βββββββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββ
β Security Layer 3: File System β
β Isolation (chroot) β
βββββββββββββββββββββββββββββββββββββββ€
β β Restricted file access β
β β Isolated directory tree β
β β Limited system exposure β
βββββββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββ
β Security Layer 4: Monitoring β
β & Logging β
βββββββββββββββββββββββββββββββββββββββ€
β β Real-time behavior tracking β
β β Audit trail creation β
β β Anomaly detection capability β
βββββββββββββββββββββββββββββββββββββββ
- This sandbox is NOT a complete security solution
- It provides defense in depth but shouldn't be the only security measure
- Chroot can be escaped by privileged processes
- Resource limits can be bypassed in some scenarios
- Always run untrusted code in additional isolation (VMs, containers)
# cpu_test.py
while True:
pass # Infinite CPU loop# Run with 5-second CPU limit
python3 src/sandbox.py --cpu 5 --mem 50 python3 cpu_test.py
# Expected: Process killed due to timeout# normal_script.py
import time
for i in range(5):
print(f"Count: {i}")
time.sleep(1)
print("Completed successfully!")# Run with adequate limits
python3 src/sandbox.py --cpu 10 --mem 100 python3 normal_script.pySolution:
# Use sudo for chroot operations
sudo python3 src/sandbox.py --cpu 5 --mem 50 python3 script.py
# OR use --no-chroot flag
python3 src/sandbox_test.py --cpu 5 --mem 50 --no-chroot python3 script.pySolution:
# Activate virtual environment
source venv/bin/activate
# Install dependencies
pip install -r requirements.txtSolution:
# Setup chroot jail
bash setup_jail.sh
# OR manually copy Python binary
sudo cp /usr/bin/python3 sandbox_root/Contributions are welcome! Please feel free to submit a Pull Request.
This project is licensed under the MIT License.
- Divyansh - Initial work - Divyansh-9
- GitHub: @Divyansh-9
- Project Link: https://github.com/Divyansh-9/sandbox-project
- v1.0.0 (2025-10-11)
- Initial release
- Core sandbox functionality
- Resource limiting (CPU, Memory)
- Process isolation
- Chroot jail support
- Real-time monitoring
- Logging system
- Analysis tools
# INSTALLATION
git clone git@github.com:Divyansh-9/sandbox-project.git
cd sandbox-project
python3 -m venv venv && source venv/bin/activate
pip install -r requirements.txt
# BASIC USAGE
python3 src/sandbox.py --cpu 5 --mem 50 python3 script.py
# WITHOUT ROOT
python3 src/sandbox_test.py --cpu 5 --mem 50 --no-chroot python3 script.py
# ANALYSIS
python3 analyze_log.py logs/sandbox_run_*.log
python3 visualize_log.py logs/sandbox_run_*.logMade with β€οΈ for secure code execution