Machine Learning-Driven Automated Offense and Defense: A State-Based Approach

    This article explains how machine learning and large language models can orchestrate automated security offense and defense through state-based workflows rather than rigid scripts. It covers three core technical pillars—stateful orchestration, tool-based capabilities, and closed-loop feedback—along with five typical scenarios such as asset mapping, vulnerability prioritization, anomaly detection, automated validation, and report generation. Readers will also find key engineering practices and common pitfalls for building auditable, permission-controlled, and sustainable automation.

    1. The Starting Point: Why Automated Offense and Defense Needs a “Map” Instead of a “Script”

    In security operations and adversarial engagements, automation has always been a core way to reduce cost and improve efficiency. However, most traditional automation relies on fixed rules: predefined decision branches, a fixed execution order, and hard-coded thresholds. This approach works well when the environment is stable and the target is simple. Once the environment becomes complex—with constantly changing asset distributions, widely varying protection policies, and dynamic attack surfaces—scripts quickly break down. As more rules are added and branches become entangled, the result is a “dead script” that is hard to maintain.

    Recent practice is shifting toward a different model: using a large language model as the core for reasoning and decision-making, treating traditional security tools as callable capabilities, and organizing both with a state map that can loop, branch, and roll back. Here, the “map” refers to a state-based orchestration framework: states carry context, nodes carry specific actions, and edges determine transition conditions. The model no longer follows a script step by step; instead, it chooses the next step based on the current state.

    It is important to emphasize that machine learning in offense and defense scenarios is not meant to replace existing detection engines. It fills the experience-heavy segment of “judgment—decision—orchestration.”

    2. Three Technical Pillars

    2.1 Stateful Orchestration: Making Processes Traceable

    The state is the single source of truth for the entire workflow. It typically includes target information, completed actions, intermediate conclusions, a to-do queue, and retry counts. Explicitly writing all intermediate outputs into the state brings three direct benefits: first, recoverability—the workflow can resume from the state after an interruption; second, auditability—every decision is documented; third, intervenability—humans can insert approvals at key nodes.

    A sample state definition is shown below:

    1. from typing import TypedDict, List, Dict
    2. class SecurityState(TypedDict):
    3. target: str # Target identifier
    4. facts: Dict[str, str] # Confirmed facts
    5. todos: List[str] # Pending actions
    6. findings: List[Dict] # Risk findings
    7. retries: Dict[str, int] # Retry count per action
    8. need_human: bool # Whether human confirmation is required

    2.2 Tool-Based Capabilities: Giving the Model Hands and Feet

    The model itself can only produce text; real actions depend on tools. In engineering practice, tool descriptions (name, purpose, parameter structure) are usually provided to the model, which then decides which tool to call and what parameters to pass. Common tool categories in security scenarios include asset discovery and port scanning, directory and interface enumeration, fingerprinting, vulnerability validation, log and traffic queries, and alert handling orchestration.

    The key constraint is that tools must perform parameter validation and permission scoping, exposing only the minimum capabilities required for the current task.

    1. def scan_ports(params: dict) -> dict:
    2. host = params.get("host", "")
    3. if not host or not is_in_scope(host):
    4. return {"error": "Target is out of authorized scope"}
    5. return {"host": host, "open": [22, 80, 443]}

    2.3 Closed-Loop Feedback: From a Single Output to Multi-Round Convergence

    The essence of offense and defense is iteration under information asymmetry. The model proposes a hypothesis, tools return observations, and the model refines the hypothesis until evidence is sufficient or an exit condition is triggered. To prevent infinite loops, three brakes are needed: a maximum number of rounds, duplicate action detection, and a confidence threshold.

    3. Typical Application Scenarios

    Scenario 1: Asset Mapping and Attack Surface Analysis

    After reading the target description, the model autonomously decomposes the task: first perform liveness detection, then identify ports and services, then infer fingerprints for non-standard ports, and finally aggregate everything into a structured asset inventory. Compared with fixed scripts, the advantage is that it can dynamically adjust depth based on detection results—diving deeper only when abnormal ports are found, avoiding ineffective scans.

    Scenario 2: Vulnerability Intelligence Correlation and Prioritization

    After matching the asset inventory against a vulnerability feature database, the model combines business importance, exposure, exploitation difficulty, and existing protections to output an explainable priority list. Here, machine learning mainly handles “multi-factor weighting and explanation generation” rather than replacing the vulnerability database itself.

    Scenario 3: Anomaly Detection in Traffic and Logs

    For high-dimensional traffic features, unsupervised methods (such as clustering and isolation-forest-style approaches) are suitable for discovering unknown anomalies, while supervised methods are suitable for classifying known attacks. A more robust practice is a two-layer structure: traditional rules and statistical engines handle high-confidence alerts, while the model performs secondary analysis and clustering consolidation on low-confidence, long-tail samples, significantly reducing alert noise.

    Scenario 4: Automated Validation and Low-Risk Handling Orchestration

    Within a clearly authorized scope, the model can orchestrate validation workflows: construct minimal validation requests, compare response differences, determine whether an issue truly exists, and generate reproduction steps and remediation suggestions. Actions such as blocking, isolation, and ticket dispatch should be set as nodes requiring human confirmation.

    Scenario 5: Report Generation and Knowledge Accumulation

    Structured findings are converted into readable reports, and the handling process is written back as searchable knowledge for reference in the next round of decisions, forming organization-level experience accumulation.

    4. Key Engineering Practices

    • Least privilege: tools are authorized at task granularity, and sensitive actions require secondary confirmation.
    • Full traceability: state snapshots, tool inputs and outputs, and model conclusions are stored in alignment for easy review.
    • Cost and latency: high-frequency simple judgments go through rules, and only complex judgments are handed to the model; repeated query results are cached.
    • Evaluation system: build a labeled historical sample set to track accuracy, false positive rate, average convergence rounds, and human intervention rate.
    • Security boundaries: all automated actions are limited to authorized assets and authorized time windows, with a one-click circuit breaker retained.
    • Portable deployment: after decoupling states and tools, the system can run on container platforms, use message queues for task distribution, achieve observability with logging and monitoring alerts, and use object storage for reports and snapshots.

    5. Common Pitfalls

    The first is treating the model as a scanner and expecting it to replace mature detection engines. The second is missing state design, making workflows impossible to recover or audit. The third is exposing tools too broadly, amplifying the risk of misoperation. The fourth is focusing only on the final answer while ignoring the explainability of intermediate reasoning. The fifth is lacking an evaluation baseline, making it impossible to tell whether optimization is truly effective.

    6. Conclusion

    The value of machine learning in automated offense and defense lies not in making processes “smarter” at bypassing constraints, but in organizing scattered tools and experience into a traceable, explainable, and auditable decision loop. With states at the center, tools as hands and feet, and feedback as the driver—combined with strict permission and evaluation systems—automated offense and defense can move from a demonstration to sustainable operations.