[Python-Dev] what can we do to hide the 'file' type?

Michael Chermside mcherm at mcherm.com
Thu Jul 6 21:07:51 CEST 2006


Me:
> I agree. But we don't have to give up yet. How about instead of hiding
> file, we cripple it. Completely. Modify the file type so that when
> executing on a sandboxed interpreter, all of the dangerous methods
> and attributes of file throw exceptions.

Brett:
> This is basically what I proposed in the first place! <runs around  
> in circles, pulling at his hair like a crazy man>

Not quite. Your original proposal had the file type throwing
exceptions when the user did something they weren't allowed to
(access a file not on the list, etc). This version proposes that
it *always* fails, and creates a separate beast (the
SecureFileWrapper) for applying the restrictions. Why? Because
if the C code in file enforces the rules, then all possible
rules need to be written in advance, and you have to hold long
arguments about whether to allow subdirectories, restrict file
sizes, etc. Whereas SecureFileWrapper could delegate its
restrictions to Python functions provided by the USER and then
USERS could design whatever level of restriction they wanted.

Imagine we want some code to be able to open files only if they
contain the letter 'w':

     # get my own wrapper from __builtins__
     myFileWrapper = file

     # define a function to constrain my callers
     def filenameContainsLetterW(path, mode):
         filename = os.path.basename(path)
         if 'w' not in filename and 'W' not in filename:
             raise PyXXX_SecurityException

     # create more restrictive wrapper
     class MustHaveW_FileWrapper:
         __metaclass__ = SecureFileWrapperMeta
         wrapped_file =
         init_condition = filenameContainsLetterW

     # register the wrapper so it applies to any code
     # in this stack frame or lower. The restriction is
     # automatically lifted when the current stack
     # frame exits.
     PyXXX_RegisterFileWrapper( MustHaveW_FileWrapper )

     # Invoke less-trusted code with restrictions in place
     less_trusted_code()

If the code fragment shown above ALREADY received
a wrapped form of file which was restricted to read-only
access, then less_trusted_code() would be restricted
to read-only access to files containing 'w'.

Okay, the syntax needs work, but the idea is that I can
defin restrictions *in python* and apply them to other
code. Using the stack to enforce wrappers is something
Python code cannot get around (although it does prevent
passing more-powerful callbacks to later stackframes).

It all depends on whether we think that a simple set
of restrictions implementable in C (such as 4 lists:
read-only files, read-write files, read-only dirs,
write-only dirs) will be sufficient, or if it is
valuable to allow end users to fine-tune the
restrictions.

-- Michael Chermside



More information about the Python-Dev mailing list