{"id":1342,"cve":"CVE-2025-46725","cve_url":"https:\/\/www.cvedetails.com\/cve\/CVE-2025-46725\/","cwe":"CWE-94","cwe_number":94,"cwe_url":"https:\/\/cwe.mitre.org\/data\/definitions\/94","cvss_score":8.1,"published":"2025-05-20","owasp":"A03 Injection","odc":"Interface","cdc":"Incorrect Functionality","category":"Input Validation and Sanitization","subcategory":"Insecure Parsing or Deserialization","scope":"Remote","impact":"Arbitrary Code Execution","summary":"Langroid uses pandas eval(), allowing remote code execution via crafted queries.","permalink":"https:\/\/netpack.pt\/vaitp\/vulnerability\/CVE-2025-46725\/","description":"Langroid is a Python framework to build large language model (LLM)-powered applications. Prior to version 0.53.15, `LanceDocChatAgent` uses pandas eval() through `compute_from_docs()`. As a result, an attacker may be able to make the agent run malicious commands through `QueryPlan.dataframe_calc]`) compromising the host system. Langroid 0.53.15 sanitizes input to the affected function by default to tackle the most common attack vectors, and added several warnings about the risky behavior in the project documentation.","solution":"Upgrade to Langroid version 0.53.15 or later.","affected_component":"Langroid","fixed_by_upgrading":true,"vulnerable_code":"import pandas as pd\n\nclass QueryPlan:\n    def __init__(self, dataframe_calc):\n        \"\"\"Vulnerable function that demonstrates the security issue.\"\"\"\n        self.dataframe_calc = dataframe_calc\n\n        class LanceDocChatAgent:\n            def compute_from_docs(self, query_plan):\n                \"\"\"\n                Computes results based on a query plan using pandas eval.\n                POTENTIALLY UNSAFE: Uses pandas eval which can execute arbitrary code.\n                \"\"\"\n                try:\n            # Simulate loading data into a pandas DataFrame\n            # In a real application, this would load data from documents.\n                    data = {'col1': [1, 2, 3], 'col2': [4, 5, 6]}\n                    df = pd.DataFrame(data)\n\n            # Execute the calculation specified in the query plan using pandas eval\n                    result = df.eval(query_plan.dataframe_calc)\n                    return result\n                    except Exception as e:\n                        return f\"Error during calculation: {e}\"\n\n# Example usage (VULNERABLE)\n                        if __name__ == '__main__':\n                            agent = LanceDocChatAgent()\n\n    # Malicious query plan injecting code execution\n                            malicious_calc = \"__import__('os').system('echo EXPLOITED > \/tmp\/pwned.txt')\"\n                            malicious_plan = QueryPlan(dataframe_calc=malicious_calc)\n                            result = agent.compute_from_docs(malicious_plan)\n                            print(f\"Result: {result}\")  # Print the result\n    # After execution, a file named 'pwned.txt' containing 'EXPLOITED' will be created in \/tmp if the execution was successful.","patched_code":"import pandas as pd\nimport re\n\ndef safe_eval(expression, local_dict=None, global_dict=None):\n    \"\"\"\n    Safely evaluates a mathematical expression.  Restricts access to\n    potentially dangerous functions and attributes.  Allows basic\n    arithmetic, comparison operators, and explicitly defined variables.\n\n    Args:\n        expression (str): The expression to evaluate.\n        local_dict (dict, optional): Local variables to use in the evaluation. Defaults to None.\n        global_dict (dict, optional): Global variables to use in the evaluation. Defaults to None.\n\n    Returns:\n        The result of the evaluation, or None if the expression is unsafe.\n    \"\"\"\n\n    # Whitelist of allowed characters and functions\n    allowed_chars = r\"[0-9+\\-*\/().%<>=!&|\\s,:a-zA-Z_]\"\n    allowed_functions = ['abs', 'round', 'min', 'max', 'sum', 'len'] # add more as needed\n\n    # Simple check for potentially malicious code injections\n    if not re.match(f\"^[{allowed_chars}]*$\", expression):\n        print(\"Unsafe characters detected in expression.\")\n        return None\n\n    # Check for use of potentially dangerous attributes and functions.\n    # This is a more comprehensive check than just character whitelisting.\n    blacklist = [\n        \"_\",  # Avoid access to hidden attributes and methods\n        \"import\",\n        \"exec\",\n        \"eval\",\n        \"compile\",\n        \"getattr\",\n        \"setattr\",\n        \"deleteattr\",\n        \"globals\",\n        \"locals\",\n        \"vars\",\n        \"open\",\n        \"read\",\n        \"write\",\n        \"system\",\n        \"os\",\n        \"subprocess\",\n        \"__\", # double underscores\n    ]\n\n    for item in blacklist:\n        if item in expression.lower():  # Lowercase for case-insensitive matching\n            print(f\"Blacklisted keyword '{item}' detected in expression.\")\n            return None\n    \n    # Check if potentially malicious functions are called\n    pattern = r'\\b(' + '|'.join(allowed_functions) + r')\\b'\n    function_calls = re.findall(pattern, expression) # list of all function calls\n    \n    # Check for usage of pandas methods in calculation\n    pandas_method_blacklist = [\n        \"apply\",\n        \"map\",\n        \"pipe\",\n        \"aggregate\",\n        \"transform\",\n        \"groupby\",\n        \"rolling\",\n        \"expanding\",\n        \"shift\",\n        \"diff\",\n        \"pct_change\"\n    ]\n\n    for item in pandas_method_blacklist:\n        if item in expression.lower():\n            print(f\"Potentially dangerous pandas method '{item}' detected.\")\n            return None\n\n    try:\n        # Create a safe namespace by limiting builtins\n        safe_globals = {k: __builtins__.__dict__[k] for k in allowed_functions if k in __builtins__.__dict__}\n\n        # Add specified global variables, if provided\n        if global_dict:\n            safe_globals.update(global_dict)\n\n        # Evaluate the expression with the safe namespace\n        result = eval(expression, safe_globals, local_dict)\n        return result\n    except (SyntaxError, NameError, TypeError, ZeroDivisionError) as e:\n        print(f\"Error evaluating expression: {e}\")\n        return None\n    except Exception as e:\n        print(f\"An unexpected error occurred: {e}\")\n        return None\n\ndef compute_from_docs(df, calc_string):\n    \"\"\"\n    Computes a new column in the DataFrame based on a safe calculation string.\n\n    Args:\n        df (pd.DataFrame): The DataFrame to operate on.\n        calc_string (str): The calculation string to apply.\n\n    Returns:\n        pd.DataFrame: The DataFrame with the new column, or the original DataFrame if the calculation fails.\n    \"\"\"\n    \n    #Sanitize input calc_string using safe_eval function\n    result = safe_eval(calc_string)\n    if result is None:\n        print(\"The calc string is not safe. Returning original DataFrame\")\n        return df\n\n    try:\n        df['new_column'] = result\n        return df\n    except Exception as e:\n        print(f\"Error during calculation: {e}\")\n        return df\n\n\nif __name__ == '__main__':\n    # Example usage (safe):\n    data = {'col1': [1, 2, 3], 'col2': [4, 5, 6]}\n    df = pd.DataFrame(data)\n\n    # Simulate user-provided calculation string\n    safe_calculation = \"df['col1'] + df['col2']\"\n    df_safe = compute_from_docs(df.copy(), safe_calculation)\n    print(\"Safe calculation result:\")\n    print(df_safe)\n\n    # Example of a blocked malicious calculation:\n    malicious_calculation = \"__import__('os').system('ls -l')\"\n    df_unsafe = compute_from_docs(df.copy(), malicious_calculation)\n    print(\"\\nUnsafe calculation attempt:\")\n    print(df_unsafe)\n\n    malicious_calculation_2 = \"df['col1'].apply(lambda x: x**2)\"\n    df_unsafe_2 = compute_from_docs(df.copy(), malicious_calculation_2)\n    print(\"\\nUnsafe calculation attempt 2:\")\n    print(df_unsafe_2)\n\n    # A calculation that requires usage of pandas functions\n    # df['col1'].mean() will cause an issue when applying the fix\n    # due to the restriction of pandas methods.\n    pandas_calculation = \"df['col1'].mean()\"\n    df_pandas_calculation = compute_from_docs(df.copy(), pandas_calculation)\n    print(\"\\nPandas function calculation attempt:\")\n    print(df_pandas_calculation)\n\n    complex_calculation = \"(df['col1'] + df['col2']) * abs(min(df['col1']))\"\n    df_complex = compute_from_docs(df.copy(), complex_calculation)\n    print(\"\\nComplex calculation attempt:\")\n    print(df_complex)","payload_needed":true,"payload":"```python\n__import__('os').system('touch \/tmp\/pwned')\n```","payload_status":"available","published_fix":[{"repository":"langroid\/langroid","commit_url":"https:\/\/github.com\/langroid\/langroid\/commit\/0d9e4a7bb3ae2eef8d38f2e970ff916599a2b2a6","commit_subject":"fixes to code-injection mitigation PR #841 (#850)","units":[{"file":"langroid\/agent\/special\/table_chat_agent.py","function":null},{"file":"langroid\/agent\/special\/table_chat_agent.py","function":"TableChatAgent.pandas_eval"},{"file":"langroid\/utils\/pandas_utils.py","function":null},{"file":"langroid\/vector_store\/base.py","function":null},{"file":"langroid\/vector_store\/base.py","function":"VectorStore.compute_from_docs"}]}],"references":null}