如何在自建服务中执行并沙箱化Ruby代码片段?
Hey there! Running untrusted Ruby code snippets in your own service definitely requires proper sandboxing—using raw eval or plain ruby script.rb is super risky because it exposes your system to all sorts of attacks (file access, network calls, resource exhaustion, you name it). Let’s break down solid solutions for you, both within Ruby and across other languages, plus some resources to dive deeper:
If you want to stick with Ruby, these tools will help you lock down code execution:
$SAFELevel (Use with Caution)
Ruby’s built-in$SAFEvariable was designed to restrict unsafe operations, but note that it’s been deprecated in newer Ruby versions (2.7+) and isn’t fully foolproof. That said, for legacy or controlled environments, setting$SAFE = 4can block access to files, environment variables, and dangerous methods. Example:$SAFE = 4 begin eval("puts 'This is safe!'") eval("File.read('/etc/passwd')") # Triggers SecurityError rescue SecurityError => e puts "Blocked risky operation: #{e.message}" endsandboxGem
This dedicated gem creates an isolated environment for running code, explicitly blocking access to the filesystem, network, and core Ruby methods that could cause harm. It’s more reliable than$SAFEfor modern Ruby versions. Example:require 'sandbox' sb = Sandbox.new puts sb.eval("2 ** 10") # Returns 1024 # Attempting to access files will fail begin sb.eval("File.open('/tmp/test.txt', 'w') { |f| f.write('bad') }") rescue Sandbox::SecurityError => e puts "Operation blocked: #{e}" endDocker Container Isolation
For the most robust sandboxing, wrap yourruby script.rbexecution in a Docker container. You can limit CPU/memory resources, restrict network access, and mount only specific read-only directories. A simple workflow:- Create a minimal Ruby image (e.g.,
ruby:alpine). - Write a script that accepts user code, saves it to a temporary file, and runs it in the container with
docker run --rm --network none --memory 64m --cpus 0.5 ruby:alpine ruby /tmp/code.rb. - Capture the container’s output and return it to the user.
- Create a minimal Ruby image (e.g.,
If you’re open to switching languages, these ecosystems have more mature sandboxing tools:
Python + RestrictedPython
RestrictedPython lets you define a safe subset of Python, blocking access to dangerous modules, file operations, and system calls. It’s widely used in platforms like Plone for running untrusted code. Example:from RestrictedPython import compile_restricted from RestrictedPython.Eval import default_guarded_getitem from RestrictedPython.Guards import full_write_guard safe_globals = { '__builtins__': None, '__getitem__': default_guarded_getitem, '__write__': full_write_guard, } user_code = "result = 10 * 5" bytecode = compile_restricted(user_code, '<user_code>', 'exec') exec(bytecode, safe_globals) print(safe_globals['result']) # Outputs 50Node.js +
vmModule
Node’s built-invmmodule creates isolated contexts for running JavaScript. If you still need to execute Ruby code, you can combine it withchild_processto spawn a Ruby process in a restricted environment (e.g., limit memory, timeout execution). Example for JavaScript sandboxing:const vm = require('vm'); const context = { result: null }; const code = "result = 3 + 7"; vm.runInNewContext(code, context); console.log(context.result); // Outputs 10Go + Process Isolation
Go’s strong control over system processes makes it great for sandboxing external code. You can spawn a Ruby interpreter process, set resource limits (CPU, memory), and capture stdout/stderr. Theos/execpackage andsyscallallow you to restrict the process’s environment and capabilities.
- Books
- Ruby Under a Microscope: Dives deep into Ruby’s runtime internals, helping you understand why raw
evalis risky and how sandboxing works at the low level. - Secure Programming with Static Analysis: Teaches you to identify and mitigate security risks in code, a critical skill for designing safe sandboxes (not Ruby-specific but universally useful).
- Ruby Under a Microscope: Dives deep into Ruby’s runtime internals, helping you understand why raw
- Tutorials
- Ruby Official Security Guide: Covers the history of
$SAFE, secure coding practices, and limitations of built-in security features. - Docker Container Security Docs: Learn how to harden containers, set resource quotas, and isolate networks for running untrusted code.
- RestrictedPython Official Tutorial: Step-by-step guide to setting up restricted Python environments, including custom guards and allowed modules.
- Ruby Official Security Guide: Covers the history of
内容的提问来源于stack exchange,提问作者Mohamed Ayman

