[Python-Dev] Challenge: Please break this! [Now with blog post]

Cesare Di Mauro cesare.dimauro at a-tono.com
Tue Feb 24 14:46:22 CET 2009


On Feb, 24 2009 at 12:11PM, Antoine Pitrou <solipsis at pitrou.net> wrote:

> tav <tav <at> espians.com> writes:
>>
>> I've fixed this hole in safelite.py, but would be interested to know
>> if there are other non-user-initiated dynamically imported modules?
>
> You'd better make __builtins__ read-only, it will plug a whole class of attacks
> like this.

I found very useful adding objects to the builtins namespace, but I'll prefer a
standard and controlled way to do so. Something like a built-in function
"install", like the following which I use:

import __builtin__, types

_ValidBuiltinTypes = (types.BuiltinFunctionType, types.ClassType,
  types.FunctionType, types.GeneratorType,
  types.TypeType, functools.partial)

def install(*Args, **Keys):
  '''Installs the given parameters in the builtins namespace.
  From Args will be installed only valid types (classes, functions and types),
  taking their __name__ attribute.
  Every keyword-value cuple from Keys will be installed as is.'''

  _NameSpace = __builtin__.__dict__

  for Arg in Args:
    if isinstance(Arg, _ValidBuiltinTypes):
      _NameSpace[Arg.__name__] = Arg

  for Key, Value in Keys.iteritems():
    _NameSpace[Key] = Value


With a built-in install function a granular control can be implemented by
the running Python implementation.

Also, having builtins read only by default can be used in future compiler
and virtual machine implementations to gain interesting optimizations.

Cheers,
Cesare


More information about the Python-Dev mailing list