Code safety question

(Jamal Hansen) #1

Hi all,
I have a situation where I would like to create a string and
interpolate it later (sample code below). The string will be
interpolated while iterating through a potentially long list of
values. To do this I have set up the string as

    astring=%q{%{somthing #{foo}}}

and am then using

    eval (astring)

to cause the interpolation to happen.

Why? Well one of the variables I want is a block variable and out of
scope outside the block.

Another of the variables that is being interpolated is entered by the
user who I must assume could be malicious. I tried $SAFE=1 and then
back to 0 after the iteration, but it caused an error with 'require'.

Well enough talk; how safe is the following code? Assuming that the
input was passed in from the web rather than a gets. Also, is there a
better way of doing something like this? Thanks in advance for your
input. -Jamal

···

=========================================

class Foozle
   def foo
      # a hash to iterate through
      ahash={ :a => 'This', :b => 'That', :c => 'The other'}
    
      # get some value from user
      print 'value:'
      user_input=gets.chomp
    
      # our string to interpolate
      output=%q{%{#{v} asks, "Is user input '#{user_input}' safe for
any user input when $SAFE==0?"\n}}
    
      # ...and pow!
      ahash.each { | k, v | puts eval(output) }
   end
end

inst=Foozle.new
inst.foo

(Gavin Kistner) #2

My Ruby security knowledge is lacking, so i can't directly answer your question. As for the 'better way' aspect, however, I think that using ERB is a 'better' solution than using a later eval. (You can also specify $SAFE level for the ERB eval during the ERB constructor.) It may depend on what you mean by 'better', however.

···

On Aug 18, 2005, at 11:49 PM, Jamal Hansen wrote:

Well enough talk; how safe is the following code? Assuming that the
input was passed in from the web rather than a gets. Also, is there a
better way of doing something like this? Thanks in advance for your
input. -Jamal

(Jamal Hansen) #3

Thanks Gavin,

I was playing with ERB last night, I should have thought of that.

-Jamal

As for the 'better way' aspect, however, I think that

···

On 8/19/05, Gavin Kistner <gavin@refinery.com> wrote:

using ERB is a 'better' solution than using a later eval. (You can
also specify $SAFE level for the ERB eval during the ERB
constructor.) It may depend on what you mean by 'better', however.