How can I make this code safer? It is a minimal reproducible example of a more complex code where the internal users are allowed read access to a few dictionaries in the code, whose names are known in advance. The example works as intended with eval
, and prevents some malicious user input, such as a system call to rm -rf /
. But I was looking for a safer method than eval
.
import re
# In the minimal example, I have 2 dicts that the users need
# read access to, and keys match this regex: ^\w+$
dct_a = {'foo': 1, 'bar': 2}
dct_b = {'baz': 3, 'bletch': 4}
# User input, e.g.:
lst = ["dct_a['foo']", "dct_b['baz']"]
for item in lst:
# Make safer, prevent a few obvious hacks:
if not re.findall(r"^[\w\]\[']+$", item):
raise Exception(f'Unsafe item: {item}')
# do something with item, e.g.:
print(eval(item))
# Prints:
# 1
# 3
I am aware that eval
is dangerous, no need to repeat the warnings.
RELATED:
Python: make eval safe