Skip to content

15. Secure Code Execution Guide

ad1107 edited this page May 25, 2025 · 1 revision

Secure Code Execution & Sandboxing 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.

๐Ÿ“‹ Table of Contents


Overview

The bot provides two secure execution environments for Python code:

๐Ÿณ Docker Sandbox (Recommended)

  • 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

๐Ÿ”„ Fallback Sandbox

  • Subprocess-based execution when Docker unavailable
  • Basic security with import restrictions
  • Limited resource control (Unix systems only)
  • Emergency fallback for environments without Docker

Security Features

๐Ÿ”’ Container Security

Feature Docker Sandbox Fallback Sandbox
Process Isolation โœ… Full container โš ๏ธ Process only
Memory Limits โœ… Strict (128-256MB) โš ๏ธ Basic (Unix only)
CPU Limits โœ… Configurable โŒ None
Network Access โœ… Blocked โŒ Limited
File System โœ… Read-only โš ๏ธ Process perms
Import Blocking โœ… Comprehensive โš ๏ธ Basic
Timeout Control โœ… Reliable โš ๏ธ Signal-based

๐Ÿ›ก๏ธ Blocked Operations

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

โœ… Allowed Operations

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

Commands

/eval - Secure Code Evaluation

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"

/run - Competitive Programming

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

Configuration

Environment Variables

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

Resource Limits

Default Limits (/eval 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

Enhanced Limits (/run command)

  • 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

Installation & Setup

Prerequisites

  1. 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
  1. Python Dependencies:
pip install docker>=7.0.0

Verification

Test the sandbox system:

# Check Docker status
docker info

# Verify bot can access Docker
python -c "import docker; print(docker.from_env().ping())"

Fallback Setup

If Docker is unavailable, the system automatically uses subprocess execution:

# Install resource monitoring (Unix only)
pip install psutil

# Note: Limited security in fallback mode

Competitive Programming

Supported Problem Types

๐Ÿ”ข Algorithmic Problems

  • Sorting and searching algorithms
  • Dynamic programming solutions
  • Graph algorithms (with NetworkX)
  • Mathematical computations
  • String processing

๐Ÿ“Š Data Structure Problems

  • Array and list manipulations
  • Tree and graph traversals
  • Hash table implementations
  • Stack and queue operations

๐Ÿงฎ Mathematical Problems

  • Number theory (with SymPy)
  • Combinatorics and probability
  • Linear algebra (with NumPy)
  • Statistical analysis (with SciPy)

Example Workflows

1. Contest Problem Solving

# 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ยฒ)

2. Algorithm Testing

# 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"

3. Performance Analysis

# 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

Language Support

Current Support

๐Ÿ Python 3.11

  • 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

Planned Support

๐Ÿ”ง C++ (Coming Soon)

  • GCC compiler with C++17/20 support
  • STL (Standard Template Library)
  • Compilation + execution pipeline
  • Memory and time limit enforcement

โ˜• Java (Coming Soon)

  • OpenJDK with standard libraries
  • Compilation + execution
  • Class file management
  • Memory profiling support

๐ŸŸข Node.js (Planned)

  • JavaScript execution environment
  • NPM package support (limited)
  • ES6+ syntax support

Troubleshooting

Common Issues

1. Docker Not Available

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

2. Permission Denied

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)

3. Timeout Issues

Error: Code execution times out Solutions:

  • Increase timeout parameter: /run timeout:30
  • Optimize algorithm efficiency
  • Use smaller test cases
  • Check for infinite loops

4. Memory Limits

Error: "Memory limit exceeded" Solutions:

  • Reduce data structure sizes
  • Use generators instead of lists
  • Optimize memory usage
  • Increase memory limit in config

5. Import Errors

Error: "Module 'xyz' is blocked" Solutions:

  • Use allowed alternatives
  • Check allowed operations
  • Request module to be whitelisted
  • Use legacy mode for testing (unsafe)

Debug Mode

Enable debug logging to troubleshoot issues:

# In .env file
DEBUG=true
LOG_LEVEL=DEBUG

# Check logs
tail -f logs/bot.log | grep -i sandbox

Performance Monitoring

Monitor system resources during execution:

# Check Docker stats
docker stats --no-stream

# Monitor system load
htop

# Check disk usage
df -h /tmp

Best Practices

๐Ÿ” Security

  1. Always use Docker: Install Docker for production environments
  2. Avoid legacy mode: Only use for trusted code and testing
  3. Monitor execution: Watch for suspicious patterns
  4. Limit file sizes: Keep uploads reasonable
  5. Regular updates: Keep Docker images current

โšก Performance

  1. Optimize algorithms: Write efficient code for better performance
  2. Use appropriate timeouts: Set realistic limits for your use case
  3. Minimize output: Large outputs slow down response
  4. Batch operations: Process multiple test cases efficiently
  5. Memory management: Use generators for large datasets

๐ŸŽฏ Competitive Programming

  1. Test locally first: Verify solutions before submission
  2. Use meaningful variable names: Makes debugging easier
  3. Handle edge cases: Test with empty inputs, large numbers
  4. Time complexity: Ensure algorithms scale appropriately
  5. Input validation: Check for malformed input data

๐Ÿ› Debugging

  1. Start simple: Test with basic examples first
  2. Print intermediate values: Debug step by step
  3. Check input format: Ensure input matches expected format
  4. Use appropriate data types: int vs float, string handling
  5. Error handling: Add try/catch for robust solutions

๐Ÿ”— Related Pages


๐Ÿ“ What's Next?

Clone this wiki locally