Inspect, eval & security

Hi guys ! :slight_smile:

Just a quick question… Is this code safe to execute ?

eval(string.inspect)

Thank you very much,

Sébastien

Depends on what string represents.

“string” represents a user input.

I know, dangerous idea, but I try to better understand what “inspect”
do.

:wink:

On Sun, Dec 29, 2013 at 6:37 AM, Sébastien Durand [email protected]
wrote:

“string” represents a user input.

I know, dangerous idea, but I try to better understand
what “inspect” do.

Long story short, it mainly gives you the details of a complex object.
To quote Class: Object (Ruby 2.1.0)
:

“Returns a string containing a human-readable representation of obj.
By default, show the class name and the list of the instance variables
and their values (by calling inspect on each of them). User defined
classes should override this method to make better representation of
obj. When overriding this method, it should return a string whose
encoding is compatible with the default external encoding.”

To see what it does specifically to a string, try it in irb. You’ll
see that it basically adds a lot of escaping, especially to any double
quotes, and adds a pair of them around it. For instance:

irb> s = “puts "foo"”
=> “puts "foo"”
irb> s
=> “puts "foo"”
irb> s.inspect
=> “"puts \"foo\""”
irb> eval s # DON’T DO THIS WITH USER INPUT!!!
foo
=> nil
irb> eval s.inspect
=> “puts "foo"”

So, yeah, technically eval’ing the inspection of a string should be
safe… but it’s still like playing with fire. Be VERY distrustful of
ANY user input.

There’s not much difference between “eval” and “evil”. Coincidence?
I think not. :wink:

-Dave

Thanks so much, Dave !

Great answer.

:slight_smile:

(Lol the eval/evil comparison…)