pythonpython-3.xsecuritycode-injectionrestrictedpython

Why doesn't RestrictedPython allow iter, max, min, sum, etc


The Python library Restricted Python by default doesn't include built-in functions like iter, max, min, sum, or any other function that does any form of iteration, as part of their default safe_builtins. Why are these functions unsafe? What's the risk of allowing the use of these functions?


Solution

  • They want to be able to perform access checks when user code tries to retrieve an item from a sequence or other iterable. RestrictedPython can compile seq[0] to code that performs an access check, but it can't do that cleanly with min, max, or sum.

    The default min, max, and sum all allow retrieving sequence items without performing access checks. For example,

    container = # some one-element list
    
    x = min(container)
    y = max(container)
    
    class Foo:
        def __add__(self, other):
            return other
    
    z = sum(container, start=Foo())
    

    RestrictedPython is a Zope project, and you can see in Zope's closely-related AccessControl framework how they define guarded wrappers for min, max, and sum and use those in place of the built-ins.

    iter is similar. They want to perform access checks on every item retrieved from the iterator, so AccessControl defines a SafeIter wrapper that performs access checks and a guarded_iter function that wraps any iterator in a SafeIter if it's not already known to be safe. This function is installed in place of the default iter. (It's also the same function that provides the access checks for guarded_min, guarded_max, and guarded_sum.)