dan
dan

Reputation: 45632

What's the best way in Ruby to clean up a user-provided url string so that it's safe to interpolate into a shell command?

I want to let a user of a web app enter a URL and then pass that URL onto curl. I'd rather use curl than Net::HTTP or open-uri. But this poses a security risk. What's the best way to check the URL string and prevent any injection attacks?

I'm thinking of just using a regular expression like this to check for an injection attack:

raise "possible injection attack" if url =~ /[\s']/ 

and if that check succeeds, then just invoke curl like so

html = `curl '#{url}'`

Is this safe enough?

Upvotes: 1

Views: 421

Answers (2)

akuhn
akuhn

Reputation: 27793

system("curl", url)

this is safe because parameters are directly passed to the main(argv) of the command rather than being parsed by a command line processor. For example system("echo", "* && echo shenanigan") literally outputs * && echo shenanigan.

Upvotes: 2

ChristopheD
ChristopheD

Reputation: 116157

Maybe you're better off using a library like libcurl (to avoid having to use shell commands) ?

Upvotes: 1

Related Questions