Package PyFoam :: Package ThirdParty :: Module pyratemp :: Class EvalPseudoSandbox
[hide private]
[frames] | no frames]

Class EvalPseudoSandbox

source code


An eval-pseudo-sandbox.

The pseudo-sandbox restricts the available functions/objects, so the
code can only access:

- some of the builtin python-functions, which are considered "safe"
  (see safe_builtins)
- some additional functions (exists(), default(), setvar())
- the passed objects incl. their methods.

Additionally, names beginning with "_" are forbidden.
This is to prevent things like '0 .__class__', with which you could
easily break out of a "sandbox".

Be careful to only pass "safe" objects/functions to the template,
because any unsafe function/method could break the sandbox!
For maximum security, restrict the access to as few objects/functions
as possible!

:Warning:
    Note that this is no real sandbox! (And although I don't know any
    way to break out of the sandbox without passing-in an unsafe object,
    I cannot guarantee that there is no such way. So use with care.)

    Take care if you want to use it for untrusted code!!

Instance Methods [hide private]
 
__init__(self) source code
 
compile(self, expr)
Compile a python-eval-expression.
source code
 
eval(self, expr, locals)
Eval a python-eval-expression.
source code
 
f_default(self, expr, default=None)
``default()`` for the sandboxed code.
source code
 
f_exists(self, varname)
``exists()`` for the sandboxed code.
source code
 
f_import(self, name, *args, **kwargs)
``import``/``__import__()`` for the sandboxed code.
source code
 
f_setvar(self, name, expr)
``setvar()`` for the sandboxed code.
source code
 
register(self, name, obj)
Add an object to the "allowed eval-globals".
source code
Class Variables [hide private]
  safe_builtins = {'abs': <built-in function abs>, 'bool': <type...
  safe_builtins_python2 = {'False': '__builtin__.False', 'None':...
Method Details [hide private]

compile(self, expr)

source code 
Compile a python-eval-expression.

- Use a compile-cache.
- Raise a `NameError` if `expr` contains a name beginning with ``_``.

:Returns: the compiled `expr`
:Exceptions:
    - `SyntaxError`: for compile-errors
    - `NameError`: if expr contains a name beginning with ``_``

eval(self, expr, locals)

source code 

Eval a python-eval-expression.

Sets ``self.locals_ptr`` to ``locales`` and compiles the code before evaluating.

f_default(self, expr, default=None)

source code 
``default()`` for the sandboxed code.

Try to evaluate an expression and return the result or a
fallback-/default-value; the `default`-value is used
if `expr` does not exist/is invalid/results in None.

This is very useful for optional data.

:Parameter:
    - expr: eval-expression
    - default: fallback-falue if eval(expr) fails or is None.
:Returns:
    the eval-result or the "fallback"-value.

:Note:      the eval-expression has to be quoted! (like in eval)
:Example:   see module-docstring

f_exists(self, varname)

source code 

``exists()`` for the sandboxed code.

Test if the variable `varname` exists in the current locals-namespace.

This only works for single variable names. If you want to test complicated expressions, use i.e. `default`. (i.e. `default("expr",False)`)

:Note: the variable-name has to be quoted! (like in eval) :Example: see module-docstring

f_import(self, name, *args, **kwargs)

source code 
``import``/``__import__()`` for the sandboxed code.

Since "import" is insecure, the PseudoSandbox does not allow to
import other modules. But since some functions need to import
other modules (e.g. "datetime.datetime.strftime" imports "time"),
this function replaces the builtin "import" and allows to use
modules which are already accessible by the sandboxed code.

:Note:
    - This probably only works for rather simple imports.
    - For security, it may be better to avoid such (complex) modules
      which import other modules. (e.g. use time.localtime and
      time.strftime instead of datetime.datetime.strftime)

:Example:

    >>> from datetime import datetime
    >>> import pyratemp
    >>> t = pyratemp.Template('@!mytime.strftime("%H:%M:%S")!@')
    >>> print t(mytime=datetime.now())
    Traceback (most recent call last):
      ...
    ImportError: import not allowed in pseudo-sandbox; try to import 'time' yourself and pass it to the sandbox/template
    >>> import time
    >>> print t(mytime=datetime.strptime("13:40:54", "%H:%M:%S"), time=time)
    13:40:54

    # >>> print t(mytime=datetime.now(), time=time)
    # 13:40:54

f_setvar(self, name, expr)

source code 

``setvar()`` for the sandboxed code.

Set a variable.

:Example: see module-docstring

register(self, name, obj)

source code 

Add an object to the "allowed eval-globals".

Mainly useful to add user-defined functions to the pseudo-sandbox.


Class Variable Details [hide private]

safe_builtins

Value:
{'abs': <built-in function abs>,
 'bool': <type 'bool'>,
 'chr': <built-in function chr>,
 'complex': <type 'complex'>,
 'dict': <type 'dict'>,
 'divmod': <built-in function divmod>,
 'enumerate': <type 'enumerate'>,
 'float': <type 'float'>,
...

safe_builtins_python2

Value:
{'False': '__builtin__.False',
 'None': '__builtin__.None',
 'True': '__builtin__.True',
 'cmp': '__builtin__.cmp',
 'long': '__builtin__.long',
 'unichr': '__builtin__.unichr',
 'unicode': '__builtin__.unicode',
 'xrange': '__builtin__.xrange'}