Akash Srivastava Akash Srivastava - 7 months ago 43
Bash Question

Remove command injection in rails

So I have a helper that uses

and a method inside it which enforces
on command line to extract QR data from an image. The image source has to be parametric.

qr_code_data = %x(zbarimg -q #{src})

gives me a
command injection
warning here, obviously. Using only
gives the same warning, and while
would produce the result required, it returns
and not the output. I don't want to use a QR-decoding wrapper/gem, or Open3. I need to know can I sanitise my image source as a parameter to avoid command injection, except by using the two options I have mentioned.


ImageMagick generally supports using STDIN for input. IO.popen supports replacing stdin of the subprocess with the contents of a file. Try the following:

qr_code_data = ""
IO.popen(['zbarimg','-q','png:-'], :in=>[src]) do |pipe|
  qr_code_data = pipe.read

Replace png above with your actual image format or remove png: entirely to allow ImageMagick to determine the file type from the input's magic number.