malei0311
malei0311

Reputation: 201

Avoid executing system command with Ruby secure open

In terminal, typing:

> irb
> require('open-uri')
> open("| curl http://www.haosou.com").read

can execute a system command. How can I avoid this?

ruby open curl

Upvotes: 1

Views: 66

Answers (1)

PJ Bergeron
PJ Bergeron

Reputation: 2998

Executing this kind of command is a serious security issue.

You can use a regex to validate the format:

/^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/ix

The validation can be done in a model:

validates_format_of :url, :with => /^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/ix

Or elsewhere:

if url =~ /^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/ix
    require('open-uri')
    open(url).read
end

Upvotes: 1

Related Questions