Skip to content
Snippets Groups Projects
Commit 60a2b242 authored by Christoph Berg's avatar Christoph Berg :satellite:
Browse files

Import Upstream version 3.6.0

parents
No related branches found
No related tags found
No related merge requests found
Showing
with 1370 additions and 0 deletions
Changes
=======
3.6.0 (2010-07-09)
------------------
- Added name check for names assigned during imports using the
"from x import y" format.
- Added test for name check when assigning an alias using multiple-context with
statements in Python 2.7.
- Added tests for protection of the iterators for dict and set comprehensions
in Python 2.7.
3.6.0a1 (2010-06-05)
--------------------
- Removed support for DocumentTemplate.sequence - this is handled in the
DocumentTemplate package itself.
3.5.2 (2010-04-30)
------------------
- Removed a testing dependency on zope.testing.
3.5.1 (2009-03-17)
------------------
- Added tests for ``Utilities`` module.
- Filtered DeprecationWarnings when importing Python's ``sets`` module.
3.5.0 (2009-02-09)
------------------
- Dropped legacy support for Python 2.1 / 2.2 (``__future__`` imports
of ``nested_scopes`` / ``generators``.).
3.4.3 (2008-10-26)
------------------
- Fixed deprecation warning: ``with`` is now a reserved keyword on
Python 2.6. That means RestrictedPython should run on Python 2.6
now. Thanks to Ranjith Kannikara, GSoC Student for the patch.
- Added tests for ternary if expression and for 'with' keyword and
context managers.
3.4.2 (2007-07-28)
------------------
- Changed homepage URL to the CheeseShop site
- Greatly improved README.txt
3.4.1 (2007-06-23)
------------------
- Fixed http://www.zope.org/Collectors/Zope/2295: Bare conditional in
a Zope 2 PythonScript followed by a comment causes SyntaxError.
3.4.0 (2007-06-04)
------------------
- RestrictedPython now has its own release cycle as a separate egg.
- Synchronized with RestrictedPython from Zope 2 tree.
3.2.0 (2006-01-05)
------------------
- Corresponds to the verison of the RestrictedPython package shipped
as part of the Zope 3.2.0 release.
- No changes from 3.1.0.
3.1.0 (2005-10-03)
------------------
- Corresponds to the verison of the RestrictedPython package shipped
as part of the Zope 3.1.0 release.
- Removed unused fossil module, ``SafeMapping``.
- Replaced use of deprecated 'whrandom' module with 'random' (aliased
to 'whrandom' for backward compatibility).
3.0.0 (2004-11-07)
------------------
- Corresponds to the verison of the RestrictedPython package shipped
as part of the Zope X3.0.0 release.
Zope Foundation and Contributors
\ No newline at end of file
Zope Public License (ZPL) Version 2.1
A copyright notice accompanies this license document that identifies the
copyright holders.
This license has been certified as open source. It has also been designated as
GPL compatible by the Free Software Foundation (FSF).
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions in source code must retain the accompanying copyright
notice, this list of conditions, and the following disclaimer.
2. Redistributions in binary form must reproduce the accompanying copyright
notice, this list of conditions, and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Names of the copyright holders must not be used to endorse or promote
products derived from this software without prior written permission from the
copyright holders.
4. The right to distribute this software or to use it for any purpose does not
give you the right to use Servicemarks (sm) or Trademarks (tm) of the
copyright
holders. Use of them is covered by separate agreement with the copyright
holders.
5. If any files are modified, you must cause the modified files to carry
prominent notices stating that you changed the files and the date of any
change.
Disclaimer
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY EXPRESSED
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
PKG-INFO 0 → 100644
Metadata-Version: 1.0
Name: RestrictedPython
Version: 3.6.0
Summary: RestrictedPython provides a restricted execution environment for Python, e.g. for running untrusted code.
Home-page: http://pypi.python.org/pypi/RestrictedPython
Author: Zope Foundation and Contributors
Author-email: zope-dev@zope.org
License: ZPL 2.1
Description: .. contents::
Overview
========
RestrictedPython provides a ``restricted_compile`` function that works
like the built-in ``compile`` function, except that it allows the
controlled and restricted execution of code:
>>> src = '''
... def hello_world():
... return "Hello World!"
... '''
>>> from RestrictedPython import compile_restricted
>>> code = compile_restricted(src, '<string>', 'exec')
The resulting code can be executed using the ``exec`` built-in:
>>> exec(code)
As a result, the ``hello_world`` function is now available in the
global namespace:
>>> hello_world()
'Hello World!'
Compatibility
=============
This release of RestrictedPython is compatible with Python 2.3, 2.4, 2.5, 2.6,
and 2.7.
Implementing a policy
=====================
RestrictedPython only provides the raw material for restricted
execution. To actually enforce any restrictions, you need to supply a
policy implementation by providing restricted versions of ``print``,
``getattr``, ``setattr``, ``import``, etc. These restricted
implementations are hooked up by providing a set of specially named
objects in the global dict that you use for execution of code.
Specifically:
1. ``_print_`` is a callable object that returns a handler for print
statements. This handler must have a ``write()`` method that
accepts a single string argument, and must return a string when
called. ``RestrictedPython.PrintCollector.PrintCollector`` is a
suitable implementation.
2. ``_write_`` is a guard function taking a single argument. If the
object passed to it may be written to, it should be returned,
otherwise the guard function should raise an exception. ``_write``
is typically called on an object before a ``setattr`` operation.
3. ``_getattr_`` and ``_getitem_`` are guard functions, each of which
takes two arguments. The first is the base object to be accessed,
while the second is the attribute name or item index that will be
read. The guard function should return the attribute or subitem,
or raise an exception.
4. ``__import__`` is the normal Python import hook, and should be used
to control access to Python packages and modules.
5. ``__builtins__`` is the normal Python builtins dictionary, which
should be weeded down to a set that cannot be used to get around
your restrictions. A usable "safe" set is
``RestrictedPython.Guards.safe_builtins``.
To help illustrate how this works under the covers, here's an example
function::
def f(x):
x.foo = x.foo + x[0]
print x
return printed
and (sort of) how it looks after restricted compilation::
def f(x):
# Make local variables from globals.
_print = _print_()
_write = _write_
_getattr = _getattr_
_getitem = _getitem_
# Translation of f(x) above
_write(x).foo = _getattr(x, 'foo') + _getitem(x, 0)
print >>_print, x
return _print()
Examples
========
``print``
---------
To support the ``print`` statement in restricted code, we supply a
``_print_`` object (note that it's a *factory*, e.g. a class or a
callable, from which the restricted machinery will create the object):
>>> from RestrictedPython.PrintCollector import PrintCollector
>>> _print_ = PrintCollector
>>> src = '''
... print "Hello World!"
... '''
>>> code = compile_restricted(src, '<string>', 'exec')
>>> exec(code)
As you can see, the text doesn't appear on stdout. The print
collector collects it. We can have access to the text using the
``printed`` variable, though:
>>> src = '''
... print "Hello World!"
... result = printed
... '''
>>> code = compile_restricted(src, '<string>', 'exec')
>>> exec(code)
>>> result
'Hello World!\n'
Built-ins
---------
By supplying a different ``__builtins__`` dictionary, we can rule out
unsafe operations, such as opening files:
>>> from RestrictedPython.Guards import safe_builtins
>>> restricted_globals = dict(__builtins__ = safe_builtins)
>>> src = '''
... open('/etc/passwd')
... '''
>>> code = compile_restricted(src, '<string>', 'exec')
>>> exec(code) in restricted_globals
Traceback (most recent call last):
...
NameError: name 'open' is not defined
Guards
------
Here's an example of a write guard that never lets restricted code
modify (assign, delete an attribute or item) except dictionaries and
lists:
>>> from RestrictedPython.Guards import full_write_guard
>>> _write_ = full_write_guard
>>> _getattr_ = getattr
>>> class BikeShed(object):
... colour = 'green'
...
>>> shed = BikeShed()
Normally accessing attriutes works as expected, because we're using
the standard ``getattr`` function for the ``_getattr_`` guard:
>>> src = '''
... print shed.colour
... result = printed
... '''
>>> code = compile_restricted(src, '<string>', 'exec')
>>> exec(code)
>>> result
'green\n'
However, changing an attribute doesn't work:
>>> src = '''
... shed.colour = 'red'
... '''
>>> code = compile_restricted(src, '<string>', 'exec')
>>> exec(code)
Traceback (most recent call last):
...
TypeError: attribute-less object (assign or del)
As said, this particular write guard (``full_write_guard``) will allow
restricted code to modify lists and dictionaries:
>>> fibonacci = [1, 1, 2, 3, 4]
>>> transl = dict(one=1, two=2, tres=3)
>>> src = '''
... # correct mistake in list
... fibonacci[-1] = 5
... # one item doesn't belong
... del transl['tres']
... '''
>>> code = compile_restricted(src, '<string>', 'exec')
>>> exec(code)
>>> fibonacci
[1, 1, 2, 3, 5]
>>> sorted(transl.keys())
['one', 'two']
Changes
=======
3.6.0 (2010-07-09)
------------------
- Added name check for names assigned during imports using the
"from x import y" format.
- Added test for name check when assigning an alias using multiple-context with
statements in Python 2.7.
- Added tests for protection of the iterators for dict and set comprehensions
in Python 2.7.
3.6.0a1 (2010-06-05)
--------------------
- Removed support for DocumentTemplate.sequence - this is handled in the
DocumentTemplate package itself.
3.5.2 (2010-04-30)
------------------
- Removed a testing dependency on zope.testing.
3.5.1 (2009-03-17)
------------------
- Added tests for ``Utilities`` module.
- Filtered DeprecationWarnings when importing Python's ``sets`` module.
3.5.0 (2009-02-09)
------------------
- Dropped legacy support for Python 2.1 / 2.2 (``__future__`` imports
of ``nested_scopes`` / ``generators``.).
3.4.3 (2008-10-26)
------------------
- Fixed deprecation warning: ``with`` is now a reserved keyword on
Python 2.6. That means RestrictedPython should run on Python 2.6
now. Thanks to Ranjith Kannikara, GSoC Student for the patch.
- Added tests for ternary if expression and for 'with' keyword and
context managers.
3.4.2 (2007-07-28)
------------------
- Changed homepage URL to the CheeseShop site
- Greatly improved README.txt
3.4.1 (2007-06-23)
------------------
- Fixed http://www.zope.org/Collectors/Zope/2295: Bare conditional in
a Zope 2 PythonScript followed by a comment causes SyntaxError.
3.4.0 (2007-06-04)
------------------
- RestrictedPython now has its own release cycle as a separate egg.
- Synchronized with RestrictedPython from Zope 2 tree.
3.2.0 (2006-01-05)
------------------
- Corresponds to the verison of the RestrictedPython package shipped
as part of the Zope 3.2.0 release.
- No changes from 3.1.0.
3.1.0 (2005-10-03)
------------------
- Corresponds to the verison of the RestrictedPython package shipped
as part of the Zope 3.1.0 release.
- Removed unused fossil module, ``SafeMapping``.
- Replaced use of deprecated 'whrandom' module with 'random' (aliased
to 'whrandom' for backward compatibility).
3.0.0 (2004-11-07)
------------------
- Corresponds to the verison of the RestrictedPython package shipped
as part of the Zope X3.0.0 release.
Platform: UNKNOWN
Please refer to src/RestrictedPython/README.txt.
##############################################################################
#
# Copyright (c) 2006 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Bootstrap a buildout-based project
Simply run this script in a directory containing a buildout.cfg.
The script accepts buildout command-line options, so you can
use the -c option to specify an alternate configuration file.
"""
import os, shutil, sys, tempfile, urllib2
from optparse import OptionParser
tmpeggs = tempfile.mkdtemp()
is_jython = sys.platform.startswith('java')
# parsing arguments
parser = OptionParser()
parser.add_option("-v", "--version", dest="version",
help="use a specific zc.buildout version")
parser.add_option("-d", "--distribute",
action="store_true", dest="distribute", default=False,
help="Use Disribute rather than Setuptools.")
parser.add_option("-c", None, action="store", dest="config_file",
help=("Specify the path to the buildout configuration "
"file to be used."))
options, args = parser.parse_args()
# if -c was provided, we push it back into args for buildout' main function
if options.config_file is not None:
args += ['-c', options.config_file]
if options.version is not None:
VERSION = '==%s' % options.version
else:
VERSION = ''
USE_DISTRIBUTE = options.distribute
args = args + ['bootstrap']
to_reload = False
try:
import pkg_resources
if not hasattr(pkg_resources, '_distribute'):
to_reload = True
raise ImportError
except ImportError:
ez = {}
if USE_DISTRIBUTE:
exec urllib2.urlopen('http://python-distribute.org/distribute_setup.py'
).read() in ez
ez['use_setuptools'](to_dir=tmpeggs, download_delay=0, no_fake=True)
else:
exec urllib2.urlopen('http://peak.telecommunity.com/dist/ez_setup.py'
).read() in ez
ez['use_setuptools'](to_dir=tmpeggs, download_delay=0)
if to_reload:
reload(pkg_resources)
else:
import pkg_resources
if sys.platform == 'win32':
def quote(c):
if ' ' in c:
return '"%s"' % c # work around spawn lamosity on windows
else:
return c
else:
def quote (c):
return c
cmd = 'from setuptools.command.easy_install import main; main()'
ws = pkg_resources.working_set
if USE_DISTRIBUTE:
requirement = 'distribute'
else:
requirement = 'setuptools'
if is_jython:
import subprocess
assert subprocess.Popen([sys.executable] + ['-c', quote(cmd), '-mqNxd',
quote(tmpeggs), 'zc.buildout' + VERSION],
env=dict(os.environ,
PYTHONPATH=
ws.find(pkg_resources.Requirement.parse(requirement)).location
),
).wait() == 0
else:
assert os.spawnle(
os.P_WAIT, sys.executable, quote (sys.executable),
'-c', quote (cmd), '-mqNxd', quote (tmpeggs), 'zc.buildout' + VERSION,
dict(os.environ,
PYTHONPATH=
ws.find(pkg_resources.Requirement.parse(requirement)).location
),
) == 0
ws.add_entry(tmpeggs)
ws.require('zc.buildout' + VERSION)
import zc.buildout.buildout
zc.buildout.buildout.main(args)
shutil.rmtree(tmpeggs)
[buildout]
develop = .
parts = interpreter test
[interpreter]
recipe = zc.recipe.egg
interpreter = python
eggs = RestrictedPython
[test]
recipe = zc.recipe.testrunner
eggs = RestrictedPython
[egg_info]
tag_build =
tag_date = 0
tag_svn_revision = 0
setup.py 0 → 100644
##############################################################################
#
# Copyright (c) 2006 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Setup for RestrictedPython package
"""
import os
from setuptools import setup, find_packages
def read(*rnames):
return open(os.path.join(os.path.dirname(__file__), *rnames)).read()
setup(name='RestrictedPython',
version='3.6.0',
url='http://pypi.python.org/pypi/RestrictedPython',
license='ZPL 2.1',
description='RestrictedPython provides a restricted execution '
'environment for Python, e.g. for running untrusted code.',
author='Zope Foundation and Contributors',
author_email='zope-dev@zope.org',
long_description=(read('src', 'RestrictedPython', 'README.txt')
+ '\n' +
read('CHANGES.txt')),
packages = find_packages('src'),
package_dir = {'': 'src'},
install_requires = ['setuptools'],
include_package_data = True,
zip_safe = False,
)
Metadata-Version: 1.0
Name: RestrictedPython
Version: 3.6.0
Summary: RestrictedPython provides a restricted execution environment for Python, e.g. for running untrusted code.
Home-page: http://pypi.python.org/pypi/RestrictedPython
Author: Zope Foundation and Contributors
Author-email: zope-dev@zope.org
License: ZPL 2.1
Description: .. contents::
Overview
========
RestrictedPython provides a ``restricted_compile`` function that works
like the built-in ``compile`` function, except that it allows the
controlled and restricted execution of code:
>>> src = '''
... def hello_world():
... return "Hello World!"
... '''
>>> from RestrictedPython import compile_restricted
>>> code = compile_restricted(src, '<string>', 'exec')
The resulting code can be executed using the ``exec`` built-in:
>>> exec(code)
As a result, the ``hello_world`` function is now available in the
global namespace:
>>> hello_world()
'Hello World!'
Compatibility
=============
This release of RestrictedPython is compatible with Python 2.3, 2.4, 2.5, 2.6,
and 2.7.
Implementing a policy
=====================
RestrictedPython only provides the raw material for restricted
execution. To actually enforce any restrictions, you need to supply a
policy implementation by providing restricted versions of ``print``,
``getattr``, ``setattr``, ``import``, etc. These restricted
implementations are hooked up by providing a set of specially named
objects in the global dict that you use for execution of code.
Specifically:
1. ``_print_`` is a callable object that returns a handler for print
statements. This handler must have a ``write()`` method that
accepts a single string argument, and must return a string when
called. ``RestrictedPython.PrintCollector.PrintCollector`` is a
suitable implementation.
2. ``_write_`` is a guard function taking a single argument. If the
object passed to it may be written to, it should be returned,
otherwise the guard function should raise an exception. ``_write``
is typically called on an object before a ``setattr`` operation.
3. ``_getattr_`` and ``_getitem_`` are guard functions, each of which
takes two arguments. The first is the base object to be accessed,
while the second is the attribute name or item index that will be
read. The guard function should return the attribute or subitem,
or raise an exception.
4. ``__import__`` is the normal Python import hook, and should be used
to control access to Python packages and modules.
5. ``__builtins__`` is the normal Python builtins dictionary, which
should be weeded down to a set that cannot be used to get around
your restrictions. A usable "safe" set is
``RestrictedPython.Guards.safe_builtins``.
To help illustrate how this works under the covers, here's an example
function::
def f(x):
x.foo = x.foo + x[0]
print x
return printed
and (sort of) how it looks after restricted compilation::
def f(x):
# Make local variables from globals.
_print = _print_()
_write = _write_
_getattr = _getattr_
_getitem = _getitem_
# Translation of f(x) above
_write(x).foo = _getattr(x, 'foo') + _getitem(x, 0)
print >>_print, x
return _print()
Examples
========
``print``
---------
To support the ``print`` statement in restricted code, we supply a
``_print_`` object (note that it's a *factory*, e.g. a class or a
callable, from which the restricted machinery will create the object):
>>> from RestrictedPython.PrintCollector import PrintCollector
>>> _print_ = PrintCollector
>>> src = '''
... print "Hello World!"
... '''
>>> code = compile_restricted(src, '<string>', 'exec')
>>> exec(code)
As you can see, the text doesn't appear on stdout. The print
collector collects it. We can have access to the text using the
``printed`` variable, though:
>>> src = '''
... print "Hello World!"
... result = printed
... '''
>>> code = compile_restricted(src, '<string>', 'exec')
>>> exec(code)
>>> result
'Hello World!\n'
Built-ins
---------
By supplying a different ``__builtins__`` dictionary, we can rule out
unsafe operations, such as opening files:
>>> from RestrictedPython.Guards import safe_builtins
>>> restricted_globals = dict(__builtins__ = safe_builtins)
>>> src = '''
... open('/etc/passwd')
... '''
>>> code = compile_restricted(src, '<string>', 'exec')
>>> exec(code) in restricted_globals
Traceback (most recent call last):
...
NameError: name 'open' is not defined
Guards
------
Here's an example of a write guard that never lets restricted code
modify (assign, delete an attribute or item) except dictionaries and
lists:
>>> from RestrictedPython.Guards import full_write_guard
>>> _write_ = full_write_guard
>>> _getattr_ = getattr
>>> class BikeShed(object):
... colour = 'green'
...
>>> shed = BikeShed()
Normally accessing attriutes works as expected, because we're using
the standard ``getattr`` function for the ``_getattr_`` guard:
>>> src = '''
... print shed.colour
... result = printed
... '''
>>> code = compile_restricted(src, '<string>', 'exec')
>>> exec(code)
>>> result
'green\n'
However, changing an attribute doesn't work:
>>> src = '''
... shed.colour = 'red'
... '''
>>> code = compile_restricted(src, '<string>', 'exec')
>>> exec(code)
Traceback (most recent call last):
...
TypeError: attribute-less object (assign or del)
As said, this particular write guard (``full_write_guard``) will allow
restricted code to modify lists and dictionaries:
>>> fibonacci = [1, 1, 2, 3, 4]
>>> transl = dict(one=1, two=2, tres=3)
>>> src = '''
... # correct mistake in list
... fibonacci[-1] = 5
... # one item doesn't belong
... del transl['tres']
... '''
>>> code = compile_restricted(src, '<string>', 'exec')
>>> exec(code)
>>> fibonacci
[1, 1, 2, 3, 5]
>>> sorted(transl.keys())
['one', 'two']
Changes
=======
3.6.0 (2010-07-09)
------------------
- Added name check for names assigned during imports using the
"from x import y" format.
- Added test for name check when assigning an alias using multiple-context with
statements in Python 2.7.
- Added tests for protection of the iterators for dict and set comprehensions
in Python 2.7.
3.6.0a1 (2010-06-05)
--------------------
- Removed support for DocumentTemplate.sequence - this is handled in the
DocumentTemplate package itself.
3.5.2 (2010-04-30)
------------------
- Removed a testing dependency on zope.testing.
3.5.1 (2009-03-17)
------------------
- Added tests for ``Utilities`` module.
- Filtered DeprecationWarnings when importing Python's ``sets`` module.
3.5.0 (2009-02-09)
------------------
- Dropped legacy support for Python 2.1 / 2.2 (``__future__`` imports
of ``nested_scopes`` / ``generators``.).
3.4.3 (2008-10-26)
------------------
- Fixed deprecation warning: ``with`` is now a reserved keyword on
Python 2.6. That means RestrictedPython should run on Python 2.6
now. Thanks to Ranjith Kannikara, GSoC Student for the patch.
- Added tests for ternary if expression and for 'with' keyword and
context managers.
3.4.2 (2007-07-28)
------------------
- Changed homepage URL to the CheeseShop site
- Greatly improved README.txt
3.4.1 (2007-06-23)
------------------
- Fixed http://www.zope.org/Collectors/Zope/2295: Bare conditional in
a Zope 2 PythonScript followed by a comment causes SyntaxError.
3.4.0 (2007-06-04)
------------------
- RestrictedPython now has its own release cycle as a separate egg.
- Synchronized with RestrictedPython from Zope 2 tree.
3.2.0 (2006-01-05)
------------------
- Corresponds to the verison of the RestrictedPython package shipped
as part of the Zope 3.2.0 release.
- No changes from 3.1.0.
3.1.0 (2005-10-03)
------------------
- Corresponds to the verison of the RestrictedPython package shipped
as part of the Zope 3.1.0 release.
- Removed unused fossil module, ``SafeMapping``.
- Replaced use of deprecated 'whrandom' module with 'random' (aliased
to 'whrandom' for backward compatibility).
3.0.0 (2004-11-07)
------------------
- Corresponds to the verison of the RestrictedPython package shipped
as part of the Zope X3.0.0 release.
Platform: UNKNOWN
CHANGES.txt
COPYRIGHT.txt
LICENSE.txt
README.txt
bootstrap.py
buildout.cfg
setup.py
src/RestrictedPython/Eval.py
src/RestrictedPython/Guards.py
src/RestrictedPython/Limits.py
src/RestrictedPython/MutatingWalker.py
src/RestrictedPython/PrintCollector.py
src/RestrictedPython/RCompile.py
src/RestrictedPython/README.txt
src/RestrictedPython/RestrictionMutator.py
src/RestrictedPython/SelectCompiler.py
src/RestrictedPython/Utilities.py
src/RestrictedPython/__init__.py
src/RestrictedPython/notes.txt
src/RestrictedPython.egg-info/PKG-INFO
src/RestrictedPython.egg-info/SOURCES.txt
src/RestrictedPython.egg-info/dependency_links.txt
src/RestrictedPython.egg-info/not-zip-safe
src/RestrictedPython.egg-info/requires.txt
src/RestrictedPython.egg-info/top_level.txt
src/RestrictedPython/tests/__init__.py
src/RestrictedPython/tests/before_and_after.py
src/RestrictedPython/tests/before_and_after24.py
src/RestrictedPython/tests/before_and_after25.py
src/RestrictedPython/tests/before_and_after26.py
src/RestrictedPython/tests/before_and_after27.py
src/RestrictedPython/tests/class.py
src/RestrictedPython/tests/lambda.py
src/RestrictedPython/tests/restricted_module.py
src/RestrictedPython/tests/security_in_syntax.py
src/RestrictedPython/tests/security_in_syntax26.py
src/RestrictedPython/tests/security_in_syntax27.py
src/RestrictedPython/tests/testCompile.py
src/RestrictedPython/tests/testREADME.py
src/RestrictedPython/tests/testRestrictions.py
src/RestrictedPython/tests/testUtiliities.py
src/RestrictedPython/tests/unpack.py
src/RestrictedPython/tests/verify.py
\ No newline at end of file
setuptools
\ No newline at end of file
RestrictedPython
##############################################################################
#
# Copyright (c) 2002 Zope Foundation and Contributors.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
##############################################################################
"""Restricted Python Expressions
"""
__version__='$Revision: 1.6 $'[11:-2]
from RestrictedPython import compile_restricted_eval
from string import translate, strip
import string
nltosp = string.maketrans('\r\n',' ')
default_guarded_getattr = getattr # No restrictions.
def default_guarded_getitem(ob, index):
# No restrictions.
return ob[index]
PROFILE = 0
class RestrictionCapableEval:
"""A base class for restricted code."""
globals = {'__builtins__': None}
rcode = None # restricted
ucode = None # unrestricted
used = None
def __init__(self, expr):
"""Create a restricted expression
where:
expr -- a string containing the expression to be evaluated.
"""
expr = strip(expr)
self.__name__ = expr
expr = translate(expr, nltosp)
self.expr = expr
self.prepUnrestrictedCode() # Catch syntax errors.
def prepRestrictedCode(self):
if self.rcode is None:
if PROFILE:
from time import clock
start = clock()
co, err, warn, used = compile_restricted_eval(
self.expr, '<string>')
if PROFILE:
end = clock()
print 'prepRestrictedCode: %d ms for %s' % (
(end - start) * 1000, `self.expr`)
if err:
raise SyntaxError, err[0]
self.used = tuple(used.keys())
self.rcode = co
def prepUnrestrictedCode(self):
if self.ucode is None:
# Use the standard compiler.
co = compile(self.expr, '<string>', 'eval')
if self.used is None:
# Examine the code object, discovering which names
# the expression needs.
names=list(co.co_names)
used={}
i=0
code=co.co_code
l=len(code)
LOAD_NAME=101
HAVE_ARGUMENT=90
while(i < l):
c=ord(code[i])
if c==LOAD_NAME:
name=names[ord(code[i+1])+256*ord(code[i+2])]
used[name]=1
i=i+3
elif c >= HAVE_ARGUMENT: i=i+3
else: i=i+1
self.used=tuple(used.keys())
self.ucode=co
def eval(self, mapping):
# This default implementation is probably not very useful. :-(
# This is meant to be overridden.
self.prepRestrictedCode()
code = self.rcode
d = {'_getattr_': default_guarded_getattr,
'_getitem_': default_guarded_getitem}
d.update(self.globals)
has_key = d.has_key
for name in self.used:
try:
if not has_key(name):
d[name] = mapping[name]
except KeyError:
# Swallow KeyErrors since the expression
# might not actually need the name. If it
# does need the name, a NameError will occur.
pass
return eval(code, d)
def __call__(self, **kw):
return self.eval(kw)
##############################################################################
#
# Copyright (c) 2002 Zope Foundation and Contributors.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
##############################################################################
__version__ = '$Revision: 1.14 $'[11:-2]
import exceptions
# This tiny set of safe builtins is extended by users of the module.
# AccessControl.ZopeGuards contains a large set of wrappers for builtins.
# DocumentTemplate.DT_UTil contains a few.
safe_builtins = {}
for name in ['False', 'None', 'True', 'abs', 'basestring', 'bool', 'callable',
'chr', 'cmp', 'complex', 'divmod', 'float', 'hash',
'hex', 'id', 'int', 'isinstance', 'issubclass', 'len',
'long', 'oct', 'ord', 'pow', 'range', 'repr', 'round',
'str', 'tuple', 'unichr', 'unicode', 'xrange', 'zip']:
safe_builtins[name] = __builtins__[name]
# Wrappers provided by this module:
# delattr
# setattr
# Wrappers provided by ZopeGuards:
# __import__
# apply
# dict
# enumerate
# filter
# getattr
# hasattr
# iter
# list
# map
# max
# min
# sum
# all
# any
# Builtins that are intentionally disabled
# compile - don't let them produce new code
# dir - a general purpose introspector, probably hard to wrap
# execfile - no direct I/O
# file - no direct I/O
# globals - uncontrolled namespace access
# input - no direct I/O
# locals - uncontrolled namespace access
# open - no direct I/O
# raw_input - no direct I/O
# vars - uncontrolled namespace access
# There are several strings that describe Python. I think there's no
# point to including these, although they are obviously safe:
# copyright, credits, exit, help, license, quit
# Not provided anywhere. Do something about these? Several are
# related to new-style classes, which we are too scared of to support
# <0.3 wink>. coerce, buffer, and reload are esoteric enough that no
# one should care.
# buffer
# bytes
# bytearray
# classmethod
# coerce
# eval
# intern
# memoryview
# object
# property
# reload
# slice
# staticmethod
# super
# type
for name in dir(exceptions):
if name[0] != "_":
safe_builtins[name] = getattr(exceptions, name)
def _write_wrapper():
# Construct the write wrapper class
def _handler(secattr, error_msg):
# Make a class method.
def handler(self, *args):
try:
f = getattr(self.ob, secattr)
except AttributeError:
raise TypeError, error_msg
f(*args)
return handler
class Wrapper:
def __len__(self):
# Required for slices with negative bounds.
return len(self.ob)
def __init__(self, ob):
self.__dict__['ob'] = ob
__setitem__ = _handler('__guarded_setitem__',
'object does not support item or slice assignment')
__delitem__ = _handler('__guarded_delitem__',
'object does not support item or slice assignment')
__setattr__ = _handler('__guarded_setattr__',
'attribute-less object (assign or del)')
__delattr__ = _handler('__guarded_delattr__',
'attribute-less object (assign or del)')
return Wrapper
def _full_write_guard():
# Nested scope abuse!
# safetype and Wrapper variables are used by guard()
safetype = {dict: True, list: True}.has_key
Wrapper = _write_wrapper()
def guard(ob):
# Don't bother wrapping simple types, or objects that claim to
# handle their own write security.
if safetype(type(ob)) or hasattr(ob, '_guarded_writes'):
return ob
# Hand the object to the Wrapper instance, then return the instance.
return Wrapper(ob)
return guard
full_write_guard = _full_write_guard()
def guarded_setattr(object, name, value):
setattr(full_write_guard(object), name, value)
safe_builtins['setattr'] = guarded_setattr
def guarded_delattr(object, name):
delattr(full_write_guard(object), name)
safe_builtins['delattr'] = guarded_delattr
##############################################################################
#
# Copyright (c) 2002 Zope Foundation and Contributors.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
##############################################################################
__version__='$Revision: 1.5 $'[11:-2]
limited_builtins = {}
def limited_range(iFirst, *args):
# limited range function from Martijn Pieters
RANGELIMIT = 1000
if not len(args):
iStart, iEnd, iStep = 0, iFirst, 1
elif len(args) == 1:
iStart, iEnd, iStep = iFirst, args[0], 1
elif len(args) == 2:
iStart, iEnd, iStep = iFirst, args[0], args[1]
else:
raise AttributeError, 'range() requires 1-3 int arguments'
if iStep == 0: raise ValueError, 'zero step for range()'
iLen = int((iEnd - iStart) / iStep)
if iLen < 0: iLen = 0
if iLen >= RANGELIMIT: raise ValueError, 'range() too large'
return range(iStart, iEnd, iStep)
limited_builtins['range'] = limited_range
def limited_list(seq):
if isinstance(seq, str):
raise TypeError, 'cannot convert string to list'
return list(seq)
limited_builtins['list'] = limited_list
def limited_tuple(seq):
if isinstance(seq, str):
raise TypeError, 'cannot convert string to tuple'
return tuple(seq)
limited_builtins['tuple'] = limited_tuple
##############################################################################
#
# Copyright (c) 2002 Zope Foundation and Contributors.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
##############################################################################
__version__='$Revision: 1.6 $'[11:-2]
from SelectCompiler import ast
ListType = type([])
TupleType = type(())
SequenceTypes = (ListType, TupleType)
class MutatingWalker:
def __init__(self, visitor):
self.visitor = visitor
self._cache = {}
def defaultVisitNode(self, node, walker=None, exclude=None):
for name, child in node.__dict__.items():
if exclude is not None and name in exclude:
continue
v = self.dispatchObject(child)
if v is not child:
# Replace the node.
node.__dict__[name] = v
return node
def visitSequence(self, seq):
res = seq
for idx in range(len(seq)):
child = seq[idx]
v = self.dispatchObject(child)
if v is not child:
# Change the sequence.
if type(res) is ListType:
res[idx : idx + 1] = [v]
else:
res = res[:idx] + (v,) + res[idx + 1:]
return res
def dispatchObject(self, ob):
'''
Expected to return either ob or something that will take
its place.
'''
if isinstance(ob, ast.Node):
return self.dispatchNode(ob)
elif type(ob) in SequenceTypes:
return self.visitSequence(ob)
else:
return ob
def dispatchNode(self, node):
klass = node.__class__
meth = self._cache.get(klass, None)
if meth is None:
className = klass.__name__
meth = getattr(self.visitor, 'visit' + className,
self.defaultVisitNode)
self._cache[klass] = meth
return meth(node, self)
def walk(tree, visitor):
return MutatingWalker(visitor).dispatchNode(tree)
##############################################################################
#
# Copyright (c) 2002 Zope Foundation and Contributors.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
##############################################################################
__version__='$Revision: 1.4 $'[11:-2]
class PrintCollector:
'''Collect written text, and return it when called.'''
def __init__(self):
self.txt = []
def write(self, text):
self.txt.append(text)
def __call__(self):
return ''.join(self.txt)
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment