Håkon Hægland
Håkon Hægland

Reputation: 40758

Use python exec safely

I would like to read a set of variable definitions from a file. I would like to use execfile to read them (to simplify my input code). Consider:

#! /usr/bin/python

from math import *
import os

cmd="""
a=[0,3]
b=[0,1]
print 'Hello'
print sin(2)
os.system('rm my_important_file')
"""
gd={}
ld={}
exec(cmd,gd,ld)
print ld

(I use here exec instead of execfile to simplify the question). As you see I am trying to use exec safely by supplying dictionaries as second and third argument. I would like to only have variable definitions as valid operations in the input file. So print 'Hello', print sin(2), and os.system('rm my_important_file') should all produce errors. It seems to work for the last two, but not for print 'Hello'. What is the reason for this?

Upvotes: 0

Views: 692

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1122262

print is a statement, a language feature. No imports are required to execute it. You are executing all valid Python code when using exec or execfile, and that includes the print statement.

Your empty dictionaries will also not prevent imports. I can still do:

import os
os.system('rm my_important_file')

in the config file and have it executed under the privileges of the Python code that called execfile() on this file.

If your config file is only allowed to use assignments and a subset of expressions, don't use execfile or exec. There is no way of making those 'safe'; Python is too dynamic a language.

Parse the file yourself into a domain specific language, or use a different pre-existing config file format, such as ConfigParser. These won't allow for Python expressions to be executed, however.

Upvotes: 1

Related Questions