开发者

Passing shell commands parameters securely with %x[] in Ruby

开发者 https://www.devze.com 2023-03-30 15:00 出处:网络
Let\'s say I have in a Rails controller: dir = params[:dir] output = %x[ls #{dir}] 开发者_Python百科

Let's say I have in a Rails controller:

dir = params[:dir]
output = %x[ls #{dir}]
开发者_Python百科

This is a HUGE security hole if somebody posts dir="foo; rm -rf /"

So I need to secure the parameter. I know I could do

system "ls", dir

But this method does not capture stdout !

So, how can I securely pass parameters to %x[] ?


The problem is that %x() basically hands a string to the shell to be parsed so you'd have to escape everything that the shell could possibly interpret. So %x is pretty much out the window if you need to deal with anything that you haven't built yourself (and event then it is suspect).

One solution is to use Open3.capture3:

out, err, status = Open3.capture3('/bin/ls', dir)

and then deal with the standard output (out) and standard error (err) returns as needed. There are a few other things in Open3 that might serve your needs better.


Have you looked at Ruby's safe levels?

http://www.ruby-doc.org/docs/ProgrammingRuby/html/taint.html

For levels >= 2 it says "Can't change, make, or remove directories, or use chroot."

There also used to be a sandbox gem, but I'm not sure if that's still active. You also could have a look at the source of "Try Ruby!" there has to be some kind of sandboxing in there.

0

精彩评论

暂无评论...
验证码 换一张
取 消