当$SAFE = 4的线程调用方法时,该方法以相同的$SAFE级别运行:
def test_method raise "value of $SAFE inside the method: #{$SAFE}" end t = Thread.new{$SAFE = 4; self.test_method}; t.join => RuntimeError: value of $SAFE inside the method: 4
但是,当调用块时,它似乎使用原始上下文中的$SAFE:
test_lambda = lambda do raise "value of $SAFE inside the lambda: #{$SAFE}" end t = Thread.new{$SAFE = 4; test_lambda.call}; t.join => RuntimeError: value of $SAFE inside the lambda: 0
有人可以解释为什么它这样工作?这似乎是一个安全问题.
(我使用raise而不是puts的原因是puts在$SAFE = 4时不起作用)
这可用于在看似安全的上下文中评估受污染的字符串:
test_lambda = lambda{|s| puts "Tainted: #{s.tainted?}"; eval s} t = Thread.new{$SAFE = 4; test_lambda.call("puts `date`")}; t.join => Tainted: true => Fri Mar 30 03:15:33 UTC 2012