{"id":1402,"cve":"CVE-2024-41921","cve_url":"https:\/\/www.cvedetails.com\/cve\/CVE-2024-41921\/","cwe":"CWE-94","cwe_number":94,"cwe_url":"https:\/\/cwe.mitre.org\/data\/definitions\/94","cvss_score":7.8,"published":"2025-07-17","owasp":"A03 Injection","odc":"Checking","cdc":"Missing Check","category":"Input Validation and Sanitization","subcategory":"Command Injection","scope":"Local","impact":"Arbitrary Code Execution","summary":"ROS rostopic echo --filter allows code injection via unsanitized eval().","permalink":"https:\/\/netpack.pt\/vaitp\/vulnerability\/CVE-2024-41921\/","description":"A code injection vulnerability has been discovered in the Robot Operating System (ROS) 'rostopic' command-line tool, affecting ROS distributions Noetic Ninjemys and earlier. The vulnerability lies in the 'echo' verb, which allows a user to introspect a ROS topic and accepts a user-provided Python expression via the --filter option. This input is passed directly to the eval() function without sanitization, allowing a local user to craft and execute arbitrary code.","solution":"Upgrade the `ros-noetic-rostopic` package to version 1.16.0 or newer.","affected_component":"rostopic","fixed_by_upgrading":true,"vulnerable_code":"import sys\nimport os\n\ndef rostopic_echo_vulnerable(filter_expression):\n    \"\"\"\n    A simplified representation of the vulnerable logic in 'rostopic echo --filter'.\n    This function simulates the core behavior of processing a ROS message\n    against a user-provided filter expression.\n    \"\"\"\n    # In the actual tool, 'm' would be a ROS message object received from a\n    # topic subscription. Here, we create a mock dictionary to serve as the message.\n    m = {\n        'header': {\n            'seq': 101,\n            'stamp': '2024-01-01T00:00:00Z',\n            'frame_id': 'base_link'\n        },\n        'temperature': 25.5,\n        'active': True\n    }\n\n    # The context for eval() is prepared. The user's filter expression\n    # can access the message content via the variable 'm'.\n    evaluation_context = {'m': m}\n\n    # THE VULNERABLE LINE:\n    # The user-provided 'filter_expression' is passed directly to the eval()\n    # function without any sanitization. The expression is expected to return\n    # a boolean to decide if the message should be printed, but a malicious\n    # user can craft an expression that executes arbitrary system commands.\n    if eval(filter_expression, globals(), evaluation_context):\n        print(\"Message matched filter and would be displayed:\")\n        print(m)\n    else:\n        # In the case of code execution, the return value might be None or 0,\n        # leading to this branch being executed after the payload runs.\n        print(\"Message did not match filter.\")\n\n\nif __name__ == '__main__':\n    # This block simulates the command-line invocation of the tool.\n    # Example of legitimate use:\n    # python vulnerable_code.py \"m['temperature'] > 20.0\"\n    #\n    # Example of malicious use to execute code:\n    # python vulnerable_code.py \"__import__('os').system('echo VULNERABILITY DEMONSTRATED')\"\n\n    if len(sys.argv) < 2:\n        print(\"Usage: python <script_name>.py \\\"<filter_expression>\\\"\")\n        print(\"\\nDemonstrating with a malicious payload...\")\n        # A payload that is non-destructive and works on most OSes.\n        malicious_payload = \"__import__('os').system('echo CODE_EXECUTION_SUCCESSFUL')\"\n        filter_arg = malicious_payload\n    else:\n        filter_arg = sys.argv[1]\n\n    print(f\"\\n[*] Executing with filter: {filter_arg}\\n\" + \"-\"*30)\n    rostopic_echo_vulnerable(filter_arg)\n    print(\"-\"*30)","patched_code":"import ast\n\ndef safe_eval_filter(filter_expression, msg):\n    \"\"\"\n    Safely evaluates a filter expression against a message object.\n\n    This function mitigates CVE-2024-41921 by parsing the user-provided\n    expression into an Abstract Syntax Tree (AST) and validating that it\n    only contains a restricted, safe subset of Python's grammar before\n    evaluation. This prevents the execution of arbitrary code.\n\n    Args:\n        filter_expression (str): The user-provided Python expression.\n        msg (object): The ROS message instance to be evaluated against. The\n                      expression can refer to this object as 'm'.\n\n    Returns:\n        bool: The result of the expression.\n\n    Raises:\n        ValueError: If the expression contains disallowed constructs.\n    \"\"\"\n    if not filter_expression:\n        return True\n\n    # 1. Parse the expression into an AST. mode='eval' ensures it's an expression.\n    try:\n        tree = ast.parse(filter_expression, mode='eval')\n    except (SyntaxError, TypeError) as e:\n        raise ValueError(f\"Invalid filter expression: {e}\")\n\n    # 2. Define a whitelist of safe AST node types.\n    # This allows for comparisons, attribute access, boolean logic, and literals,\n    # but explicitly disallows calls, imports, comprehensions, etc.\n    allowed_node_types = {\n        ast.Expression,    # The top-level node\n        ast.Compare,       # Comparisons (e.g., m.data > 10)\n        ast.Attribute,     # Attribute access (e.g., m.data)\n        ast.Name,          # Variable names (e.g., 'm')\n        ast.Load,          # Context for loading variables\n        ast.Constant,      # Literals (Python 3.8+)\n        ast.BoolOp,        # Boolean operators (and, or)\n        ast.And,\n        ast.Or,\n        ast.UnaryOp,       # Unary operators (not)\n        ast.Not,\n        ast.BinOp,         # Binary operators (+, -, *, \/)\n        ast.Add, ast.Sub, ast.Mult, ast.Div,\n        \n        # For older Python compatibility (pre-3.8)\n        ast.NameConstant,  # True, False, None\n        ast.Num,           # Numbers\n        ast.Str,           # Strings\n    }\n\n    # 3. Walk the entire AST and validate every node against the whitelist.\n    for node in ast.walk(tree):\n        if type(node) not in allowed_node_types:\n            raise ValueError(\n                f\"Disallowed expression construct '{type(node).__name__}' found. \"\n                \"Execution of arbitrary code is blocked.\"\n            )\n        # 4. Additionally, prevent access to \"private\" or \"magic\" attributes.\n        if isinstance(node, ast.Attribute) and node.attr.startswith('_'):\n            raise ValueError(\n                \"Access to private or magic attributes (starting with '_') is not permitted.\"\n            )\n        # 5. Ensure the only allowed variable name is 'm'.\n        if isinstance(node, ast.Name) and node.id != 'm':\n            raise ValueError(f\"Unknown variable '{node.id}' found. Only 'm' is allowed.\")\n\n    # 6. If validation passes, compile and evaluate the expression in a\n    #    restricted environment.\n    #    The 'globals' dictionary is restricted to prevent access to built-ins.\n    #    The 'locals' dictionary only exposes the message object as 'm'.\n    code = compile(tree, '<string>', 'eval')\n    return eval(code, {\"__builtins__\": {}}, {'m': msg})","payload_needed":true,"payload":"`__import__('os').system('id')`","payload_status":"available","published_fix":[],"references":null}