Escaping shell commands

Donn Cave donn at drizzle.com
Sat Aug 30 22:54:38 EDT 2003


Quoth tocapicha at hotmail.com (Inspector Chan):

|   I'm using some external data on shell commands which are to be
| executed with os.system (other functions doesn't provide enough
| flexibility for executing these shell lines).
|
|   So I have decided to user re.escape() for escaping these data before
| using it on the created command lines.
|
| Quick example:
|
| malicious external data in var 'data':
|
| data= '; touch /home/user/I0wnzu'
|
| shell command to be executed is 'command':
|
| command= 'echo I am so happy' + re.escape(data)
|
| This way the generated shell lines is:
|
| echo I am so happy\;\ touch\ \/home\/user\/I0wnzu
|
| With this example it looks safe... But I'm not quite sure about this
| method of escaping input.
|
| Is this breakable?

I can't think of any way right off hand.  Well, if the immediate
command actually goes on to invoke another shell that will
interpret this string again, you lose, but you can't win that
one anyway.

| Does anyone knows a better way to get this done?

I prefer to avoid the shell, with os.spawnv().  Suppose you're
invoking something a little more fussy about its parameters than
echo, like 'ls' -

 	os.spawnv(os.P_WAIT, '/bin/ls', ['ls', '-l', data]) 

Note that element 0 of the parameter list is the name of the
command - this list is the sys.argv for ls.

	Donn Cave, donn at drizzle.com




More information about the Python-list mailing list