-
Notifications
You must be signed in to change notification settings - Fork 0
15. Secure Code Execution Guide
This guide covers the bot's advanced secure code execution system with Docker-based sandboxing for safe Python code evaluation and competitive programming support.
- Overview
- Security Features
- Commands
- Configuration
- Installation & Setup
- Competitive Programming
- Language Support
- Troubleshooting
- Best Practices
The bot provides two secure execution environments for Python code:
- Full containerization with Docker isolation
- Resource limits: Memory, CPU, and execution time
- Network isolation: No external connectivity
- File system protection: Read-only containers
- Maximum security for untrusted code execution
- Subprocess-based execution when Docker unavailable
- Basic security with import restrictions
- Limited resource control (Unix systems only)
- Emergency fallback for environments without Docker
Feature | Docker Sandbox | Fallback Sandbox |
---|---|---|
Process Isolation | โ Full container | |
Memory Limits | โ Strict (128-256MB) | |
CPU Limits | โ Configurable | โ None |
Network Access | โ Blocked | โ Limited |
File System | โ Read-only | |
Import Blocking | โ Comprehensive | |
Timeout Control | โ Reliable |
The sandbox prevents access to dangerous operations:
# โ Blocked imports
import os # System access
import sys # System manipulation
import subprocess # Process execution
import socket # Network access
import threading # Concurrency
import __import__ # Dynamic imports
# โ Blocked functions
open() # File access (limited)
eval() # Code evaluation
exec() # Code execution
compile() # Code compilation
Safe operations that are permitted:
# โ
Allowed imports
import math # Mathematical functions
import random # Random number generation
import json # JSON processing
import re # Regular expressions
import datetime # Date/time handling
import collections # Data structures
import itertools # Iterator tools
# โ
Scientific libraries (Docker only)
import numpy # Numerical computing
import scipy # Scientific computing
import sympy # Symbolic mathematics
import networkx # Graph algorithms
Purpose: Execute Python code with full security restrictions and file upload support
Syntax:
/eval [code:"Python code"] [stdin_input:"input data"] [file:upload] [legacy_mode:false]
Parameters:
-
code
(optional): Python code to execute - can be blank when uploading files -
stdin_input
(optional): Input data for the program -
file
(optional): Upload Python (.py) or text (.txt) files up to 1MB -
legacy_mode
(optional): Use unsafe legacy mode (developers only)
File Upload Features:
- ๐ค Smart File Handling: Automatically uses file content when code parameter is blank
- ๐ Flexible Input: Can combine uploaded files with additional code
- ๐ File Validation: Supports .py and .txt files with size validation
- ๐ก Processing Feedback: Real-time file processing status with size information
Examples:
# Basic calculation
/eval code:"print(2 ** 10)"
# With input handling
/eval code:"name = input(); print(f'Hello, {name}!')" stdin_input:"Alice"
# Mathematical computation
/eval code:"import math; print(math.factorial(10))"
# List processing
/eval code:"nums = [1,2,3,4,5]; print(sum(x**2 for x in nums))"
# File upload only (leave code blank)
/eval file:my_script.py
# File upload with additional code
/eval code:"print('Starting computation')" file:algorithm.py
# File upload with stdin input
/eval file:interactive_script.py stdin_input:"user input data"
Purpose: Execute code with enhanced resources for algorithmic problems and comprehensive file upload support
Syntax:
/run [code:"code"] [language:"python"] [input_data:"test data"] [timeout:10] [file:upload]
Parameters:
-
code
(optional): Source code - can be blank when uploading files -
language
(optional): Programming language (auto-detected from file extension) -
input_data
(optional): Test case input -
timeout
(optional): Execution timeout (1-30 seconds) -
file
(optional): Upload source code files up to 5MB
File Upload Features:
- ๐ค Enhanced Upload Support: Multiple file types up to 5MB each
- ๐ Language Auto-Detection: Automatically detects language from file extensions
- ๐ Smart Code Handling: Uses file content when code parameter is blank
- ๐ก Flexible Combination: Can combine uploaded files with additional code
- ๐ Processing Feedback: Real-time file processing and validation status
Features:
- Enhanced resources: 256MB memory, full CPU access
- File uploads: Support for source files up to 5MB
- Multiple languages: Python ready, C++/Java with compilation support
- Test case support: Input/output file handling
- Language auto-detection: Determines language from file extensions
Examples:
# Algorithm with test data
/run code:"n=int(input()); print(sum(range(1,n+1)))" input_data:"100"
# File upload only (leave code blank)
/run file:solution.py input_data:"5\n1 2 3 4 5" timeout:15
# C++ file upload with auto-detection
/run file:algorithm.cpp input_data:"test case data"
# Combine file upload with additional code
/run code:"print('Debug mode')" file:main_solution.py input_data:"test data"
# Complex algorithm with file upload
/run file:advanced_algorithm.py input_data:"10
1 2 3 4 5 6 7 8 9 10" timeout:25
Add these to your .env
file:
# Sandboxing Configuration
ENABLE_DOCKER_SANDBOX=true # Use Docker for execution
SANDBOX_TIMEOUT=10 # Default timeout (seconds)
SANDBOX_MEMORY_LIMIT=128m # Memory limit (Docker format)
ENABLE_EVAL_COMMAND=true # Enable /eval command
ENABLE_RUN_COMMAND=true # Enable /run command
- Memory: 128MB
- CPU: 50% of one core
- Timeout: 10 seconds
- Output: 8192 characters max
- File upload size: 1MB max per file
- File types: .py and .txt files only
- Memory: 256MB
- CPU: 100% of one core
- Timeout: 1-30 seconds (configurable)
- Output: Enhanced output handling
- File upload size: 5MB max per file
- File types: Multiple extensions (.py, .cpp, .java, .c, .txt, etc.)
- Timeout: 1-30 seconds (configurable)
- Output: 16384 characters max
- File size: 5MB max
- Docker Installation (Recommended):
# Ubuntu/Debian
curl -fsSL https://get.docker.com -o get-docker.sh
sudo sh get-docker.sh
# Add user to docker group
sudo usermod -aG docker $USER
newgrp docker
# Test installation
docker run hello-world
- Python Dependencies:
pip install docker>=7.0.0
Test the sandbox system:
# Check Docker status
docker info
# Verify bot can access Docker
python -c "import docker; print(docker.from_env().ping())"
If Docker is unavailable, the system automatically uses subprocess execution:
# Install resource monitoring (Unix only)
pip install psutil
# Note: Limited security in fallback mode
- Sorting and searching algorithms
- Dynamic programming solutions
- Graph algorithms (with NetworkX)
- Mathematical computations
- String processing
- Array and list manipulations
- Tree and graph traversals
- Hash table implementations
- Stack and queue operations
- Number theory (with SymPy)
- Combinatorics and probability
- Linear algebra (with NumPy)
- Statistical analysis (with SciPy)
# Problem: Find sum of squares of first n natural numbers
/run code:"
n = int(input())
result = sum(i*i for i in range(1, n+1))
print(result)
" input_data:"5"
# Output: 55 (1ยฒ + 2ยฒ + 3ยฒ + 4ยฒ + 5ยฒ)
# Upload your solution file and test with multiple cases
/run input_data:"3
5
1 2 3 4 5
10
1 2 3 4 5 6 7 8 9 10
1
42"
# Test algorithm efficiency
/run code:"
import time
start = time.time()
# Your algorithm here
result = sorted([random.randint(1, 1000) for _ in range(1000)])
end = time.time()
print(f'Sorted {len(result)} numbers in {end-start:.3f}s')
" timeout:30
- Full support with extensive library ecosystem
- Scientific stack: NumPy, SciPy, SymPy, NetworkX
- Standard library: All safe modules available
- Package management: Pre-installed common packages
Available Libraries:
# Mathematical
import math, cmath, decimal, fractions, statistics
# Data structures
import collections, heapq, bisect, array
# Algorithms
import itertools, functools, operator
# I/O and formatting
import json, csv, re, string
# Scientific (Docker only)
import numpy as np
import scipy
import sympy
import networkx as nx
- GCC compiler with C++17/20 support
- STL (Standard Template Library)
- Compilation + execution pipeline
- Memory and time limit enforcement
- OpenJDK with standard libraries
- Compilation + execution
- Class file management
- Memory profiling support
- JavaScript execution environment
- NPM package support (limited)
- ES6+ syntax support
Error: "Docker client not available" Solution:
# Check Docker service
sudo systemctl status docker
# Start Docker if stopped
sudo systemctl start docker
# Verify user permissions
docker run hello-world
Error: "Permission denied" when running Docker Solution:
# Add user to docker group
sudo usermod -aG docker $USER
newgrp docker
# Or run bot with sudo (not recommended)
Error: Code execution times out Solutions:
- Increase timeout parameter:
/run timeout:30
- Optimize algorithm efficiency
- Use smaller test cases
- Check for infinite loops
Error: "Memory limit exceeded" Solutions:
- Reduce data structure sizes
- Use generators instead of lists
- Optimize memory usage
- Increase memory limit in config
Error: "Module 'xyz' is blocked" Solutions:
- Use allowed alternatives
- Check allowed operations
- Request module to be whitelisted
- Use legacy mode for testing (unsafe)
Enable debug logging to troubleshoot issues:
# In .env file
DEBUG=true
LOG_LEVEL=DEBUG
# Check logs
tail -f logs/bot.log | grep -i sandbox
Monitor system resources during execution:
# Check Docker stats
docker stats --no-stream
# Monitor system load
htop
# Check disk usage
df -h /tmp
- Always use Docker: Install Docker for production environments
- Avoid legacy mode: Only use for trusted code and testing
- Monitor execution: Watch for suspicious patterns
- Limit file sizes: Keep uploads reasonable
- Regular updates: Keep Docker images current
- Optimize algorithms: Write efficient code for better performance
- Use appropriate timeouts: Set realistic limits for your use case
- Minimize output: Large outputs slow down response
- Batch operations: Process multiple test cases efficiently
- Memory management: Use generators for large datasets
- Test locally first: Verify solutions before submission
- Use meaningful variable names: Makes debugging easier
- Handle edge cases: Test with empty inputs, large numbers
- Time complexity: Ensure algorithms scale appropriately
- Input validation: Check for malformed input data
- Start simple: Test with basic examples first
- Print intermediate values: Debug step by step
- Check input format: Ensure input matches expected format
- Use appropriate data types: int vs float, string handling
- Error handling: Add try/catch for robust solutions
- Commands Reference - Complete command documentation
- Security Guide - General security practices
- Configuration Guide - Environment setup
- Developer Guide - Extension development