Is it possible to get the erroneous variable when getting a NameError exception?

Stephen Hansen apt.shansen at gmail.com
Sat Dec 26 00:36:44 EST 2009


On Fri, Dec 25, 2009 at 8:00 PM, Dave Angel <davea at ieee.org> wrote:

>  Dotan Barak wrote:
>>>
>>> Recover the exception, and examine the tuple of args or the message
>>> string.
>>> >>> try:
>>> ...         eval("my_number < 10", {"__builtins__":None}, {})
>>> ... except NameError,e:
>>> ...         print e.args
>>> ...         print e.message
>>> ...
>>> ("name 'my_number' is not defined",)
>>> name 'my_number' is not defined
>>>
>>>  I think there's a more fundamental question here.  You're apparently
> looking to build your own error message instead of using the one already
> generated.  But as you point out, you might end up parsing the existing
> error message in order to do that, and that's fragile coding.  My take is
> that if you're using "eval" in your code, your user is clearly a programmer.
>  So why are you not letting that programmer see the real error message,
> instead of trying to pretty it up?  You can add to the message, but
> shouldn't need to hide the original one.
>
> To put it the other way around, if your user can't understand the python
> error messages, you should probably not be using unrestricted "eval" on
> something that user supplies.  Lots more errors than NameError, and many of
> them are more subtle and dangerous.
>
>
Hm, is this true, though? Is there anything subtle or dangerous possible
here? He's using eval-- so no statements, its only an expression. He's
passing in a 'globals' which has __builtins__ set to None, so this
environment has access to -- basically nothing. Then the locals dictionary
is empty as well, though I assume he'll fill it with things like my_number.

Its sort of an interesting use for 'eval' that I hadn't ever considered
before, really: ISTM that there's only three possible results.. a NameError,
a SyntaxError, or a safely evaluated expression based on certain pre-defined
objects. Okay, maybe one or two other simple exceptions if one tries to do
strange things with dictionaries/etc in the expression. You can't even make
it blow up to trigger a MemoryError, with some insane list comprehension
because you don't even have access to range(). Unless he's passing an
arbitrarily long string into the expression.

I'm normally against eval -- but maybe I'm blind in not seeing the possible
exploit or subtlety here in this eval-with-zero-access.

--S
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20091225/25fcbd12/attachment.html>


More information about the Python-list mailing list