在Web服务器上执行用户提供的红宝石代码 [英] Executing user-supplied ruby code on a web server

查看:87
本文介绍了在Web服务器上执行用户提供的红宝石代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想让我的用户创建Ruby脚本,该脚本对Web服务器上的某些数据进行计算,然后输出结果.脚本在服务器上执行.有什么方法可以安全地做到这一点吗?

I would like to let my users create Ruby scripts that do computation on some data residing on the web server and then outputs results. The scripts are executed on the server. Is there any way to do this securely?

更具体地说,我想:

  • 限制脚本可以使用的资源(内存和cpu),并限制其运行时间
  • 限制脚本可以使用的核心类(例如String,Fixnum,Float,Math等)
  • 让脚本访问并返回数据
  • 向用户输出任何错误

是否有符合我要求的库或项目?如果不是使用Ruby,也许还有其他语言?

Are there any libraries or projects that do what I'm asking for? If not in Ruby, maybe some other language?

推荐答案

您可以使用空白石板"作为洁净室,并使用沙箱在其中设置

You can use a "blank slate" as a clean room, and a sandbox in which to set the safe level to 4.

一个空白的对象是您已经从中剥离所有方法的对象:

A blank slate an object you've stripped all the methods from:

class BlankSlate

  instance_methods.each do |name|
    class_eval do
      unless name =~ /^__|^instance_eval$|^binding$|^object_id$/
        undef_method name
      end
    end
  end

end

无尘室是一个对象,您可以在其中评估其他代码:

A clean room is an object in which context you evaluate other code:

  clean_room = BlankSlate.new

从不受信任的来源读取命令,然后取消污染.除非不受污染,否则Ruby将拒绝在沙箱中评估字符串.

Read a command from an untrusted source, then untaint it. Unless untainted, Ruby will refuse to eval the string in a sandbox.

  command = gets
  command.untaint

现在在沙箱中执行字符串,将安全级别提高到最高水平. proc结束时,$ SAFE级别将恢复正常.我们在洁净室绑定的上下文中执行该命令,以便它只能看到洁净室可以看到的方法和变量(不过请记住,就像任何对象一样,洁净室可以在全局视野中看到任何东西).

Now execute the string in a sandbox, cranking the safe level up as high as it will go. The $SAFE level will go back to normal when the proc ends. We execute the command in the context of the clean room's binding, so that it can only see the methods and variables that the clean room can see (remember, though, that like any object, the clean room can see anything in global scape).

  result = proc do
    $SAFE = 4
    clean_room.instance_eval do
      binding
    end.eval(command)
  end.call

打印结果:

  p result

这篇关于在Web服务器上执行用户提供的红宝石代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆