Dynamic variable creation from string

Steven D'Aprano steve+comp.lang.python at pearwood.info
Fri Dec 9 06:59:16 EST 2011


On Fri, 09 Dec 2011 01:55:28 -0800, Massi wrote:

> for k in D : exec "%s = D[k]" %k
> 
> That seems to do the trick, but someone speaks about "dirty code", can
> anyone point me out which problems this can generate? Again, thank you
> for your help!

Just the second-most common source of viruses, malware and security 
vulnerabilities (behind buffer overflows): code injection attacks.

Code injection attacks make up at least three of the top 25 security 
vulnerabilities on the CWE/SANS list:

http://cwe.mitre.org/top25/index.html

including the top 2 most dangerous threats (beating even our old friend, 
the buffer overflow): SQL injection and OS command injection. Your use of 
exec is vulnerable to attack if a hostile user can fool you into using a 
dict like this one:

D = {'a': '42', 
     'import os;'\
     ' os.system("""echo "ha ha i ownz ur system rm-rf/" """); b': '23',
    }
for k in D : exec "%s = D[k]" % k


You might think you're safe from such attacks, but (1) it is MUCH harder 
to protect against them than you might think; and (2) code has a habit of 
being re-used. Today your application might only be used by you; next 
week your code might find itself embedded in a web-application where 
hostile script kiddies can destroy your server with a single upload.

My advice is:

(1) If you need to ask why exec is dangerous, you shouldn't touch it.
(2) If you're sure you can protect against code injection, you can't.
(3) If you think you need exec, you probably don't.
(4) If you think you can make exec safe with a prohibited list of 
dangerous strings, you probably can't.


-- 
Steven



More information about the Python-list mailing list