[CentOS] bash - safely pass untrusted strings?

Stephen Harris lists at spuddy.org
Tue Feb 26 21:42:50 UTC 2008


On Tue, Feb 26, 2008 at 12:40:06PM -0800, Benjamin Smith wrote:
> In script2.sh, $1 only contains the string "this". There is no safe way to 
> pass $1 (containing string "this parameter") from script1 to script2 as a 
> single, trustable parameter. 

The statement is meaningless.  Trusted in WHAT CONTEXT?  In an eval?
Passed to a SQL command?  Or merely passed as a parameter to another
program?  If the last, then USE QUOTES.  

> So $1 in script 1 contains "this parameter". $1 in script 2 contains "this". 

Because you are doing it wrong.  You want to pass "$1" which tells the
shell to pass the contents of $1 WITHOUT parsing it.  You're passing $1
which tells the shell to break the arguments up at whitespace (well, $IFS)
when passing to an external program.

> Instead, I have to hork it up with awk, sed, or something similar, and try to 
> account for every possible interpreted character. 

No you don't.  You need to learn how to quote properly.

> #!/bin/bash
> PassToShell2=`escapethis $1`; 

You're missing  "" around the $1 again

> Again, you're missing the point. (practice makes perfect?) 

You've missed every single clue thrown at you, so far.  You are MISUSING
the tool, and blaming it for your mistakes.

> is being interpreted, it doesn't change the fact that $file is unescaped. 

You're missing "" again.

  mv -- "$file" wheee

> for file in $*
>                  do
>                  mv ${file} $prefix$file

mv -- "$file" "$prefix$file"

> echo blah > "Disney trip -a mother\'s journey.doc"; 

  $ ls
  Disney trip -a mother\'s journey.doc
  $ for a in *
  > do
  > mv -- "$a" "whee$a"
  > done
  $ ls
  wheeDisney trip -a mother\'s journey.doc

Clever that, innit?

> for file in $* 
> 	do 
> 	echo "$file"; 
> 	done; 
> 
> called like: 
> /bin/bash ../test.sh * 

You're doing it wrong.  You've now got TWO SHELLS expanding the command
line.
  bash ../test.sh "*"

Again, you don't understand Unix shell quoting.

> I mean, argue with me if you want on how my scripts are implemented but the 
> previous two (TRUE) sentences sound like a philosophical deficiency to me. 

Only because YOU ARE DOING IT WRONG.

Every single case has been fixed by proper use of "" around the variable
expansion.

You are at fault, not the shell.

(Now there _are_ odd corner cases, but you haven't hit one, yet!)

-- 

rgds
Stephen



More information about the CentOS mailing list