Skip to content

Instantly share code, notes, and snippets.

@notahat
Created September 14, 2010 05:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save notahat/578575 to your computer and use it in GitHub Desktop.
Save notahat/578575 to your computer and use it in GitHub Desktop.
# This is a replacement for Ruby's backtick operator that avoids shell
# injection attacks.
#
# In web apps that allow file uploading, it's common to run shell commands that
# operate on those files. For example, you might do this:
#
# `convert -resize 100x100 '#{image_filename}'`
#
# The problem is that a carefully crafted filename could cause trouble.
def safe_backtick(command, *args)
read_end, write_end = IO.pipe
pid = fork do
read_end.close
STDOUT.reopen(write_end)
STDERR.reopen(write_end)
exec(command, *args)
end
write_end.close
output = read_end.read
Process.waitpid(pid)
read_end.close
return output
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment