Command injection in Rails

An application will be vulnerable to command injection, if an attacker may influence command line parameters or entire Unix commands. This is less likely in Rails, because running Unix commands directly in Rails is not extremely common. However, the vulnerability might also be in a background process that uses customer data in a Unix command directly.
 
Here are common Rails command line methods:
  • %x[...]
  • system()
  • exec()
  • `...`
 Also note that there is more than one way how to chain commands together, but that depends on the hosting operating system. Examples: "&", "&&", "|", "||" etc.
 

Keep environment variables secure when running commands

A process run by your Rails app will inherit the environment variables of the parent process that might include API keys and the like. See the Secure configuration section for more on that second line of defense.


Another type: ImageMagick Command Injection

When using ImageMagick to manipulate images, Rails makes a shell call and passes command line arguments to an executable. If those arguments come from a user-supplied source, they could be crafted to cause ImageMagick to use excessive CPU or time.

What are the Possible Risks?

The likeliest scenario is a denial of service attack, where the user causes ImageMagick to consume enough CPU or memory resources to bog down the server. It’s also possible to delete or overwrite files by passing in additional options to ImageMagick.

What can I do against ImageMagick Command Injection in Rails?

When you’re dealing with a list of known parameters, as here, it’s easiest to validate user input against a regex or set of known secure responses. The Dragonfly library, for example, does a good job of checking user arguments (e.g. resize requests) to make sure they’re safe:

RESIZE_GEOMETRY = /\A\d*x\d*[><%^!]?\z|\A\d+@\z/ # e.g. '300x200!'