VAITP Dataset

← Back to the dataset

CVE-2024-9880

Pandas `query` allows remote command execution via malicious queries (<= v2.2.2).

  • CVSS 8.4
  • CWE-94
  • Input Validation and Sanitization
  • Remote

A command injection vulnerability exists in the `pandas.DataFrame.query` function of pandas-dev/pandas versions up to and including v2.2.2. This vulnerability allows an attacker to execute arbitrary commands on the server by crafting a malicious query. The issue arises from the improper validation of user-supplied input in the `query` function when using the 'python' engine, leading to potential remote command execution.

CVSS base score
8.4
Published
2025-03-20
OWASP
A03 Injection
Orthogonal defect classification
Interface
Code defect classification
Incorrect Functionality
Category
Input Validation and Sanitization
Subcategory
Command Injection
Accessibility scope
Remote
Impact
Arbitrary Code Execution
Affected component
pandas
Fixed by upgrading
Yes

Solution

Upgrade to pandas version 2.2.3 or later.

Vulnerable code sample

import pandas as pd

def demonstrate_potential_command_injection(query_string):
  """
  Demonstrates a potential command injection vulnerability in pandas.DataFrame.query
  before CVE-2024-9880 was fixed.  This is a *simplified* representation and
  doesn't directly execute commands like the actual vulnerability but shows
  how unsanitized input could be passed to the query function with the 'python' engine.

  THIS CODE IS FOR DEMONSTRATION PURPOSES ONLY. DO NOT USE IT IN A PRODUCTION ENVIRONMENT.
  IT HIGHLIGHTS A VULNERABILITY THAT HAS BEEN FIXED.

  Args:
    query_string:  A string representing the query to be executed.  An attacker
                  could potentially inject malicious code into this string.
  """

  try:
    df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})

    # The vulnerable part is the query function using the 'python' engine
    # before proper sanitization was implemented.
    result = df.query(query_string, engine='python')  # Vulnerable line

    print("Query Result:\n", result)

  except Exception as e:
    print(f"An error occurred: {e}")


if __name__ == '__main__':
  #  Example of a potentially malicious query string.  A real exploit
  #  would likely be far more complex.  This just illustrates the concept
  #  of injecting code into the query.
  malicious_query = "A > 1 and __import__('os').system('echo PWNED')"

  # This calls the function with the malicious query string. DO NOT RUN THIS
  # IN AN ENVIRONMENT WHERE IT COULD CAUSE HARM. It's for demonstration
  # of a *potential* vulnerability.

  print("Demonstrating potential vulnerability (CVE-2024-9880):")
  demonstrate_potential_command_injection(malicious_query)

  print("\nImportant: This example is simplified and doesn't perfectly replicate the actual CVE.\nIt illustrates the general concept of how unsanitized input to the query function\nwith the 'python' engine could lead to problems.")

Patched code sample

import pandas as pd
import ast
import subprocess

def safe_query(df, query_string):
    """
    Safely queries a Pandas DataFrame, mitigating command injection vulnerabilities.

    Args:
        df: The Pandas DataFrame to query.
        query_string: The query string.

    Returns:
        A new Pandas DataFrame representing the result of the query, or None if the query is unsafe.
    """

    # 1. Whitelist Allowed Functions and Attributes (AST-based)
    allowed_functions = {'abs', 'min', 'max', 'sum', 'len', 'mean'}  #  Example, extend as needed
    allowed_attributes = set(df.columns)  # Only column names allowed

    try:
        # Parse the query string into an Abstract Syntax Tree (AST)
        tree = ast.parse(query_string)

        # Walk through the AST to check for disallowed function calls or attributes
        for node in ast.walk(tree):
            if isinstance(node, ast.Call):
                if isinstance(node.func, ast.Name):
                    function_name = node.func.id
                    if function_name not in allowed_functions:
                        print(f"Error: Disallowed function '{function_name}' in query.")
                        return None  # Reject the query
            elif isinstance(node, ast.Attribute):
                if isinstance(node.value, ast.Name): # Checking if attribute belongs to df object
                    attribute_name = node.attr
                    if node.value.id != 'df' or attribute_name not in allowed_attributes:
                        print(f"Error: Disallowed attribute '{attribute_name}' in query.")
                        return None  # Reject the query
            elif isinstance(node, ast.Subscript):
                if isinstance(node.value, ast.Name) and node.value.id == 'df':  #Prevent df['os.system("evil")']
                    if isinstance(node.slice, ast.Constant):
                        if not isinstance(node.slice.value, str):
                            print(f"Error: Disallowed index type in query")
                            return None
                    elif isinstance(node.slice, ast.Slice) and all(isinstance(x, ast.Constant) or x is None for x in [node.slice.start, node.slice.stop, node.slice.step]):
                        pass
                    else:
                        print(f"Error: Complex slicing not allowed in safe query.")
                        return None
            elif isinstance(node, ast.Import) or isinstance(node, ast.ImportFrom):
                print("Error: Imports are not allowed in safe queries.")
                return None

            # Add more checks here to cover other potentially dangerous AST node types.

        # 2. Use a Safe Querying Method (e.g., numexpr or a custom evaluation)
        try:
            result = df.query(query_string, engine='numexpr') # Force the usage of numexpr if available
            return result
        except Exception as e:
            print(f"Query execution error: {e}")
            return None

    except SyntaxError as e:
        print(f"Syntax error in query: {e}")
        return None
    except Exception as e:
        print(f"Error during query validation: {e}")
        return None


if __name__ == '__main__':
    # Example usage
    data = {'col1': [1, 2, 3, 4, 5],
            'col2': [6, 7, 8, 9, 10]}
    df = pd.DataFrame(data)

    # Safe query
    safe_result = safe_query(df, "col1 > 2 and col2 < 9")
    if safe_result is not None:
        print("Safe Query Result:\n", safe_result)

    # Attempt to inject code (this will be blocked)
    unsafe_query = "col1 > 2 and df['col1'].abs().sum() < 15"
    unsafe_result = safe_query(df, unsafe_query)  # Example of using an allowed function
    if unsafe_result is not None:
        print("Unsafe Query Result:\n", unsafe_result)
    else:
        print("Unsafe query was blocked.")
    
    # Attempt to use an attribute that is not allowed
    unsafe_query2 = "col1 > 2 and df.index.name == 'evil'"
    unsafe_result2 = safe_query(df, unsafe_query2)  # Example of using an allowed function
    if unsafe_result2 is not None:
        print("Unsafe Query Result:\n", unsafe_result2)
    else:
        print("Unsafe query 2 was blocked.")

    #Example of blocked import.
    unsafe_query3 = "import os; col1 > 2"
    unsafe_result3 = safe_query(df, unsafe_query3)
    if unsafe_result3 is not None:
        print("Unsafe Query Result:\n", unsafe_result3)
    else:
        print("Unsafe query 3 was blocked.")

Payload

'`__import__("os").system("touch /tmp/pwned")`'

Cite this entry

@misc{vaitp:cve20249880,
  title        = {{Pandas `query` allows remote command execution via malicious queries (<= v2.2.2).
}},
  author       = {Bogaerts, Fr\'ed\'eric and Ivaki, Naghmeh and Fonseca, Jos\'e},
  year         = {2025},
  note         = {VAITP Python Vulnerability Dataset, entry CVE-2024-9880},
  howpublished = {\url{https://netpack.pt/vaitp/vulnerability/CVE-2024-9880/}}
}
Introducing the "VAITP dataset": a specialized repository of Python vulnerabilities and patches, meticulously compiled for the use of the security research community. As Python's prominence grows, understanding and addressing potential security vulnerabilities become crucial. Crafted by and for the cybersecurity community, this dataset offers a valuable resource for researchers, analysts, and developers to analyze and mitigate the security risks associated with Python. Through the comprehensive exploration of vulnerabilities and corresponding patches, the VAITP dataset fosters a safer and more resilient Python ecosystem, encouraging collaborative advancements in programming security.

The supreme art of war is to subdue the enemy without fighting.

Sun Tzu – “The Art of War”

:: Shaping the future through research and ingenuity ::