{"id":18770055,"url":"https://github.com/yaroslaff/evalidate","last_synced_at":"2025-04-06T19:11:27.157Z","repository":{"id":57427207,"uuid":"405613637","full_name":"yaroslaff/evalidate","owner":"yaroslaff","description":"Safe and fast evaluation of untrusted user-supplied python expressions","archived":false,"fork":false,"pushed_at":"2024-12-09T11:59:53.000Z","size":84,"stargazers_count":30,"open_issues_count":0,"forks_count":4,"subscribers_count":3,"default_branch":"master","last_synced_at":"2025-03-30T18:08:12.591Z","etag":null,"topics":["eval","evaluate","evaluation","expression","python","python3","safe","sandbox","secure","security","validate"],"latest_commit_sha":null,"homepage":"https://github.com/yaroslaff/evalidate","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/yaroslaff.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2021-09-12T10:41:15.000Z","updated_at":"2025-03-21T02:21:18.000Z","dependencies_parsed_at":"2024-12-24T11:14:42.218Z","dependency_job_id":"54353494-2533-4e4b-89cc-e3b56a161c65","html_url":"https://github.com/yaroslaff/evalidate","commit_stats":{"total_commits":76,"total_committers":2,"mean_commits":38.0,"dds":"0.013157894736842146","last_synced_commit":"107c872fceae49c922d8d88d794ea3fb728d7e47"},"previous_names":[],"tags_count":7,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yaroslaff%2Fevalidate","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yaroslaff%2Fevalidate/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yaroslaff%2Fevalidate/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yaroslaff%2Fevalidate/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/yaroslaff","download_url":"https://codeload.github.com/yaroslaff/evalidate/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247535517,"owners_count":20954576,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["eval","evaluate","evaluation","expression","python","python3","safe","sandbox","secure","security","validate"],"created_at":"2024-11-07T19:17:56.814Z","updated_at":"2025-04-06T19:11:27.140Z","avatar_url":"https://github.com/yaroslaff.png","language":"Python","readme":"﻿# Evalidate\nEvalidate is simple python module for safe and very fast eval()'uating user-supplied (possible malicious) python expressions.\n\n## Upgrade warning\nVersion 2.0 is backward incompatible with older versions. `safeeval()` and `evalidate()` methods are removed, and EvalMode class is introduced.\n\nSee [upgrade example in ticket](https://github.com/yaroslaff/evalidate/issues/5) or use older (any before 2.0.0, e.g. [v1.1.0](https://pypi.org/project/evalidate/1.1.0/)) if you have old code and do not want to upgrade. But upgrading is easy, so please consider this option.\n\n## Purpose\nOriginally it's developed for filtering complex data structures e.g. \n\nFind cheap smartphones available for sale:\n```python\ncategory==\"smartphones\" and price\u003c300 and stock\u003e0\n```\n\nBut also, it can be used for other expressions, e.g. arithmetical, like\n```python\na+b-100\n```\n\nEvalidate is fastest among all (known to me) secure eval python modules.\n\n## Install\n\n```shell\npip3 install evalidate\n```\n    \n## Security\n\nBuilt-in python features such as compile() or eval() are quite powerful to run any kind of user-supplied code, but could be insecure if used code is malicious like `os.system(\"rm -rf /\")`. Evalidate works on whitelist principle, allowing code only if it consist only of safe operations (based on authors views about what is safe and what is not, your mileage may vary - but you can supply your list of safe operations)\n\n\n## TL;DR. Just give me safe eval!\n```python       \nfrom evalidate import Expr, EvalException\n\nsrc = 'a + 40 \u003e b'\n# src = \"__import__('os').system('clear')\"\n\ntry:\n    print(Expr(src).eval({'a':10, 'b':42}))\nexcept EvalException as e:\n    print(e)\n```\n\nGives output: `True`\n\nIn case of dangerous code (uncomment second src line to test):\n  \noutput will be: `ERR: Operation type Call is not allowed`\n\n\n## Exceptions\nEvalidate throws exceptions `CompilationException`, `ValidationException`, `ExecutionException`. All of them\ninherit from base exception class `EvalException`.\n\n## Configure validation\nEvalidate is very flexible, depending on security model, same code can either pass validation or raise exception.\n\nEvalModel is security model class for eval - lists of allowed AST nodes, function calls, attributes and dict of imported functions. There is built-in model `base_eval_model` with basic operations allowed (which are safe from authors point of view).\n\nYou can create custom empty model (and extend it later):\n~~~python\nmy_model = evalidate.EvalModel()\n~~~\n\n(nothing is allowed by default, even `1+2` will not be considered safe)\n\nor you may start from `base_eval_mode` and extend it:\n~~~python\nfrom evalidate import Expr, base_eval_model\n\nmy_model = base_eval_model.clone()\nmy_model.nodes.append('Mult')\n\nExpr('2*2', model=my_model).eval()\n~~~\n\nTo enable `int()` function, need to allow `'Call'` node and add this function to list of allowed function:\n\n~~~python\nmy_model.nodes.append('Call')\nmy_model.allowed_functions.append('int')\n\nExpr('int(36.6)', model=my_model).eval()\n~~~\n\nOr, to call attributes:\n~~~python\nm = base_eval_model.clone()\nm.nodes.extend(['Call', 'Attribute'])\nm.attributes.append('startswith')\n\nsrc = '\"abcdef\".startswith(\"abc\")'\nr = evalidate.Expr(src, model=m).eval()\n~~~\n\nBut even with this settings, exploiting it with expression like `__builtins__[\"eval\"](1)` will fail (good!).\n\n\n### Exporting my functions to eval code\n~~~python\ndef one():\n  return 1\n\nm = base_eval_model.clone()\nm.nodes.append('Call')\nm.imported_functions[\"one\"] = one\nExpr('one()', model=m).eval()\n~~~\n\n## Improve speed by using native eval() with validated code\nEvalidate is very fast, but it's still takes CPU cycles... If you want to achieve maximal possible speed, you can use python native [eval](https://docs.python.org/3/library/functions.html#eval) with this kind of code:\n\n~~~python\nfrom evalidate import Expr\n\nd = dict(a=1, b=2)\nexpr = Expr('a+b')\neval(expr.code, None, d) # \u003c-- native python eval, will run at eval() speed\n~~~\n\nThis is as secure as expr.eval(), because `expr.code` is already validated to be secure.\n\nDifference is very little: execution of `expr.code` can throw any exception, while `expr.eval()` can throw only ExecutionException. Also, if you want to export your functions to eval, you should do this manually. \n\n## Limitations\n\nevalidate uses [ast.parse()](https://docs.python.org/3/library/ast.html#ast.parse) to get [AST node](https://docs.python.org/3/library/ast.html#node-classes) to validate it.\n\n\u003eWarning\n\u003e\n\u003eIt is possible to crash the Python interpreter with a sufficiently large/complex string due to stack depth limitations in Python’s AST compiler. \n\nIn my test, works well with 200 nested int(): `int(int(.... int(1)...))` but not with 201. Source code is 1000+ characters. But even if evalidate will get such code, it will just raise `CompilationException`.\n\n\n### evalidate.security.test_security()\nEvalidate is very flexible and it's possible to shoot yourself in foot if you will try hard. `test_security()` checks your configuration (nodes, funcs, attrs) against given list of possible attack code or against built-in list of attacks. `test_security()` returns True if everything is OK (all attacks raised ValidationException) or False if something passed.\n\nThis code will never print (I hope).\n~~~python\nfrom evalidate.security import test_security\n\ntest_security() or print(\"default rules are vulnerable!\")\n~~~\n\nBut this will fail because nodes/funcs leads to successful validation for attack (suppose you do not want anyone to call `int()`)\n~~~python\nfrom evalidate.security import test_security\n\nattacks = ['int(1)']\n\ntest_security(attacks, addnodes=['Call'], funcs=['int'], verbose=True)\n~~~\n\nIt will print:\n~~~\nTesting attack code:\nint(1)\nProblem! Attack passed validation without exception!\nCode:\nint(1)\n~~~\n\n\n\n\n## Example\n\n### Filtering by user-supplied condition ###\n\nThis is code of `examples/products.py`. Expression is validated and compiled once and executed (as byte-code, very fast) many times, so filtering is both fast and secure.\n\n\n~~~python\n#!/usr/bin/env python3\n\nimport requests\nfrom evalidate import Expr, ValidationException, CompilationException, ExecutionException\nimport json\nimport sys\n\ndata = requests.get('https://dummyjson.com/products?limit=100').json()\n\ntry:\n    src = sys.argv[1]\nexcept IndexError:\n    src = 'True'\n\ntry:\n    expr = Expr(src)\nexcept (ValidationException, CompilationException) as e:\n    print(e)\n    sys.exit(1)\n\nc=0\nfor p in data['products']:\n    # print(p)\n    try:\n        r = expr.eval(p)\n        if r:\n            print(json.dumps(p, indent=2))\n            c+=1\n    except ExecutionException as e:\n        print(\"Runtime exception:\", e)\nprint(\"# {} products matches\".format(c))\n~~~\n\n~~~shell\n# print all 100 products\n./products.py\n\n# Only cheap products, 8 matches\n./products.py 'price\u003c20'\n\n# smartphones (5)\n./products.py 'category==\"smartphones\"'\n\n# good smartphones\n./products.py 'category==\"smartphones\" and rating\u003e4.5'\n\n# cheap smartphones\n./products.py 'category==\"smartphones\" and price\u003c300'\n~~~\n                                       \n\n## Similar projects and benchmark\n\n[asteval](https://newville.github.io/asteval/)\n\nWhile asteval can compute much more complex code (define functions, use python math libraries) it has drawbacks:\n- asteval is much slower (evalidate can be used at speed of eval() python bytecode)\n- user can provide source code which runs very long time and consumes many resources \n\n\n[simpleeval](https://github.com/danthedeckie/simpleeval)\nVery similar project, using AST approach too and optimized to re-evaluate pre-parsed expressions. But parsed expressions are stored as more high-level [ast.Expr](https://docs.python.org/3/library/ast.html#ast.Expr) type and this approach is few times slower, while evalidate uses python native `code` type and evaluation itself goes at speed of python eval()\n\nevalidate is good to run same expression against different data.\n\n## Benchmarking\nWe use `benchmark/benchmark.py` in this repository.\nWe prepare list of 1 million of products (actually, we take just 100 products sample, but repeat it 10 000 times to get 1 million), and then filter it, finding only specific products on \"untrusted user-supplied expression\" (`price \u003c 20` in this case)\n\n~~~\nProducts: 1000000 items\nevalidate_raw_eval(): 0.266s\nevalidate_eval(): 0.326s\ntest_simpleeval(): 1.824s\ntest_asteval(): 26.106s\n~~~\n\nAs you see, evalidate is few times faster then simpleeval and both are much faster then asteval.\n\nMaybe my test is not perfectly optimized (I'm not expert with simpleeval/asteval), if you can suggest better filtering sample code (which produces faster result), I will include it. (Benchmark code must assume expression as unknown in advance and untrusted)\n\n\n## Read about eval() risks\n\n- https://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html\n- https://netsec.expert/posts/breaking-python3-eval-protections/\n- https://realpython.com/python-eval-function/\n\nNote: realpython article shows example with nice short method of validation source (using `code.co_names`), \nbut it's vulnerable, it passes \"bomb\" from Ned Batchelder article (bomb has empty `co_names` tuple) and crash interpreter. Evalidate can block this code and similar bombs (unless you will intentionally configure evalidate to pass specific bomb code. Yes, with evalidate it is hard to shoot yourself in the foot, but it is possible if you will try hard).\n\n## More info\n\nWant more info? Check source code of module, it's very short and simple, easy to modify\n\n## Contact\n\nWrite me: yaroslaff at gmail.com\n","funding_links":[],"categories":["Python"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fyaroslaff%2Fevalidate","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fyaroslaff%2Fevalidate","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fyaroslaff%2Fevalidate/lists"}