Akash Srivastava Akash Srivastava - 1 month ago 8
Bash Question

Remove command injection in rails

So I have a helper that uses

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

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


brakeman
gives me a
command injection
warning here, obviously. Using only
backticks
gives the same warning, and while
system
would produce the result required, it returns
true
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.

Answer

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
end

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.