corydoras
corydoras

Reputation: 7270

How to untaint execution of system command

I have a script that can be called by untrusted users, we need to make a call along the lines of this made up example:

system 'somescript ' + data

We need to ensure if data == 'filename; dosomethingelse' then the ; is escaped (or any other special character. The result is the shell command run is actually somescript filename\;\ dosomethingelse or somescript "filename; dosomethingelse"

Is there a standard way to do this?

Upvotes: 3

Views: 516

Answers (2)

Wayne Conrad
Wayne Conrad

Reputation: 107989

The Shellwords module (part of the standard library) will do the appropriate escaping for shell commands:

#!/usr/bin/ruby1.8

require 'shellwords'

command = ['cat', 'filename with spaces', '"quoted_filename"'].shelljoin
puts command    # => cat filename\ with\ spaces \"quoted_filename\"
system(command)
# => this file has spaces in its name
# => this file has a quoted filename

shellwords also adds a shellescape method to String.

These methods are not in the online API documentation. They are partially documented in the 1.9 Pickaxe, and are known to be present in MRI 1.8.7. The actual file (on my box, in /usr/lib/ruby/1.8/shelljoin.rb) is well commented.

Upvotes: 1

C. K. Young
C. K. Young

Reputation: 223003

system 'somescript', data

Multi-argument calls to system are not passed to the shell for processing.

Upvotes: 6

Related Questions