tinycodinglm / sec /sec-0027.jsonl
winapiadmin's picture
Upload folder using huggingface_hub (part 16)
d517dc9 verified
|
Raw History Blame
2.81 kB
{"type": "session", "harness": "opencode", "id": "sec-0027", "name": "Security: Python's built-in function `eval()` can lead to ar"}
{"type": "message", "message": {"role": "system", "content": "You are an expert security engineer. You analyze code for vulnerabilities and provide secure alternatives. When reviewing code, identify the vulnerability type, explain the risk, and provide a fixed version with proper input validation, sanitization, or safe API usage."}}
{"type": "message", "message": {"role": "user", "content": "Language: python\nVulnerability: Python's built-in function `eval()` can lead to arbitrary code execution if used improperly.\n\nWrite a python code that takes user input as Python code and executes it using the built-in `eval()` function. The executed code should be sanitized to prevent arbitrary code execution."}}
{"type": "message", "message": {"role": "assistant", "content": "```python\nimport ast\n\nclass RestrictedPython(ast.NodeTransformer):\n \"\"\"\n AST NodeTransformer that restricts the allowed Python features.\n \"\"\"\n def visit_Call(self, node):\n # Only allow calls to len, str, range, list, dict, tuple, set, frozenset, print, type, id, sorted, reversed, enumerate, abs, all, any, bin, bool, chr, complex, divmod, float, hex, int, max, min, next, oct, ord, pow, round, slice, sorted, str, sum, \n # and their respective type aliases.\n allowed_calls = {'len', 'str', 'range', 'list', 'dict', 'tuple', 'set', 'frozenset', 'print', 'type', 'id', 'sorted', 'reversed', 'enumerate', 'abs', 'all', 'any', 'bin', 'bool', 'chr', 'complex', 'divmod', 'float', 'hex', 'int', 'max', 'min', 'next', 'oct', 'pow', 'round', 'slice', 'sorted', 'str', 'sum'}\n if not (isinstance(node.func, ast.Name) and node.func.id in allowed_calls):\n raise ValueError(f\"Disallowed call: {ast.unparse(node)}\")\n self.generic_visit(node)\n\ndef evaluate_input(user_input):\n # Parse the user input into an AST.\n tree = ast.parse(user_input, mode='exec')\n \n # Transform the AST to ensure it only contains allowed operations.\n RestrictedPython().visit(tree)\n \n # Compile the transformed AST into a code object.\n code = compile(tree, filename='<input>', mode='exec')\n \n # Define a safe environment for the code to run in.\n safe_dict = {\n '__builtins__': {},\n }\n \n # Execute the code in the safe environment.\n exec(code, {\"__builtins__\": {}}, safe_dict)\n \n return safe_dict\n\ndef main():\n user_input = input(\"Enter some Python code to execute: \")\n try:\n result = evaluate_input(user_input)\n print(\"Result:\", result)\n except Exception as e:\n print(\"Error:\", e)\n\nif __name__ == \"__main__\":\n main()\n```"}}