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

···

--
Posted via http://www.ruby-forum.com/.

Depends on what string represents.

···

On Sat, Dec 28, 2013 at 11:04 PM, Sébastien Durand <lists@ruby-forum.com>wrote:

Hi guys ! :slight_smile:

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

eval(string.inspect)

Thank you very much,

Sébastien

--
Posted via http://www.ruby-forum.com/\.

"string" represents a user input.

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

:wink:

···

--
Posted via http://www.ruby-forum.com/.

Thanks so much, Dave !

Great answer.

:slight_smile:

(Lol the eval/evil comparison...)

···

--
Posted via http://www.ruby-forum.com/.

"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:

  > s = "puts \"foo\""
  => "puts \"foo\""
  > s
  => "puts \"foo\""
  > s.inspect
  => "\"puts \\\"foo\\\"\""
  > eval s # DON'T DO THIS WITH USER INPUT!!!
  foo
  => nil
  > 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

···

On Sun, Dec 29, 2013 at 6:37 AM, Sébastien Durand <lists@ruby-forum.com> wrote:

--
Dave Aronson, the T. Rex of Codosaurus LLC (codosaur.us),
freelance software developer, and creator of these sites:
PullRequestRoulette.com, blog.codosaur.us, & Dare2XL.com.