Typing stubs for defusedxml

0.7.0.20260408 · active · verified Fri Apr 10

types-defusedxml provides type hints for the defusedxml library, which offers protection against XML-related security vulnerabilities like XML bombs (Billion Laughs, Quadratic Blowup) and external entity attacks in Python's standard library XML modules. It is part of the typeshed project and allows type checkers to analyze code using defusedxml for correctness. This package ensures compatibility with defusedxml==0.7.* and is regularly updated.

Warnings

Install

Imports

Quickstart

Demonstrates how to use `defusedxml.ElementTree.fromstring` to parse XML data securely, including handling potential XML entity expansion attacks. The `types-defusedxml` package provides the necessary type hints for `defusedxml` components, allowing static analysis tools to verify type correctness and anticipate exceptions like `EntitiesForbidden`.

import defusedxml.ElementTree as ET
from typing import Dict, Any

xml_data_safe = "<root><item>safe_data</item></root>"
xml_data_malicious = """
<!DOCTYPE foo [
<!ELEMENT foo ANY >
<!ENTITY xxe SYSTEM \"file:///non_existent_path\" >
]>
<foo>&xxe;</foo>
"""

def parse_xml_safely(xml_string: str) -> Dict[str, Any]:
    try:
        # types-defusedxml provides type hints for ET.fromstring
        root = ET.fromstring(xml_string)
        result = {child.tag: child.text for child in root}
        print(f"Successfully parsed: {result}")
        return result
    except ET.EntitiesForbidden as e:
        print(f"Caught an XML entity expansion attempt: {e}")
        return {"error": "Entities Forbidden"}
    except ET.ParseError as e:
        print(f"Caught a general XML parsing error: {e}")
        return {"error": "Parse Error"}

# Example usage with safe data
parse_xml_safely(xml_data_safe)

# Example usage with malicious data (XXE attempt) 
# This should be blocked by defusedxml, with stubs informing type checkers 
# about the EntitiesForbidden exception.
parse_xml_safely(xml_data_malicious)

view raw JSON →