remote code execution in ruby with constantize remote code execution in ruby with constantize ruby ruby

remote code execution in ruby with constantize


Turning a string into a constant isn't dangerous in itself, but how that constant is used is potentially dangerous (i.e. the method that is then called).

If you really need to do this, then it's probably best to provide a list of classes that are allowed. E.g.

klass = params[:class].classifyif %w(Class1 Class2 Class3).include? klass  klass.constantize.do_something_with_id(params[:id])else  raise 'Forbidden'end

However it's done, it helps you to sleep at night to know that the input is considerably limited.

Update

Another way of controlling the creation, which is more explicit but also more verbose, is to use a case statement:

def create_klass(option)  case option  when "option1"    Class1  when "option2"    Class2  when "option3"    Class3  else    raise "Unknown option"  endend

This way, you don't need to expose the internals of your system to the client. If there are many options, then you could use a hash with options mapping to classes.