Code safety question

J

Jamal Hansen

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=3D%q{%{somthing #{foo}}}

and am then using=20

eval (astring)=20

to cause the interpolation to happen. =20

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=3D1 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

=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D

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

inst=3DFoozle.new
inst.foo
 
G

Gavin Kistner

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

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.
 
J

Jamal Hansen

Thanks Gavin,=20

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

-Jamal
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,819
Latest member
masterdaster

Latest Threads

Top