PythonNoob PythonNoob - 8 days ago 6
Python Question

EVAL(). Is this dangerous?

Well, almost everybody out there say that

eval
is evil, and that's true for the 99% of situations...BUT I'm here to ask about some piece of code I've wrote that uses
eval
, SO, Is this dangerous?

I tried to sanitize data as most as possible, while keeping the original funtionality, but this makes use of
eval
and something can go wrong:

import os

try:
if os.environ["LANG"].rstrip('''\n''')[5:] == ".UTF-8":
Language = str(os.environ["LANG"].rstrip('''\n''').rstrip(os.environ["LANG"].rstrip('''\n''')[5:]))
eval (str("LP." + Language + "()"))
else:
raise Exception("Not an UTF-8 locale")
except KeyError:
LP.Fallback()
except AttributeError:
LP.Fallback()


First of all, this code is supposed to run under UNIX and derivatives.

Wrote in python2.7.

What this does is to call some methods inside the
LP
class.

I've alredy tried to mess up my PC trying to change my
LANG
system variable to any string that could harm my PC, like
rm -rf /
or similars, but, because my code removes the last 5 characters of the
LANG
var & adds
LP.
at the start and
()
at the end , it results like this, without mentioning that it checks from the start if last 5 characters of the string are
UTF-8
, but if I delete that condition this should be the "harmful" command:

LP.rm -r()


Until now, I've noted that any command longer than 5 characters won't be able to bypass the "remove last 5 characters" line of code, and the added
LP.
&
()
should suffice to neutralize any attempt of harm.

Till now, I'll keep the ".UTF-8" to avoid any critical error...

Answer

I can't see any reason for eval here at all.

You're trying to get the method on LP that corresponds to the LANGUAGE setting. So, you can use getattr:

meth = getattr(LP, Language)
result = meth()

Note there's no need to do the rstrip stuff so many times:

lang = os.environ["LANG"].rstrip('''\n''')
if lang.endswith(".UTF-8"):
    ...