PythonNoob PythonNoob - 1 year ago 78
Python Question

EVAL(). Is this dangerous?

Well, almost everybody out there say that

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
, SO, Is this dangerous?

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

import os

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 + "()"))
raise Exception("Not an UTF-8 locale")
except KeyError:
except AttributeError:

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

I've alredy tried to mess up my PC trying to change my
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
var & adds
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
, 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
should suffice to neutralize any attempt of harm.

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

Answer Source

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"):
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download