Ruby: creating a sandboxed eval?

fearless_fool picture fearless_fool · May 20, 2011 · Viewed 8k times · Source

My Rails app has complicated rules about when a bit of content should be displayed on a page or not. I've decided to implement this by writing predicates (simple 'yes/no' functions) in Ruby and storing them in the db for subsequent eval'ing. It it pretty straightforward.

My main concern is security: if a malicious somebody figures out how to write to the db, they could stick arbitrary Ruby code in the db and then 'all your base are belong to us'.

So is it possible to create an 'sandboxed' eval, for example, which has all IO operations removed?

Answer

Pablo Fernandez picture Pablo Fernandez · May 20, 2011

You might want to check the 'taint' method and related stuff. This is a good reference:

http://ruby-doc.com/docs/ProgrammingRuby/html/taint.html

Despite that, I can't advise you enough against storing code and evaluating it, it's a security risk that should be avoided and most times there's a simpler way of solving your problems.

If you need to evaluate complex rules and predicates I'd recommend a rule engine to create a nice DSL. Haven't used one in ruby but this one looks good to me:

http://treetop.rubyforge.org/index.html

Cheers