when format strings attack

Steven D'Aprano steve at REMOVE.THIS.cybersource.com.au
Fri Jan 19 14:06:45 EST 2007


On Fri, 19 Jan 2007 03:51:08 -0800, Eric_Dexter at msn.com wrote:

> http://www.ddj.com/184405774;jsessionid=BDDEMUGJOPXUMQSNDLQCKHSCJUNN2JVN
> 
> I saw a warning from homeland security about this.  I only comment on
> the because I am trying to use os.system('command1 arg') and it doesn't
> work 

What do you mean, doesn't work? It works fine for me, precisely as
expected. What does it do for you? Crash Windows? Crash Python? Raise an
exception? Return an unexpected result?

> but I do see examples with % that is borrowed from the c language.

The "When Format Strings Attack" article isn't relevant to Python. Unlike
C, Python doesn't arbitrary dump bytes from the stack into a string if you
print a string containing %s. In Python, print just prints strings, it
doesn't do any string formatting. String formatting is done by the %
operator, so print "a string containing %s" is safe.

You'd be better off looking at Python examples than C. This is what I'm
guessing you're doing:

>>> command1 = 'dir'
>>> args = '-l text.txt'
>>> os.system('command1 arg')
sh: command1: command not found
32512

os.system doesn't do name-lookups of the string you pass to it. The right
way to do this is some variation on this:

>>> commandline = "%s %s" % (command1, args)
>>> commandline
'dir -l text.txt'
>>> os.system(commandline)
-rw-rw-r-- 1 steve steve 333 Sep 24 16:51 text.txt
0

or even something like this:

os.system('dir -l %s' % 'text.txt')


Now, there is a security risk: you might set command1 yourself, and
allow the user to set args. If command1 is an external application
with a security hole, and the user provides arguments that trigger that
bug, then naturally your application will inherit whatever security
vulnerabilities the external application suffers from. No surprises there.


-- 
Steven.




More information about the Python-list mailing list