Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I sanitize user input before passing it to %x (executing it)?

I am taking an input string from a user and using that as the parameters for a command line back-end program.

What is the best way to ensure that this input is "safe"? Aka they haven't inserted "; cd /; rm -rf" or some other ugliness into field?

Without any sanitizing I have...

@query = params[:query]
@result = %x( mycommand #{@query} )

I need to get the output of the command, so I can't use system("command","parameters") as that only returns true or false but would provide protection.

I know this is dangerous... thanks in advance.

like image 535
SWR Avatar asked Dec 22 '22 11:12

SWR


1 Answers

Always, always define what you will accept and then deny everything else. Too often people try to allow everything and then deny the bad things.

  1. Start with characters. I.e. if mycommand only needs alphanumeric input plus spaces then only allow that. There would be no chance of "rm -rf /" sneaking in, nor of the other 10,000 things that require punctuation.
  2. Are there further syntactics/semantics of mycommand that you can use to define "good" input? Such as it requires exactly 2 space separated parameters?

Without knowing what mycommand is I can't offer specifics, but you get the idea: don't try to throw away bad things; define valid and throw away everything else. Note that this is still hard, but without this approach it's almost impossible.

like image 112
dwc Avatar answered Feb 02 '23 00:02

dwc