A context management method for penetration testing, a computer device and a storage medium
Patent Information
- Application Number
- CN202611476805.2
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2026-09-22
- Publication Date
- 2026-10-30
AI Technical Summary
[0004]本申请实施例的目的是提供一种渗透测试的上下文管理方法、计算机设备及存储介质,以解决失败分支累积导致的上下文腐烂与决策质量退化问题
[0009]在本申请实施例中,通过以分支为基本压缩单元对失败分支进行结构化摘要,在保留侦查线索价值的同时大幅缩减上下文占用;通过外部存储模块持久化保存原始输出并配合按需检索机制,实现了渐进式信息披露,使智能体在常态下仅需阅读精简摘要即可保持全局感知,在需要时又能精确还原历史原始输出进行细粒度分析,从而在上下文占用与线索保留之间取得了有效平衡。
Smart Images

Figure CN123013123A_ABST
Abstract
Description
Technical Field
[0001] This application belongs to the field of artificial intelligence technology, specifically relating to a penetration testing context management method, computer equipment, and storage medium. Background Technology
[0002] Large-model-driven automated penetration testing agents have made significant progress in recent years, capable of autonomously executing multi-stage attack tasks such as information reconnaissance, vulnerability exploitation, privilege escalation, and lateral movement. However, in long-duration, multi-stage penetration testing scenarios, agents face a key bottleneck: the accumulation of failed branches leads to context decay and a degradation in decision-making quality.
[0003] Specifically, there are three main problems. First, the accumulation of failed attempts leads to context bloat and the burying of critical information. During penetration testing, agents need to perform numerous trial-and-error operations, such as directory brute-force, port scanning, and vulnerability exploitation attempts. These failed branches are necessary exploratory behaviors in the short term, but after long-term accumulation, they quickly fill the context window of the large model. More seriously, large language models suffer from the "Lost in the Middle" phenomenon. When relevant information is located in the middle of a long context, the model's information recall accuracy drops significantly, and early reconnaissance results are often buried in the middle area of the context and cannot be effectively utilized by the agent. Second, there is a deep contradiction between the value of clues and information density in failed attempts. Although failed attempts themselves do not directly lead to successful attacks, their output often contains reconnaissance clues that are crucial for subsequent decisions. For example, a failed port connection can confirm firewall filtering rules, and an error echo indicating a missing dependency can reveal the specific version information of the target environment. However, existing context management methods face a dilemma: excessively large compression granularity leads to the loss of clues, while excessively small compression granularity leads to context bloat. Third, penetration testing, as a long-term task, has a natural branching exploration structure. At each stage, the agent usually needs to try multiple different attack directions starting from the same anchor point. Each direction constitutes an independent branch, and only a few branches can lead to the next anchor point. This puts forward the requirement for context management to be able to perceive the branching structure of penetration testing and extract and retain information by branch unit. Summary of the Invention
[0004] The purpose of this application is to provide a penetration testing context management method, computer device, and storage medium to solve the problem of context decay and decision quality degradation caused by the accumulation of failed branches.
[0005] To solve the above-mentioned technical problems, this application is implemented as follows: In a first aspect, embodiments of this application provide a context management method for penetration testing, the method comprising: In the main loop of penetration testing, a large model is invoked to make inference decisions and output the next action type, which includes executing penetration testing tools or invoking context management tools. When the action type is to execute a penetration testing tool, the corresponding penetration testing tool is invoked to perform operations on the target system and capture the output. At the same time, the output is stored in the external storage module using the current branch identifier and the command string as a composite key. When the action type is to invoke a context management tool, the corresponding context management operation is performed according to the type of the context management tool; The context management tool includes a failed branch summary tool. When the failed branch summary tool is invoked, all original commands and output records under the current branch are integrated into a structured summary containing a list of original commands, a list of key findings, and a branch overview. The structured summary replaces all the original context records of the current branch.
[0006] In a second aspect, embodiments of this application provide a computer device including a processor, a memory, and a program or instructions stored in the memory and executable on the processor, wherein the program or instructions, when executed by the processor, implement the steps of the method described in the first aspect.
[0007] Thirdly, embodiments of this application provide a computer-readable storage medium on which a program or instructions are stored, which, when executed by a processor, implement the steps of the method described in the first aspect.
[0008] Fourthly, embodiments of this application also provide a computer program product, including a computer program that, when executed by a processor, implements the steps of the method described in the first aspect.
[0009] In this embodiment, by using branches as the basic compression unit to perform structured summaries on failed branches, the value of investigative clues is preserved while significantly reducing context usage. By persistently saving the original output through an external storage module and cooperating with an on-demand retrieval mechanism, progressive information disclosure is achieved. This allows the agent to maintain global awareness by simply reading the concise summary under normal circumstances, and to accurately restore the original historical output for fine-grained analysis when needed, thus achieving an effective balance between context usage and clue preservation. Attached Figure Description
[0010] Figure 1 This is a flowchart illustrating a penetration testing context management method provided in some embodiments of this application; Figure 2 This is a flowchart illustrating a specific embodiment of the penetration testing context management method provided in this application; Figure 3 These are internal structural diagrams of a computer device provided in some embodiments of this application. Detailed Implementation
[0011] The technical solutions of the embodiments of this application will be clearly and completely described below with reference to the accompanying drawings. Obviously, the described embodiments are only some embodiments of this application, not all embodiments. Based on the embodiments of this application, all other embodiments obtained by those skilled in the art without creative effort are within the scope of protection of this application.
[0012] The terms "first," "second," etc., used in the specification and claims of this application are used to distinguish similar objects and not to describe a specific order or sequence. It should be understood that such use of data can be interchanged where appropriate so that embodiments of this application can be implemented in orders other than those illustrated or described herein. Furthermore, in the specification and claims, "and / or" indicates at least one of the connected objects, and the character " / " generally indicates that the preceding and following objects are in an "or" relationship.
[0013] In one exemplary embodiment, this application proposes a context management method for penetration testing. The context management method for penetration testing provided by this application will be described in detail below with reference to the accompanying drawings, through specific embodiments and application scenarios. This penetration testing context management method is applied to a device with an intelligent agent deployed. The device with the intelligent agent can be a server, workstation, personal computer, or other device with computing and network access capabilities. The intelligent agent is a software entity with a large language model as its decision engine, capable of autonomously executing multi-stage penetration testing tasks such as information reconnaissance, vulnerability exploitation, privilege escalation, and lateral movement.
[0014] Reference Figure 1 The method includes steps 102-106. Wherein: Step 102: In the main loop of the penetration test, the large model is invoked to make inference decisions and output the next action type, which includes executing the penetration test tool or invoking the context management tool.
[0015] It should be noted that the embodiments of this application involve two different types of tools: First, penetration testing tools that perform attack operations on the target system, including but not limited to nmap port scanning tools, gobuster directory brute-force tools, sqlmap injection tools, hydra password brute-force tools, and the Metasploit vulnerability exploitation framework; Second, context management tools that perform management operations on the agent's own context, including but not limited to failure branch digest tools, anchor point setting tools, and raw output retrieval tools, where the agent operates its own internal memory structure. The target system is the object of the penetration test.
[0016] The large model can be a large language model with reasoning capabilities, such as the GPT series, LLaMA series, or Qwen series. In each round of the loop, the agent incorporates both types of tools into the decision-making framework, outputs the next action type, and the testing system distributes the action type to the corresponding tool for execution.
[0017] Step 104: When the action type is to execute a penetration testing tool, the corresponding penetration testing tool is invoked to perform operations on the target system and capture the output. At the same time, the output is stored in the external storage module using the current branch identifier and the command string as a composite key.
[0018] Step 106: When the action type is to invoke a context management tool, perform the corresponding context management operation according to the type of the context management tool.
[0019] The context management tool includes a failed branch summary tool. When the failed branch summary tool is invoked, all original commands and output records under the current branch are integrated into a structured summary containing a list of original commands, a list of key findings, and a branch overview. The structured summary replaces all the original context records of the current branch.
[0020] Here is an example of a structured summary: [FAILED BRANCH br_3] under Anchor A (www-data@192.168.1.100) Original command list: "curl -X POST http: / / 192.168.1.100 / upload.php -F "file=@shell.php""; "wget --post-file=shell.php http: / / 192.168.1.100 / upload.php"; "python3 -c "import requests; r=requests.post('http: / / 192.168.1.100 / upload.php', files={'file':open('shell.php','rb')}); print(r.text)"";"curl -XPOST http: / / 192.168.1.100 / upload.php -F "file=@shell.jpg" -H "Content-Type:multipart / form-data"".
[0021] Key findings: The upload interface is http: / / 192.168.1.100 / upload.php; MIME type validation rules only allow image / jpeg and image / png types; file extension validation prohibits .php extensions, and even if the MIME type is forged, it cannot be bypassed; uploaded files are stored in / uploads / ; the backend is implemented using PHP.
[0022] Branch Overview: This branch starts from anchor point A and aims to upload a WebShell via the / upload.php interface. Four upload methods were tested: direct curl upload, curl MIME type spoofing, wget upload, and Python script upload. Test results show that the target service verifies both MIME type and file extension; only image formats are allowed by MIME type, and the .php extension is prohibited. The final attempt successfully uploaded a file named shell.jpg, but the response only returned the storage path and not session information, confirming that this interface cannot directly obtain WebShell privileges and requires further exploitation using file inclusion vulnerabilities or other methods. Based on these results, it is recommended to check the executable permissions of the / uploads directory or look for file inclusion entry points.
[0023] Repeat steps 102-106 until the termination condition is met.
[0024] This embodiment clearly distinguishes between penetration testing tools and context management tools, enabling the agent to schedule both types of tools with a unified action type decision framework. Penetration testing tools perform attack operations on the target system, while context management tools perform management operations on the agent's own context. This avoids conceptual confusion and unclear technical characteristics caused by mixing two different types of tools together.
[0025] In some embodiments, the context management tool further includes an anchor point setting tool and a raw output retrieval tool; when the action type is to call the anchor point setting tool, a new anchor point is declared and the anchor point record is appended to the context window, while the current branch identifier is updated to open a new exploration branch; when the action type is to call the raw output retrieval tool, the corresponding raw standard output and standard error output are accurately matched from the external storage module using the branch identifier and command string as composite keys.
[0026] Specifically, the context management tool includes at least three core tools: a failed branch summarization tool (tool name and parameters are summarize_failed_branch(anchor_id, branch_id, critical_commands, key_findings, branch_summary)), an anchor setting tool (tool name and parameters are attach_anchor(anchor_id, description, branch_id)), and a raw output retrieval tool (tool name and parameters are get_output(branch_id, command)).
[0027] Among them, the Failed Branch Summarization Tool is used to compress failed branches with no further exploration value into structured summaries; the Anchor Point Setting Tool is used to declare new anchor points when the agent makes deterministic progress; and the Raw Output Retrieval Tool is used to retrieve historical raw outputs from external storage on demand. All three tools perform management operations on the agent's own context, and the object of processing is the context itself, which differs from penetration testing tools that are oriented towards the target system in terms of the object of operation, processing target, and execution effect.
[0028] This embodiment enables intelligent agents to autonomously decide to call different context management tools based on the real-time situation of penetration testing through the unified design and scheduling of context management tools, thereby achieving adaptive context management.
[0029] In some embodiments, the triggering method for invoking the failed branch summarization tool includes at least one of the following: Autonomous triggering by the agent: When the agent perceives that the current attack direction is continuously blocked through multiple attempts, the tool output repeatedly indicates the same error type, or no new clues are generated after multiple attempts, the agent autonomously decides to output the action type of calling the failure branch summary tool; System forced triggering: When the number of commands continuously executed by the agent under the current branch reaches a preset threshold and no deterministic progress is made, the test system automatically triggers the call to the failure branch summary tool.
[0030] Specifically, the criteria for autonomously triggering judgments by the agent include, but are not limited to: N consecutive commands under the current branch all display the same error type (such as connection timeout, access denied, authentication failure, etc.); M consecutive commands do not generate any new port, service, path, or vulnerability information; and the action type output by the large model in several consecutive rounds of inference is the same as repeatedly trying the same type of operation. Here, N and M are positive integers, which can be set by default by the testing system or configured by the user.
[0031] The preset threshold for forced triggering by the system can be configured according to the complexity of the target system, network environment, and task requirements. For example, it can be set to reach 5, 10, or 20 consecutive failed commands. In actual deployment, the trigger threshold for the number of commands can be adjusted according to factors such as the complexity of the target system, the characteristics of the agent, and the task scenario. Alternatively, the percentage of failed commands or the number of consecutive rounds without new information can be used as the judgment indicator.
[0032] This embodiment employs a dual triggering mechanism that combines agent-driven autonomous triggering with system-forced triggering. This leverages the semantic understanding and situational awareness capabilities of the large model to make compressed decision-making flexible, while also using a fallback mechanism to avoid the risk of failed branches remaining in the context for an extended period due to model forgetting or decision-making errors.
[0033] In some embodiments, the priority of autonomous triggering by the intelligent agent is higher than the priority of forced triggering by the system.
[0034] In practice, agent-initiated actions take precedence over system-forced actions. When an agent determines that the current branch has no further exploration value before the threshold is reached, compression can be triggered in advance to save context space. When an agent fails to perceive the situation in time due to context decay or decision-making errors, the testing system will force execution when the threshold is reached to ensure that the context size is always within a controllable range.
[0035] This embodiment sets the priority relationship of the triggering method so that the compression operation can be performed at the optimal time, while retaining the test system as a backup, thus balancing efficiency and reliability.
[0036] In some embodiments, generating the original command list includes: Traverse all executed commands in the current branch and perform deduplication to obtain the original command list. For the same command string, retain the first and last execution records. For commands with iterative characteristics, additionally mark the total number of iterations.
[0037] Generate the list of key findings, including: The large model extracts valuable investigative clues from the context corresponding to the current branch to obtain the list of key findings.
[0038] Generate the branch overview, including: The large model integrates the exploration objective, execution process, and final result of the current branch to generate a natural language description as an overview of the branch. The natural language description is used to summarize the complete exploration process and the reasons for failure.
[0039] Specifically, the generation of the original command list is accomplished through hard-coded rules, without relying on the participation of a large model. The specific rules for deduplication are as follows: if multiple identical command strings exist, only the records of the first and last executions are retained, and the execution count is marked; for commands with obvious iterative characteristics, such as directory brute-force and password brute-force, the total number of iterations is additionally marked.
[0040] The list of key findings is extracted from the context information of the current branch by the large model, and its content must cover at least one of the following types: open port numbers and service versions, accessible directory paths and access control status, vulnerability fingerprints, system permission boundary information, and configuration information exposed in error echoes.
[0041] Specifically, the key findings list covers valuable reconnaissance clues that may arise at each stage of the penetration testing process. Open port numbers and service version information provide a basis for selecting attack directions; accessible directory paths and access control status information help the agent identify potential attack surfaces; vulnerability fingerprint information provides a direct reference for subsequent vulnerability exploitation; system permission boundary information helps the agent determine the current permission level and possible privilege escalation paths; and configuration information exposed in error echoes helps the agent understand the target system's technology stack and environmental characteristics.
[0042] This embodiment ensures that all valuable investigative clues are systematically extracted and preserved during the summary compression process by clearly defining the content scope of the key discovery list, thereby improving the information density and practical value of the compressed context.
[0043] The branch overview is generated by the larger model in a coherent narrative, describing the complete process of the branch starting from the anchor point, the directions tried, the problems encountered, and why it ultimately failed.
[0044] This embodiment compresses the original context of a failed branch into a high-information-density summary using a three-element structured summary, which significantly reduces context usage while preserving key investigative clues and a complete exploration path.
[0045] In some embodiments, the format of the failed branch summary is not limited to the three-element structure. Extended fields such as recommended alternatives, similar success stories, or next-step suggestions can be added as needed, as long as the format maintains structure, readability, and information density.
[0046] In practice, the addition of extended fields can be automatically generated by the large model based on the exploration results of the current branch. For example, when the agent discovers a potentially valuable path in a failed branch that cannot be directly utilized, a "Recommended Alternative Solution" field can be added to the summary, recording: "It is recommended to try a variant attack based on this path in the future." When adding a "Similar Successful Case Reference" field, the large model can retrieve similar cases from historically successful branch records based on the exploration characteristics of the current branch, providing a reference for subsequent decisions. When adding a "Next Step Suggestion" field, the large model combines the reasons for the failure of the current branch with existing key findings to provide specific suggestions for subsequent exploration.
[0047] This embodiment provides flexible summary format extensions and storage method alternatives, enabling it to adapt to penetration testing scenarios of varying scales and complexities, thus improving the versatility and scalability of the solution.
[0048] In some embodiments, after invoking the corresponding penetration testing tool to perform operations on the target system and capturing the output, the method further includes: determining whether deterministic progress has been achieved based on the tool execution result; if deterministic progress has been achieved, outputting the action type of invoking the anchor setting tool; wherein, the deterministic progress includes at least one of the following situations: obtaining new Shell access permissions, obtaining valid identity credentials, verifying the exploitability of the vulnerability and successfully executing proof-of-concept code, confirming a new live host or accessible internal service, completing privilege escalation or lateral movement.
[0049] Specifically, deterministic progress refers to an irreversible security posture breakthrough achieved by an agent during penetration testing. This includes: gaining new shell access, meaning the agent has acquired command-line or graphical interface control over the target system; obtaining valid identity credentials, including username and password combinations, API keys, tokens, and other authentication credentials; verifying vulnerability exploitability, requiring not only confirmation of the vulnerability's existence but also successful execution of proof-of-concept code to demonstrate its exploitability; confirming new live hosts or accessible internal services through network scanning and service probing; privilege escalation, which refers to acquiring higher privileges from lower-privilege accounts; and lateral movement, which refers to expanding control from currently controlled hosts to other hosts on the network.
[0050] When a deterministic progress is made, the agent will invoke the anchor point setting tool as the output for the next action type, declare a new anchor point, and update the branch identifier.
[0051] This embodiment incorporates the determination results of deterministic progress into the action type decision framework, enabling the agent to autonomously decide to invoke the anchor point setting tool when a security breakthrough is achieved, thus ensuring the orderly recording of the penetration testing process.
[0052] In some embodiments, declaring a new anchor point and appending the anchor point record to the context window includes: declaring a new anchor point and generating an anchor point record, the anchor point record including a unique anchor point identifier, the branch identifier to which it belongs at the time of establishment, a natural language state description of the anchor point, and an establishment timestamp; and permanently appending the anchor point record to the context window without compression.
[0053] Specifically, the unique identifier of an anchor point can be in an incremental numbering format or a UUID format, used to uniquely index the anchor point within the context; the branch identifier to which the anchor point was established records which branch it originated from, facilitating subsequent tracing of the complete penetration test path; the natural language state description is generated by the agent when declaring the anchor point, used to summarize the current security posture; the establishment timestamp records the creation time of the anchor point, assisting the agent in making reasoning judgments in the time dimension. Once established, the anchor point record is permanently appended to the context window and is not removed or modified during any compression operation; multiple anchor points are arranged in the order of establishment to form an anchor point chain, so that even if a large number of failed branches have been compressed into a summary, the anchor point chain still allows the agent to clearly perceive the overall progress. The anchor point chain and the branch records under each anchor point together constitute the complete tree structure of the penetration test process.
[0054] This embodiment constructs a complete framework for the penetration testing process through the multi-dimensional information structure and permanent retention mechanism of anchor point records, enabling the agent to maintain accurate perception of the global situation throughout long-term tasks.
[0055] In some embodiments, when the action type is to invoke the raw output retrieval tool, the corresponding raw standard output and standard error output are precisely matched from the external storage module using the branch identifier and command string as a composite key and returned. The retrieval results (i.e., the corresponding raw standard output and standard error output) are appended to the context window as temporary content for analysis. After the analysis is completed, the agent autonomously decides whether to retain the temporary content in the context or remove it.
[0056] Specifically, the core mechanism of the raw output retrieval module is built upon the collaboration between the external storage module and the failed branch summary module. The external storage module persistently stores the raw output of each round of interaction using a composite key of (branch identifier, complete command); the failed branch summary module generates a complete list of raw commands from the same branch within its generated failed branch summary. The external storage module and the failed branch summary module form a precise index mapping relationship through the common element of the command string. The raw output retrieval module is the software module within the agent used to invoke the raw output retrieval tool and process the retrieval results; the failed branch summary module is the software module within the agent used to invoke the failed branch summarization tool and process the failed branch summaries.
[0057] Typical scenarios for an agent to invoke the raw output retrieval tool include: discovering new vulnerability clues during subsequent operations and needing to review whether a previous command exposed relevant features; or when an attack is blocked, needing to re-analyze the error echo of a failed command to confirm whether key information was missed. The retrieval results are appended to the context window as temporary content. After the agent completes its analysis, if the results contain clues that can be continuously referenced later, they are retained; otherwise, they are removed to maintain context brevity. The design of this raw output retrieval module embodies the engineering philosophy of progressive information disclosure.
[0058] This embodiment employs a progressive information disclosure mechanism, allowing the agent to maintain awareness of global progress by simply reading a concise summary of failed branches under normal circumstances. When it is necessary to delve deeper into potential clues in historical branches, the agent can retrieve and restore the original output for fine-grained analysis, thereby preserving the ability to continuously re-analyze without increasing the burden on the normal context.
[0059] In some embodiments, storing the output into an external storage module using the current branch identifier and command string as a composite key includes: using a lightweight key-value storage method, using the composite key composed of the current branch identifier and command string as the index key, and the original standard output and standard error output of the command as the value, and writing it into a local database; the storage operation can be completed through system-side hard-coded logic, without relying on the participation of large models, and without truncating or summarizing the tool output, ensuring the integrity and fidelity of the original data.
[0060] Specifically, after each round of penetration testing commands is executed, the testing system automatically calls the external storage write function to store the command string and its original output for the current round into the external storage module. The external storage module is preferably implemented using an SQLite database to reduce deployment and maintenance costs. Alternatively, other lightweight key-value storage solutions, such as JSON Lines files or distributed storage systems, can also be used.
[0061] The database table structure includes the following fields: Branch Identifier field, used to record the branch number to which the current command belongs; Command String field, used to record the complete command text; Standard Output field, used to store the standard output after command execution; Standard Error Output field, used to store the error output after command execution; and Timestamp field, used to record the time of command execution. The storage operation is automatically triggered by the system after each tool execution, implemented entirely through hard-coded logic, and does not consume inference resources from large models.
[0062] This embodiment persistently saves the complete original output through a lightweight external storage module, and the storage process has zero inference overhead, providing a reliable data foundation for subsequent on-demand retrieval.
[0063] In some embodiments, the method further includes: after declaring a new anchor point, retaining a structured summary of all historical failed branches in the context as a reference for subsequent decisions; when all reasonable exploration branches under the current anchor point have been exhausted, the agent switches to a new attack target or direction, declares a new anchor point and resets the branch identifier, and continues to execute the loop.
[0064] Specifically, structured summaries of historical failed branches remain in the context window after a new anchor point is declared; they are not deleted or removed. These summaries prevent the agent from repeating failed paths in subsequent explorations. When all reasonable exploration branches under the current anchor point have been tried and exhausted, the agent decides to switch to a new attack target or direction, declares a new anchor point, resets the branch identifier, and continues penetration testing in the new macro-direction.
[0065] This embodiment achieves efficient advancement of the penetration testing process by retaining historical failure branch summaries and enabling agents to autonomously decide branch switching.
[0066] It should be understood that although the steps in the flowcharts of the embodiments described above are shown sequentially according to the arrows, these steps are not necessarily executed in the order indicated by the arrows. Unless explicitly stated herein, there is no strict order restriction on the execution of these steps, and they can be executed in other orders. Moreover, at least some steps in the flowcharts of the embodiments described above may include multiple steps or multiple stages. These steps or stages are not necessarily completed at the same time, but can be executed at different times. The execution order of these steps or stages is not necessarily sequential, but can be performed alternately or in turn with other steps or at least some of the steps or stages of other steps.
[0067] For ease of understanding, such as Figure 2 As shown, a specific embodiment is used for illustration: The agent is deployed on a server with the goal of performing an authorized penetration test on a company's intranet. After the task starts, the system initializes the anchor point state (currently no active anchor points) and the branch identifier (Branch-1).
[0068] The agent invokes a large model for reasoning and decision-making, outputting the action type "Execute penetration testing tool," and executes nmap to scan the target host 192.168.1.100. The testing system automatically stores the scan results in an SQLite database with the key (Branch-1, "nmap -sV192.168.1.100"). The scan results show that the target is running Apache 2.4.41 with port 80 open. The agent then decides to execute a gobuster directory brute-force attack, storing the output in external storage.
[0069] After five rounds of exploration, the agent confirmed the discovery of an exploitable file upload vulnerability and successfully obtained a shell. At this point, the agent determined that it had made deterministic progress, made a decision to output the action type of calling the anchor setting tool, declared Anchor-1, recorded "Web Shell access to 192.168.1.100 has been obtained", and started a new branch Branch-2.
[0070] In Branch-2, the agent attempts to escalate privileges, successively trying various local privilege escalation exploits, all of which fail. When the number of consecutive failed commands reaches a preset threshold, the test system automatically triggers the action type of calling the failed branch summary tool. The large model integrates the five commands of this branch and their output into a structured summary: the original command list contains the five deduplicated commands and iteration annotations; the key discovery list extracts "the current user is www-data, kernel version is Linux 4.15.0, no sudo privileges"; the branch overview describes the process of the failed local privilege escalation attempt. This summary replaces all the original records of Branch-2, significantly reducing the context space.
[0071] The agent subsequently discovered a new vulnerability clue in Branch-3, requiring confirmation of whether any port information had been missed during the previous scan. Therefore, it decided to output the action type of the original output retrieval tool, retrieving the complete scan results from the SQLite database using (Branch-1,"nmap-sV 192.168.1.100") as the key. After analysis, the agent retained the temporary retrieval content in the context for future reference. This process was repeated until the penetration test objective was achieved or all vulnerabilities were exhausted.
[0072] In one exemplary embodiment, a computer device is provided, which may be a server, and its internal structure diagram may be as follows: Figure 3As shown, this computer device includes a processor, memory, input / output (I / O) interfaces, and a communication interface. The processor, memory, and I / O interfaces are connected via a system bus, and the communication interface is also connected to the system bus via the I / O interfaces. The processor provides computational and control capabilities. The memory includes non-volatile storage media and internal memory. The non-volatile storage media stores the operating system and computer programs. The internal memory provides the environment for the operation of the operating system and computer programs stored in the non-volatile storage media. The I / O interfaces are used for exchanging information between the processor and external devices. The communication interface is used for communicating with external terminals via a network connection. When the computer program is executed by the processor, it implements a penetration testing context management method.
[0073] Those skilled in the art will understand that Figure 3 The structure shown is merely a block diagram of a portion of the structure related to the present application and does not constitute a limitation on the computer device to which the present application is applied. Specific computer devices may include more or fewer components than those shown in the figure, or combine certain components, or have different component arrangements.
[0074] In one embodiment, a computer-readable storage medium is provided, on which a program or instructions are stored, which, when executed by a processor, implement the steps in the above-described method embodiments.
[0075] In one embodiment, a computer program product is provided, including a computer program that, when executed by a processor, implements the steps in the above method embodiments.
[0076] Those skilled in the art will understand that all or part of the processes in the methods of the above embodiments can be implemented by a computer program instructing related hardware. The computer program can be stored in a non-volatile computer-readable storage medium, and when executed, it can include the processes of the embodiments of the above methods. Any references to memory, databases, or other media used in the embodiments provided in this application can include at least one of non-volatile memory and volatile memory. Non-volatile memory can include read-only memory (ROM), magnetic tape, floppy disk, flash memory, optical memory, high-density embedded non-volatile memory, resistive random access memory (ReRAM), magnetic random access memory (MRAM), ferroelectric random access memory (FRAM), phase change memory (PCM), graphene memory, etc. Volatile memory can include random access memory (RAM) or external cache memory, etc. By way of illustration and not limitation, RAM can take many forms, such as Static Random Access Memory (SRAM) or Dynamic Random Access Memory (DRAM). The databases involved in the embodiments provided in this application may include at least one type of relational database and non-relational database. Non-relational databases may include, but are not limited to, blockchain-based distributed databases. The processors involved in the embodiments provided in this application may be general-purpose processors, central processing units, graphics processing units, digital signal processors, programmable logic devices, quantum computing-based data processing logic devices, artificial intelligence (AI) processors, etc., and are not limited to these.
[0077] The technical features of the above embodiments can be combined in any way. For the sake of brevity, not all possible combinations of the technical features in the above embodiments are described. However, as long as there is no contradiction in the combination of these technical features, they should be considered to be within the scope of this application.
[0078] The embodiments described above are merely illustrative of several implementation methods of this application, and while the descriptions are specific and detailed, they should not be construed as limiting the scope of this patent application. It should be noted that those skilled in the art can make various modifications and improvements without departing from the concept of this application, and these all fall within the protection scope of this application. Therefore, the protection scope of this application should be determined by the appended claims.
Claims
1. A penetration testing context management method, applied to devices with deployed intelligent agents, characterized in that, Penetration testing context management methods include: In the main loop of penetration testing, a large model is invoked to make inference decisions and output the next action type, which includes executing penetration testing tools or invoking context management tools. When the action type is to execute a penetration testing tool, the corresponding penetration testing tool is invoked to perform operations on the target system and capture the output. At the same time, the output is stored in the external storage module using the current branch identifier and the command string as a composite key. When the action type is to invoke a context management tool, the corresponding context management operation is performed according to the type of the context management tool; The context management tool includes a failed branch summary tool. When the failed branch summary tool is invoked, all original commands and output records under the current branch are integrated into a structured summary containing a list of original commands, a list of key findings, and a branch overview. The structured summary replaces all the original context records of the current branch.
2. The penetration testing context management method according to claim 1, characterized in that, The context management tool also includes an anchor point setting tool and a raw output retrieval tool; When the action type is to call the anchor point setting tool, a new anchor point is declared and the anchor point record is appended to the context window, while the current branch identifier is updated to open a new exploration branch; When the action type is to call the raw output retrieval tool, the corresponding raw standard output and standard error output are accurately matched from the external storage module using the branch identifier and command string as composite keys.
3. The penetration testing context management method according to claim 2, characterized in that, The process of declaring a new anchor point and appending the anchor point record to the context window includes: Declare a new anchor point and generate an anchor point record, which includes a unique identifier for the anchor point, the branch identifier to which it belongs when it is established, a natural language state description of the anchor point, and an establishment timestamp. The anchor point record is permanently appended to the context window without compression.
4. The penetration testing context management method according to claim 1, characterized in that, The triggering method for invoking the failed branch summarization tool includes at least one of the following: Autonomous triggering by the intelligent agent: When the agent perceives that the current attack direction is continuously blocked after multiple attempts, the tool output repeatedly indicates the same error type, or no new clues are generated after multiple attempts, the agent autonomously decides to output the action type of calling the failure branch summary tool. System forced trigger: When the number of commands continuously executed by the agent under the current branch reaches a preset threshold and no deterministic progress is made, the system automatically triggers the invocation of the failed branch summary tool.
5. The penetration testing context management method according to claim 4, characterized in that, The priority of autonomous triggering by the intelligent agent is higher than the priority of forced triggering by the system.
6. The penetration testing context management method according to claim 1, characterized in that, The original command list is generated, including: Traverse all executed commands in the current branch and perform deduplication to obtain the original command list. For the same command string, retain the first and last execution records. For commands with iterative characteristics, additionally mark the total number of iterations. Generate the list of key findings, including: The large model extracts valuable investigative clues from the context corresponding to the current branch to obtain the list of key findings; Generate the branch overview, including: The large model integrates the exploration objective, execution process, and final result of the current branch to generate a natural language description as an overview of the branch. The natural language description is used to summarize the complete exploration process and the reasons for failure.
7. The penetration testing context management method according to claim 6, characterized in that, The list of key findings includes at least one of the following: Open port numbers and service versions, accessible directory paths and access control status, vulnerability fingerprints, system permission boundary information, and configuration information exposed in error responses.
8. The penetration testing context management method according to claim 1, characterized in that, After invoking the corresponding penetration testing tool to perform operations on the target system and capturing the output, the method further includes: Determine whether deterministic progress has been achieved based on the tool's execution results. If deterministic progress has been achieved, output the action type that invoked the anchor point setting tool. The deterministic progress includes at least one of the following scenarios: Gain new shell access, obtain valid credentials, verify the exploitability of vulnerabilities and successfully execute proof-of-concept code, confirm new live hosts or accessible internal services, and complete privilege escalation or lateral movement.
9. A computer device, characterized in that, It includes a processor, a memory, and a program or instructions stored in the memory and executable on the processor, wherein the program or instructions, when executed by the processor, implement the steps of the context management method for penetration testing as described in any one of claims 1-8.
10. A readable storage medium, characterized in that, The readable storage medium stores a program or instructions that, when executed by a processor, implement the steps of the context management method for penetration testing as described in any one of claims 1-8.
