Created
September 14, 2010 05:03
-
-
Save notahat/578575 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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