Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails how to run system command from rails command securely

I have an ActiveJob which triggers a system script to run:

 `grunt custom-job --src=files --dest="file" --vars='#{user_input_vars_from_json}'`

Point being is that

user_input_vars_from_json

Is a json config which comes as user input parameter from a controller. I do validate the json format but how can I ensure that there is no harmful code send to my system command?

like image 890
dc10 Avatar asked Apr 15 '17 11:04

dc10


1 Answers

I would just like to preface this with: Any user input should be treated as dangerous. I would not recommend executing any command using user-provided inputs.

The first thing you're going to want to do is lock down the input as much as possible. Consider restricting the length of the user_input_vars_from_json to prevent buffer overflow and DoS attacks. I also recommend trying to figure out a way to both validate and restrict the "vars" you are trying to set in the user_input_vars_from_json JSON to filter out any unwanted keys/values.

Once your input is cleaned, you can use Kernel#system in combination with Shellwords to get as close to safe as possible in executing your command from your job:

require 'shellwords'
system("grunt", "custom-job", "--src=files", '--dest="file"', "--vars=\"#{Shellwords.escape(user_input_vars_from_json)}\""
like image 170
codenamev Avatar answered Oct 30 '22 13:10

codenamev