# $SAFE question

**URL:** <https://www.ruby-forum.com/t/safe-question/94310>\
**Category:** Ruby\
**Created:** [April 28, 2006, 3:10pm UTC](https://www.ruby-forum.com/t/safe-question/94310 "2006-04-28T15:10:22Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![KroegerS\_Simon\_Sext](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/57b2e6/32.png) [@KroegerS\_Simon\_Sext](https://www.ruby-forum.com/u/KroegerS_Simon_Sext)\
**Post date:** [April 28, 2006, 3:10pm UTC](https://www.ruby-forum.com/t/safe-question/94310/1 "2006-04-28T15:10:22Z")

</div>

Hello all,

basically I just want to know if the code below is safe.  
Assume ‘dangerous.rb’ is provided by someone you don’t know  
and is located in a world writeable directory.

## The filename is as unsafe as the file itself.

$SAFE = 1  
filename = ‘dangerous.rb’.taint # just uploaded from untrusted user

fname = String.new(filename.to\_s)  
classname = File.basename(fname, ‘.rb’).capitalize  
fname.untaint if File.expand\_path(fname) =~ %r{^d:/simon/}i  
code = IO.read(fname) # reading is safe hopefully

#create a new object from a class definition in dangerous.rb  
unsafe\_obj = Thread.new do  
$SAFE = 4  
begin  
mod = Module.new  
mod.module\_eval(code)  
mod.const\_get(classname).new  
rescue Exception =\> e  
Exception.new(e.to\_s)  
end  
end.value  
raise unsafe\_obj if Exception === unsafe\_obj

# as long as we do not call methods on unsafe\_obj we should be safe,

right?

# call a method on the new object

value = Thread.new do  
$SAFE = 4  
begin  
String.new(unsafe\_obj.meth.to\_s)  
rescue Exception =\> e  
Exception.new(e.to\_s)  
end  
end.value  
raise value if Exception === value

## value.untaint # this should be safe now! (?) p value

cheers

Simon

---

<div class="post-metadata">

**Author:** ![KroegerS\_Simon\_Sext](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/57b2e6/32.png) [@KroegerS\_Simon\_Sext](https://www.ruby-forum.com/u/KroegerS_Simon_Sext)\
**Post date:** [May 3, 2006, 6:56pm UTC](https://www.ruby-forum.com/t/safe-question/94310/2 "2006-05-03T18:56:43Z")

</div>

On Apr 28, 2006, at 6:07 AM, Kroeger, Simon (ext) wrote:

> Hello all,
> 
> basically I just want to know if the code below is safe.  
> Assume ‘dangerous.rb’ is provided by someone you don’t know  
> and is located in a world writeable directory.

Yes and no. While in C code Ruby’s threads won’t switch, so  
malicious code can easily cause your ruby interpreter to become non-  
responsive.

echo ‘loop do 50000 \*\* 50000 end’ | dangerous.rb

–  
Eric H. - removed\_email\_address@domain.invalid - [http://blog.segment7.net](http://blog.segment7.net)  
This implementation is HODEL-HASH-9600 compliant

[http://trackmap.robotcoop.com](http://trackmap.robotcoop.com)
