You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在自建服务中执行并沙箱化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:

Ruby生态内的沙箱方案

If you want to stick with Ruby, these tools will help you lock down code execution:

  • $SAFE Level (Use with Caution)
    Ruby’s built-in $SAFE variable 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 = 4 can 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}"
    end
    
  • sandbox Gem
    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 $SAFE for 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}"
    end
    
  • Docker Container Isolation
    For the most robust sandboxing, wrap your ruby script.rb execution in a Docker container. You can limit CPU/memory resources, restrict network access, and mount only specific read-only directories. A simple workflow:

    1. Create a minimal Ruby image (e.g., ruby:alpine).
    2. 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.
    3. Capture the container’s output and return it to the user.
跨语言沙箱方案

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 50
    
  • Node.js + vm Module
    Node’s built-in vm module creates isolated contexts for running JavaScript. If you still need to execute Ruby code, you can combine it with child_process to 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 10
    
  • Go + 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. The os/exec package and syscall allow 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 eval is 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).
  • 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.

内容的提问来源于stack exchange,提问作者Mohamed Ayman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:04:44