diff options
| author | Christophe Simonis <chs@openerp.com> | 2014-04-15 15:36:50 +0200 |
|---|---|---|
| committer | Christophe Simonis <chs@openerp.com> | 2014-04-15 15:36:50 +0200 |
| commit | 3d2e9b4d2b6647016268ca3b5f7dd5c523a4fbb6 (patch) | |
| tree | 8014712ec2ae83aa443eebca36fe253249ef6173 /openerp/tools/safe_eval.py | |
| parent | f8d5ef0f80c216abd2e810edd4b9761c69c36dad (diff) | |
| parent | 001a034e587624e0bcca88b55d8cb5a580bec3a1 (diff) | |
[MERGE] forward port of branch 7.0 up to revid 5281 launchpad_translations_on_behalf_of_openerp-20140412094159-mhy3v2prb3ctx32k
bzr revid: jke@openerp.com-20140409153527-mic1a8afcvdhsd27
bzr revid: chs@openerp.com-20140410102422-fcwxhjk40z0oy8x5
bzr revid: chs@openerp.com-20140415133650-y46i0o3qkb2atbvi
Diffstat (limited to 'openerp/tools/safe_eval.py')
| -rw-r--r-- | openerp/tools/safe_eval.py | 80 |
1 files changed, 61 insertions, 19 deletions
diff --git a/openerp/tools/safe_eval.py b/openerp/tools/safe_eval.py index 508a072a3b2..2f280685350 100644 --- a/openerp/tools/safe_eval.py +++ b/openerp/tools/safe_eval.py @@ -71,7 +71,8 @@ _SAFE_OPCODES = _EXPR_OPCODES.union(set(opmap[x] for x in [ 'CONTINUE_LOOP', 'RAISE_VARARGS', # New in Python 2.7 - http://bugs.python.org/issue4715 : 'JUMP_IF_FALSE_OR_POP', 'JUMP_IF_TRUE_OR_POP', 'POP_JUMP_IF_FALSE', - 'POP_JUMP_IF_TRUE', 'SETUP_EXCEPT', 'END_FINALLY' + 'POP_JUMP_IF_TRUE', 'SETUP_EXCEPT', 'END_FINALLY', 'LOAD_FAST', + 'LOAD_GLOBAL', # Only allows access to restricted globals ] if x in opmap)) _logger = logging.getLogger(__name__) @@ -86,16 +87,65 @@ def _get_opcodes(codeobj): [100, 100, 23, 100, 100, 102, 103, 83] """ i = 0 - opcodes = [] byte_codes = codeobj.co_code while i < len(byte_codes): code = ord(byte_codes[i]) - opcodes.append(code) + yield code + if code >= HAVE_ARGUMENT: i += 3 else: i += 1 - return opcodes + +def assert_no_dunder_name(code_obj, expr): + """ assert_no_dunder_name(code_obj, expr) -> None + + Asserts that the code object does not refer to any "dunder name" + (__$name__), so that safe_eval prevents access to any internal-ish Python + attribute or method (both are loaded via LOAD_ATTR which uses a name, not a + const or a var). + + Checks that no such name exists in the provided code object (co_names). + + :param code_obj: code object to name-validate + :type code_obj: CodeType + :param str expr: expression corresponding to the code object, for debugging + purposes + :raises NameError: in case a forbidden name (containing two underscores) + is found in ``code_obj`` + + .. note:: actually forbids every name containing 2 underscores + """ + for name in code_obj.co_names: + if "__" in name: + raise NameError('Access to forbidden name %r (%r)' % (name, expr)) + +def assert_valid_codeobj(allowed_codes, code_obj, expr): + """ Asserts that the provided code object validates against the bytecode + and name constraints. + + Recursively validates the code objects stored in its co_consts in case + lambdas are being created/used (lambdas generate their own separated code + objects and don't live in the root one) + + :param allowed_codes: list of permissible bytecode instructions + :type allowed_codes: set(int) + :param code_obj: code object to name-validate + :type code_obj: CodeType + :param str expr: expression corresponding to the code object, for debugging + purposes + :raises ValueError: in case of forbidden bytecode in ``code_obj`` + :raises NameError: in case a forbidden name (containing two underscores) + is found in ``code_obj`` + """ + assert_no_dunder_name(code_obj, expr) + for opcode in _get_opcodes(code_obj): + if opcode not in allowed_codes: + raise ValueError( + "opcode %s not allowed (%r)" % (opname[opcode], expr)) + for const in code_obj.co_consts: + if isinstance(const, CodeType): + assert_valid_codeobj(allowed_codes, const, 'lambda') def test_expr(expr, allowed_codes, mode="eval"): """test_expr(expression, allowed_codes[, mode]) -> code_object @@ -110,15 +160,13 @@ def test_expr(expr, allowed_codes, mode="eval"): # eval() does not like leading/trailing whitespace expr = expr.strip() code_obj = compile(expr, "", mode) - except (SyntaxError, TypeError): + except (SyntaxError, TypeError, ValueError): raise except Exception, e: import sys exc_info = sys.exc_info() raise ValueError, '"%s" while compiling\n%r' % (ustr(e), expr), exc_info[2] - for code in _get_opcodes(code_obj): - if code not in allowed_codes: - raise ValueError("opcode %s not allowed (%r)" % (opname[code], expr)) + assert_valid_codeobj(allowed_codes, code_obj, expr) return code_obj @@ -187,19 +235,13 @@ def safe_eval(expr, globals_dict=None, locals_dict=None, mode="eval", nocopy=Fal This can be used to e.g. evaluate an OpenERP domain expression from an untrusted source. - Throws TypeError, SyntaxError or ValueError (not allowed) accordingly. - - >>> safe_eval("__import__('sys').modules") - Traceback (most recent call last): - ... - ValueError: opcode LOAD_NAME not allowed - + :throws TypeError: If the expression provided is a code object + :throws SyntaxError: If the expression provided is not valid Python + :throws NameError: If the expression provided accesses forbidden names + :throws ValueError: If the expression provided uses forbidden bytecode """ if isinstance(expr, CodeType): - raise ValueError("safe_eval does not allow direct evaluation of code objects.") - - if '__subclasses__' in expr: - raise ValueError('expression not allowed (__subclasses__)') + raise TypeError("safe_eval does not allow direct evaluation of code objects.") if globals_dict is None: globals_dict = {} |
