Command Injection in Rails

Command Injection is a type of injection where attackers gains access to your system through your application. It occurs when a system command includes user manipulable values.

Here are the common command lines which we generally use in rails application:

  • `….`
  • system()
  • %x[….]
  • exec()

Now, this is what command injection looks like:

path = "#{Rails.root}/public/#{params[:name]}"`mkdir -p #{path}``ls #{params[:file]}`

Here, as the params data is provided by user, so it can be used by attacker to manipulate our system command and execute it.

In the above case of command like “ls #{params[:file]}”, the attacker can just pass params[:file] value as ; cat ./config/database.yml and thats it. Just by doing this they have gained access to view your database credentials which is obviously too sensitive.

So, how to prevent this from happening?

In order to prevent it from attack like command injection, we need to break our command into separate strings like this:

path = "#{Rails.root}/public/#{params[:name]}"system("mkdir", "-p", path)system("ls", "params[:file]")

Or, if you are working with Ruby, you can use Ruby FileUtils for achieving the same things like this :

path = "#{Rails.root}/public/#{params[:name]}"FileUtils.mkdir_p path

Hope you liked it, for more such information stay tuned :)

--

--