A fine-grained JavaScript malicious behavior detection method based on a large model

CN122389033BActive Publication Date: 2026-09-18ZHEJIANG UNIV
View PDF 2 Cites 0 Cited by

Patent Information

Application Number
CN202610864952.0
Authority / Receiving Office
CN · China
Patent Type
Patents(China)
Current Assignee / Owner
Filing Date
2026-06-16
Publication Date
2026-09-18
Estimated Expiration
2046-06-16

AI Technical Summary

Technical Problem

[0008]本发明的目的在于针对现有技术的不足,提供一种基于大模型的细粒度JavaScript恶意行为检测方法,现有技术中存在强制执行引擎鲁棒性不足、对高质量标注数据依赖较强以及检测结果不够精细的问题

Benefits of technology

[0024] 1. This invention effectively solves the problem of program crashes and premature termination caused by abnormal access to null or undefined values ​​when the forced execution engine covers branches outside the normal path by implementing an exception blocking mechanism using dynamic placeholder objects. This significantly improves the robustness of the forced execution engine. In a customized dynamic execution environment, the forced execution engine can modify the bytecode generation functions of each branch statement in the V8 engine to execute all branch statements by default to expose the behavior of functions as much as possible. For any null or undefined value access operation detected during forced execution, this invention generates a dynamic placeholder object by calling a custom interface to replace the target object. Utilizing the unique attribute access interface of this placeholder object, it ensures that the operation is valid by default and continues execution during any attribute access, function call, and constructor call. The placeholder object enables safe reading and writing of the corresponding attributes. This mechanism replaces the original exception throwing logic, ensuring the continuity of the execution process without interruption and effectively solving the technical defects of existing dynamic forced execution technology, which lacks rigor in handling runtime exceptions and is prone to program crashes.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN122389033B_ABST
    Figure CN122389033B_ABST
Patent Text Reader

Abstract

The application discloses a fine-grained JavaScript malicious behavior detection method based on a large model, and automatically generates interface calling codes in a dynamic generation and document mining combined manner to drive complete execution of JavaScript library codes. The script full branch logic is enforced in an enforcement engine with a fault tolerance mechanism, function-level runtime behavior sequences are collected, the function-level behavior sequences are represented by using domain-specific language behavior data and compressed, a large language model with a reflection mechanism is used to perform deep reasoning on behavior semantics, and it is judged whether the function has malicious behavior. Compared with the prior art, the application solves the problems of insufficient robustness of the enforcement engine, strong dependence on high-quality labeled data, and insufficient detection result fineness.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the field of computer software engineering, and in particular to a fine-grained method for detecting malicious JavaScript behavior based on a large model. Background Technology

[0002] In current web development, JavaScript libraries are widely used and distributed via Content Delivery Networks (CDNs). However, if malicious code is injected into third-party libraries, attackers can rapidly spread this malicious code to thousands of web applications worldwide through CDN nodes, forming a widespread supply chain attack. Malicious JavaScript behaviors include tracking user behavior, ad injection, and malicious redirection attacks. Existing malicious JavaScript detection methods primarily identify potential malicious code through static and dynamic analysis. Due to the highly dynamic nature of JavaScript and the prevalence of code obfuscation, static analysis struggles to accurately depict the true semantics of script behavior. Furthermore, malicious behaviors often rely on runtime context and API interactions, making it difficult for developers to identify potential risks before using the script in complex web environments. In addition, existing detection systems often use the entire script as the smallest unit of judgment, frequently employing a coarse-grained overall blocking strategy when malicious behavior is detected, severely impacting webpage usability and user experience.

[0003] Previous work has investigated the detection of malicious JavaScript behavior. In terms of program analysis, static analysis has been used to identify and trace scripts, but its effectiveness is limited when faced with obfuscated code. Alternatively, dynamic analysis can be used to capture runtime behavior for judgment, and a forced execution engine can be introduced to systematically drive unreachable paths. However, this forced execution engine lacks handling for runtime exceptions and is prone to crashing. Regarding detection models, most existing models are based on machine learning or deep learning, relying on a defined feature space and a large amount of labeled training data, which limits the model's generalization ability in open-world scenarios. Furthermore, in terms of detection results, existing detection systems often use the entire script as the smallest judgment unit, frequently adopting a coarse-grained overall blocking strategy when malicious behavior is detected, severely impacting webpage usability and user experience.

[0004] The existing technology has at least the following problems:

[0005] 1. Insufficient behavior coverage and robustness: Static analysis is difficult to deal with code obfuscation, while existing dynamic enforcement techniques lack rigor in handling branch condition constraints and runtime exceptions, which can easily lead to infeasible program execution paths or crashes.

[0006] 2. Labeling Dependence and Generalization Limitations: Most traditional detection models are based on machine learning, which relies excessively on high-quality real labeled data. They have poor generalization ability and fail to fully utilize the semantic understanding and behavior modeling capabilities of large language models under conditions of scarce labels.

[0007] 3. Coarse-grained detection: Existing detection methods often use scripts as the smallest judgment unit, resulting in many legitimate functions within the script failing to execute, severely impacting webpage usability and user experience. Label dependency and limited generalization: Traditional detection models are mostly based on machine learning, overly relying on high-quality real-world labeled data, exhibiting poor generalization ability, and failing to fully utilize the semantic understanding and behavioral modeling capabilities of large language models under conditions of scarce labeling. Summary of the Invention

[0008] The purpose of this invention is to address the shortcomings of existing technologies by providing a fine-grained JavaScript malicious behavior detection method based on a large model. Existing technologies suffer from insufficient robustness of the enforcement engine, strong reliance on high-quality labeled data, and insufficiently refined detection results. To address these deficiencies, this invention automatically generates calling code, collects behavioral data on a fault-tolerant enforcement engine, and leverages function-level runtime behavioral data represented by semantic analysis of a large model to achieve function-level malicious behavior detection in JavaScript runtime, thus overcoming the shortcomings of existing technologies. The objective of this invention is achieved using the following technical solutions:

[0009] This invention discloses a fine-grained JavaScript malicious behavior detection method based on a large model, comprising the following steps:

[0010] 1) By combining dynamic generation and document mining, global interface call code for the front-end JavaScript library is automatically generated to drive the complete execution of the library code;

[0011] 2) Run the interface call code in a customized dynamic execution environment, dynamically execute all branch statements using the exception blocking mechanism of branch forced execution and dynamic placeholder objects, and collect function-level runtime behavior data attributed by call stack using instrumentation;

[0012] 3) Use a domain-specific language to structure the collected runtime behavior data, and while preserving the semantic information of the behavior, represent the original data as a compact, fine-grained sequence of function behaviors;

[0013] 4) Input the function behavior sequence into the large language model, and combine it with the thought chain and self-reflection prompts to guide the large model to make semantic judgments and detect functions with malicious behavior.

[0014] As a further improvement, in 1) of the present invention, the dynamic generation method of automatically generating global interface call code of the front-end JavaScript library by combining dynamic generation and document mining is as follows: run the front-end JavaScript library to be tested in a dynamic environment, collect all global interfaces in it, try to run these interfaces, find the interface call method without error, and generate the final interface call statement.

[0015] As a further improvement, the method for finding error-free interface calls described in this invention is as follows: a feedback-oriented unit test generation algorithm is used to generate random values ​​and construct parameter combinations for eight common data types in front-end JavaScript, and the parameter combinations executed without errors are recorded as interface call statements; the eight data types are number, string, null, boolean, array, object, function, and DOM element.

[0016] As a further improvement, in 1) of the present invention, the document mining method for automatically generating global interface call code of front-end JavaScript libraries by combining dynamic generation and document mining is as follows: crawl the README.md document from the GitHub repository where each front-end library is located, extract and filter the JavaScript code snippets that can run in the browser environment, and merge the extracted example code with the dynamically generated interface call code to build a more comprehensive set of interface call code that is closer to real use scenarios, thereby driving the complete execution of the library code.

[0017] As a further improvement, in 2) of the present invention, the specific implementation of the branch forced execution in all branch statements using the exception blocking mechanism of the branch forced execution and dynamic placeholder objects is as follows: all conditional branches, loop branches and exception handling branch statements encountered during runtime are forcibly executed. By modifying the bytecode generation function of each branch statement in the V8 engine, the jump position corresponding to the branch condition calculation result in its original execution flow is changed, so that all branch statements will be executed by default regardless of the condition calculation result.

[0018] As a further improvement, in step 2) of this invention, the specific implementation of the exception blocking mechanism for dynamically executing dynamic placeholder objects in all branch statements using branch forced execution and dynamic placeholder objects is as follows: During script execution, the read and write interfaces of object attributes and inline cache are monitored. When an attribute access operation to a null or undefined value is detected, a dynamic placeholder object is constructed through a custom interface to replace it, so as to ensure that the execution process is not interrupted due to the triggering of runtime exceptions. Among them, the dynamic placeholder object is configured with full attribute adaptive response rules. For any attribute access or method call operation of the dynamic placeholder object, it will return itself or a preset valid placeholder instance by default to drive the code to continue execution.

[0019] As a further improvement, in step 2) of this invention, the specific implementation of collecting function-level runtime behavior data attributed by call stack using instrumentation is as follows: First, the typical characteristics of the JavaScript malicious behavior are analyzed and studied, corresponding to the relevant APIs in JavaScript. By monitoring typical characteristic APIs such as storage, event handling, network requests, DOM operations, and page jumps, dynamic runtime behavior data is collected. Then, the underlying function of the call stack is used as the attribution object to realize the collection of function-level runtime behavior data.

[0020] As a further improvement, the function-level runtime behavior data collection described in this invention specifically records the API interface name, the timestamp when the API is called, the API call parameters and call result data, the underlying function name of the call stack, the execution script ID, the execution script URL, and the row and column numbers of the underlying stack frame of the call stack as logs.

[0021] As a further improvement, in 3) of the present invention, the structured processing of the collected runtime behavior data using a domain-specific language is specifically implemented as follows: design a domain-specific language oriented towards JavaScript behavioral semantics to represent function runtime behavior data in a unified and structured manner, compressing function behavior sequences while retaining behavioral semantic information. The structured representation of function runtime behavior data specifically includes JavaScript API function behavior names and function behavior-related data.

[0022] As a further improvement, in section 4) of this invention, the specific implementation of combining thought chain and self-reflection prompts to guide the large model in semantic judgment is as follows: For each malicious behavior, a thought chain prompt is designed to assist in identifying whether the function behavior sequence conforms to the preset malicious behavior characteristics. After the large model reasons and thinks according to the thought chain, it gives the output result, including the malicious behavior type and the judgment basis. For the initial judgment result of the large model, the self-reflection prompts are combined to reflect on the result of each malicious behavior type and give a second judgment result, so as to obtain the final determined malicious behavior type.

[0023] The beneficial effects of this invention are:

[0024] 1. This invention effectively solves the problem of program crashes and premature termination caused by abnormal access to null or undefined values ​​when the forced execution engine covers branches outside the normal path by implementing an exception blocking mechanism using dynamic placeholder objects. This significantly improves the robustness of the forced execution engine. In a customized dynamic execution environment, the forced execution engine can modify the bytecode generation functions of each branch statement in the V8 engine to execute all branch statements by default to expose the behavior of functions as much as possible. For any null or undefined value access operation detected during forced execution, this invention generates a dynamic placeholder object by calling a custom interface to replace the target object. Utilizing the unique attribute access interface of this placeholder object, it ensures that the operation is valid by default and continues execution during any attribute access, function call, and constructor call. The placeholder object enables safe reading and writing of the corresponding attributes. This mechanism replaces the original exception throwing logic, ensuring the continuity of the execution process without interruption and effectively solving the technical defects of existing dynamic forced execution technology, which lacks rigor in handling runtime exceptions and is prone to program crashes.

[0025] 2. This invention, through systematic modeling of JavaScript function-level runtime behavior, introduces a large language model into the semantic analysis of function-level runtime behavior. This effectively solves the problem that existing traditional detection models overly rely on explicit feature spaces and high-quality real-label data, leading to limited and poor generalization ability in open-world environments. It fully utilizes the semantic understanding and behavior modeling capabilities of large language models under conditions of scarce annotations. This invention inputs the collected function behavior sequences into the large language model, constructs prompt word templates that include role settings, task descriptions, thought chain reasoning, output format constraints, and example references, and guides the large model to perform semantic judgment and secondary reflection discrimination by combining thought chain and self-reflection prompts. This enables the detection system to accurately identify whether function behavior sequences conform to preset malicious behavior characteristics without requiring a large amount of labeled training data, greatly improving the behavior generalization detection capability in unknown or open-world environments.

[0026] 3. This invention achieves function-level attribution of runtime data by analyzing the underlying functions of the call stack. This results in accurate, function-level malicious behavior detection and judgment criteria, overcoming the problem that existing detection systems often use the entire script as the smallest unit of judgment, leading to coarse-grained overall blocking strategies when malicious behavior is detected, severely impacting webpage usability and user experience. During the runtime data collection phase, by using the underlying functions of the call stack as the attribution object, this invention can aggregate multiple semantically related API behaviors within the same function scope, successfully constructing fine-grained function-level runtime behavior data. This fine-grained attribution and large-model detection mechanism significantly narrows the code scope of malicious behavior, avoiding the drawback of many legitimate functions within the script being unable to execute. While guiding the large model to accurately output the type of malicious behavior and its judgment criteria, it maximizes the preservation of webpage usability and user experience, helping developers use interfaces securely and accurately. Attached Figure Description

[0027] Figure 1 This is a flowchart of a fine-grained JavaScript malicious behavior detection method based on a large model proposed in this invention. Detailed Implementation

[0028] To enable those skilled in the art to better understand the present invention, the invention will be further described in detail below with reference to the accompanying drawings and specific embodiments. Obviously, the described embodiments are merely some embodiments of the present invention, and not all embodiments. All other embodiments obtained by those skilled in the art based on the embodiments provided by the present invention without creative effort are within the scope of protection of the present invention. Furthermore, it is understood that although the efforts made in such a development process may be complex and lengthy, for those skilled in the art related to the content disclosed in the present invention, some design, manufacturing, or production modifications based on the technical content disclosed in the present invention are merely conventional technical means and should not be construed as insufficient disclosure of the present invention.

[0029] This invention discloses a fine-grained JavaScript malicious behavior detection method based on a large model. It automatically generates call interfaces for JavaScript libraries, enforces the execution of each conditional branch through a fault-tolerant mechanism at runtime, and collects its behavior data. Furthermore, it performs function-level representation on the behavior data, constructs a function-level behavior sequence, and inputs it into a large model to determine whether malicious behavior exists.

[0030] like Figure 1 As shown, the fine-grained JavaScript malicious behavior detection method based on a large model proposed in this invention includes the following steps:

[0031] (1) By combining dynamic generation and document mining, global interface call code of the front-end JavaScript library is automatically generated to drive the complete execution of the library code.

[0032] To investigate potential malicious behavior in runtime front-end JavaScript libraries, it's necessary to fully execute the library code. However, most JavaScript libraries only define interfaces and don't actually call them, so it's necessary to invoke these interfaces. On real websites, while these JavaScript libraries are used, they don't exhaustively enumerate all interface calls. Therefore, a separate environment is needed to enumerate these interface calls, i.e., automatically generate the interface call code. This invention combines dynamic generation and document mining to automatically generate interface call code.

[0033] The dynamic generation method for automatically generating interface call code is implemented as follows: The front-end JavaScript library to be tested is run in a separate dynamic environment. Global interfaces added to the `window` variable before and after the library is introduced in this environment are collected; these are the global interfaces defined by the front-end library. Since JavaScript is a dynamic language, the type of a variable does not need to be specified at declaration but is dynamically determined during program execution based on the value assigned to the variable, and the variable type can change at any time. Static analysis cannot determine the data type of a variable or parameter; it can only be determined at runtime. Therefore, to generate correct or error-free function call statements, the appropriateness of the generated parameter combinations can only be verified in a dynamic runtime environment. This invention uses a feedback-oriented unit test generation algorithm to generate random values ​​and construct parameter combinations for eight common data types in front-end JavaScript to drive code execution. These eight data types are number, string, null, boolean, array, object, function, and DOM element. By using AST tools to parse the number of parameters of the interface, generating a specified number of random parameter combinations, testing the interface, and considering all parameter combinations that can be executed without errors as successful calls, these are recorded as the corresponding interface call statements. Finally, a global interface test case with self-executing functionality is constructed, which includes the target library script code and its corresponding global interface call sequence.

[0034] The aforementioned dynamic process is executed entirely within a sandbox, capturing runtime errors or timeouts generated during the test run to indicate whether the call was successful. Simultaneously, by examining the object returned by the interface call, it distinguishes between synchronous and asynchronous interfaces, as the generated call code formats differ between the two types. To ensure that the constructed interface call code conforms to standard syntax, this invention utilizes an AST tool to assist in generating the call code structure, ultimately converting it into a string to obtain the call code. For example, `window.funcA = function(){…}` collects the interface `funcA` defined in the front-end JavaScript library, generates the corresponding call statement `funcA();`, and concatenates it with the source code `source_code` of the JavaScript library to be tested to form a complete self-driven execution script.

[0035] Building upon this foundation, to further enrich the application scenarios, this invention also employs document mining to automatically generate API call code. Specifically, this involves crawling the README.md files from the GitHub repositories of various front-end libraries and extracting and parsing the sample code that may be contained within. During sample extraction, regular expressions are used to extract JavaScript code blocks, filtering out valid JavaScript code snippets that can run in a browser environment through syntax checking and regular expressions. Finally, the extracted sample code is merged with the dynamically generated API call code to construct a more comprehensive set of API call code that closely resembles real-world usage scenarios. This drives the complete execution of the library code and provides a reliable data foundation for subsequent dynamic behavior analysis and malicious behavior detection.

[0036] (2) Run the interface call code in a customized dynamic execution environment, use the branch forced execution and the exception blocking mechanism of dynamic placeholder objects to dynamically execute all branch statements, and use instrumentation to collect function-level runtime behavior data attributed by the call stack.

[0037] Run the preprocessed JavaScript file in a customized dynamic execution environment. This customized dynamic execution environment includes the following two main features:

[0038] First, we enforce the execution of the V8 engine (Chrome V8 JavaScript engine), ensuring that all branching statements encountered during runtime are executed, such as conditional branches, loop branches, and exception handling statements, thus exposing the behavior within functions as much as possible. During normal program execution, when a branching statement is reached, only one branch path is selected for execution based on the evaluation result of the conditional expression, while other branch paths that do not meet the condition are not executed, resulting in incomplete path coverage. By modifying the bytecode generation functions of each branching statement in the V8 engine, we change the jump positions corresponding to the branch condition evaluation results in the original execution flow, ensuring that all branching statements are executed by default regardless of the condition evaluation result.

[0039] Because forced execution can overwrite branches outside the normal path, it often triggers exceptions for accessing null or undefined values, leading to program crashes and premature termination. Therefore, a custom interface is implemented in the V8 engine to return a dynamic placeholder object. This dynamic placeholder object is essentially a custom JSProxy object, with implementations of get, set, apply, construct, and has methods for accessing its properties. This ensures that it remains valid and continues execution by default during any property access, function call, or constructor call. The object is also marked with the `_is_stub` attribute to distinguish it as a dynamic placeholder. By monitoring the read and write interfaces of object properties and inline caches, during the forced execution engine's operation, if an access operation to a null or undefined value is detected, the original exception handling logic is replaced. The custom interface is called to generate a dynamic placeholder object to replace the target object. This dynamic placeholder object enables safe reading and writing of the corresponding properties, ensuring the continuity of execution without interruption.

[0040] Second, it utilizes Chromium browsers with specified JavaScript API instrumentation capabilities. The malicious behavior types detected by this invention include user tracking, ad injection, covert downloads, clickjacking, resource exhaustion attacks, malicious redirects, and browser environment spoofing. By analyzing the typical characteristics of these malicious JavaScript behaviors, including storage, event handling, network, DOM manipulation, and page navigation, and mapping them to relevant JavaScript APIs, the specific implementation locations of these API interfaces are located in Chromium's Blink layer. Monitoring code is inserted into these APIs to collect relevant runtime log information. The collected runtime data specifically includes the API interface name, the timestamp when the API was called, the API call parameters or call result, the name of the underlying function in the call stack, the executed script ID, the executed script URL, and the line and column numbers of the underlying stack frames in the call stack. This information is asynchronously stored in log files for subsequent analysis. Function-level attribution of this behavioral data is achieved by recording relevant call stack information. Since the top-level functions of the call stack are usually scattered, making it difficult to aggregate multiple semantically related API behaviors within the same function scope, this invention uses the underlying functions of the call stack as the attribution object to achieve function-level behavior attribution and construct function-level runtime behavior data accordingly. For example, the self-driving script of the funcA interface can be run in a customized environment to collect the raw log information generated, including the interface name, timestamp, interface call data, and stack information.The specific example data is [get screen.width], timestamp, [get screen.width], funcA_stack_info; [get screen.height], timestamp, [get screen.height], funcA_stack_info; [storagesetItem], timestamp, [storage setItem], localStorage, [storage setItem], value, [storage setItem], [storage setItem],funcA_stack_info[create image],timestamp,[create image],0:0,[create image],funcA_stack_info;[set element attribute],timestamp,[set element attribute],IMG,[set element attribute],src,[setelement attribute],source_url,[set element attribute],funcA_stack_info.

[0041] Since the API operations related to the dynamic placeholder objects cannot be passed to the Blink layer, an additional API instrumentation mechanism for dynamic placeholder objects needs to be implemented in the V8 engine, namely, recording property access operations, to ensure the comprehensiveness and coverage of behavioral data collection. Monitoring code is inserted at the object property access points in the V8 engine to collect relevant runtime log information. The collected runtime data specifically includes the accessed API interface name, the timestamp of the property access, API call parameters, the name of the underlying function in the call stack, the executed script ID, the executed script URL, and the line and column numbers of the underlying stack frame in the call stack. This information is also asynchronously stored in the log file. Based on the underlying function of the call stack as the attribution object, function-level runtime behavioral data is supplemented and constructed for subsequent analysis.

[0042] (3) Use domain-specific languages ​​to structure the collected runtime behavior data, and while preserving the semantic information of the behavior, represent the original data as a compact, fine-grained sequence of function behaviors.

[0043] Design a domain-specific language for JavaScript behavioral semantics to represent function runtime behavior data in a unified and structured way. This will compress function behavior sequences while preserving behavioral semantic information, reducing the input cost of large models. The structured data includes JavaScript API function behavior names and related data. Each piece of structured data is categorized by underlying function information from the call stack. This categorized information consists of the underlying function name, execution script ID, execution script URL, and the row and column numbers of the underlying stack frame from the log. After categorization, the data is sorted according to the timestamps in the log, resulting in a fine-grained, function-level temporal sequence of runtime behavior. For example, based on the function stack information `funcA_stack_info`, function-level categorization is performed on the original runtime data to characterize the behavior sequence of the interface `funcA`. A specific example data is `funcA_stack_info:[get screen.width];[getscreen.height];[storage setItem],localStorage,value;[create image],0:0;[setelement attribute],IMG,src,source_url`.

[0044] In addition, the present invention performs deduplication and compression processing on the behavior sequence, the processing including two steps: merging adjacent data and greedy data block deduplication.

[0045] The merging of adjacent data includes the following two rules:

[0046] 1. Merging adjacent identical data: When adjacent behavioral data are completely identical, count the number of consecutive occurrences, retain only one behavioral data, and record the corresponding number of occurrences at the end to represent the execution frequency;

[0047] 2. Merging Adjacent Data of the Same Type: When adjacent behavioral data have the same behavior type but different association parameters, their association parameters are merged to form a single behavioral data. For example, "[add event listener], mouseover", "[add event listener], mouseout", and "[add event listener], click" are merged into "[add event listener], mouseover, mouseout, click".

[0048] Furthermore, the greedy data block deduplication step includes: iterating over data blocks of length m in descending order, traversing all starting positions s in the behavior sequence, and when there are k consecutive (k≥2) data blocks of length m with identical content at position s, replacing the k data blocks with a single data block. This process is repeated for the entire behavior sequence until no further merging operations occur in a complete traversal.

[0049] By performing the above two-step deduplication and compression process, the data size of the runtime behavior sequence is effectively reduced while maintaining the density of behavioral semantic information, thereby reducing the input cost of processing large models.

[0050] (4) Input the function behavior sequence into the large language model, and combine the thought chain and self-reflection prompt words to guide the large model to make semantic judgments and detect functions with malicious behavior.

[0051] This invention detects malicious behaviors including user tracking, ad injection, covert downloads, clickjacking, resource exhaustion attacks, malicious redirection, and browser environment spoofing. By analyzing the typical characteristics of these malicious behaviors beforehand, key points for identification are identified, and thought chain prompts are designed for each type of malicious behavior. A prompt template containing role settings, task descriptions, thought chain reasoning, output format constraints, and example references guides a large-scale model to identify whether a sequence of behavioral functions conforms to the preset malicious behavior characteristics based on semantic analysis. The large-scale model then outputs results after reasoning according to the thought chain, including the type of malicious behavior and its discrimination criteria.

[0052] For the initial judgment result of the large model, when multiple malicious behavior types exist, a self-reflective secondary judgment process is performed for each candidate malicious behavior type result. Specifically, by constructing a prompt word template that includes role settings, task description, initial judgment results and their basis, more detailed thought chain reasoning, output format constraints, and example references, the large model is guided to reflect on and analyze the initial judgment results and basis, evaluate the rationality of the judgment basis, the authenticity of the related behaviors, and their matching degree with the characteristics of the corresponding malicious behavior type, thereby inferring whether the judgment result is correct and outputting the corrected malicious behavior type and its basis. Finally, the initial judgment result and the secondary reflection result are merged to obtain the final determined malicious behavior type. For example, the behavior sequence of the funcA interface, concatenated with prompt words, is input into the large model to obtain the final judgment result, including the interface name, malicious behavior type, and judgment basis. The specific example data results are: {"function_name": "funcA_stack_info","malicious_types": ["user-tracking"],"explanation": ["The function reads screen dimensions, stores data inlocalStorage under a persistent key, and triggers a tracking-pixel-styleimage request with multiple identifier-like query parameters (affid, tid,geo, reqid), indicating its primary tracking purpose is user / behavior tracking orattribution."]}.

[0053] In specific implementation, this invention is based on Chromium version 139.0.7225.0, and was used to analyze the runtime behavior data of 150 JavaScript functions. The data to be detected included 75 functions exhibiting malicious behavior and 75 functions exhibiting normal behavior. Experimental results show that this invention can detect malicious behavior with high accuracy, specifically 97%. Tools include:

[0054] A code generation module: This module uses a combination of dynamic generation and document mining to automatically generate global API call code for front-end JavaScript libraries, thereby driving the complete execution of the library code.

[0055] A customized dynamic execution environment module: used to run interface call code in a customized dynamic execution environment, dynamically execute all branch statements using branch enforcement and exception blocking mechanisms of dynamic placeholder objects, and collect function-level runtime behavior data attributed by call stack using instrumentation.

[0056] A behavioral data representation module: used to structure the collected runtime behavioral data using a domain-specific language, representing the raw data as a compact, fine-grained sequence of functional behaviors while preserving the semantic information of the behavior.

[0057] A malicious behavior detection module: This module is used to input the function behavior sequence into a large language model, and combine it with thought chain and self-reflection prompts to guide the large model to perform semantic judgment and detect functions with malicious behavior.

[0058] It should be understood that this application is not limited to the precise structure described above and shown in the accompanying drawings, and various modifications and changes can be made without departing from its scope. This invention discloses a fine-grained JavaScript malicious behavior detection method based on a large model. This invention automatically generates interface call code by combining dynamic generation and document mining to drive the complete execution of JavaScript library code. In a forced execution engine with an exception blocking mechanism, all branch logic of the script is forcibly executed, collecting function-level runtime behavior sequences. These sequences are represented and compressed into function-level behavior sequences using domain-specific language behavior data. A large language model with a reflective mechanism is then used to perform deep reasoning on the behavioral semantics to determine whether the function exhibits malicious behavior. Compared to existing technologies, this invention solves the problems of insufficient robustness of forced execution engines, strong dependence on high-quality labeled data, and insufficiently refined detection results.

[0059] The above embodiments are merely preferred embodiments of the present invention, and the scope of protection of the present invention is not limited to the above embodiments. All technical solutions falling within the scope of the present invention's concept are within the scope of protection of the present invention. It should be noted that for those skilled in the art, improvements and modifications made without departing from the principles of the present invention should also be considered within the scope of protection of the present invention.

Claims

1. A fine-grained JavaScript malicious behavior detection method based on a large model, characterized in that, Includes the following steps: 1) By combining dynamic generation and document mining, global interface call code for the front-end JavaScript library is automatically generated to drive the complete execution of the JavaScript library code; 2) Run the interface call code in a customized dynamic execution environment. Utilize branch enforcement and dynamic placeholder object exception blocking mechanisms to dynamically execute all branch statements. Use instrumentation to collect function-level runtime behavior data attributed by call stack. Specifically, the branch enforcement mechanism is implemented by forcibly executing all conditional branches, loop branches, and exception handling branches encountered during runtime. This is achieved by modifying the bytecode generation functions of each branch statement in the V8 engine, changing the jump positions corresponding to the branch condition calculation results in the original execution flow, ensuring that all branch statements are executed by default regardless of the condition calculation results. The exception blocking mechanism for dynamically executing all branch statements using branch forced execution and dynamic placeholder objects is specifically implemented as follows: During script execution, the read and write interfaces of object attributes and inline cache are monitored. When an access operation to a target null or undefined value is detected, a dynamic placeholder object is constructed through a custom interface to replace it, ensuring that the execution process is not interrupted due to runtime exceptions. The dynamic placeholder object is configured with a full-attribute adaptive response rule, and any attribute access or method call operation of the dynamic placeholder object will by default return itself or a preset valid placeholder instance to drive the code to continue execution. 3) Use a domain-specific language to structure the collected runtime behavior data, and while preserving the semantic information of the behavior, represent the original data as a compact, fine-grained sequence of function behaviors; 4) Input the function behavior sequence into the large language model, and combine it with the thought chain and self-reflection prompts to guide the large model to make semantic judgments and detect functions with malicious behavior.

2. The fine-grained JavaScript malicious behavior detection method based on a large model according to claim 1, characterized in that, In the first part, the dynamic generation method of automatically generating global interface call code of the front-end JavaScript library by combining dynamic generation and document mining is as follows: run the front-end JavaScript library to be tested in a dynamic environment, collect all global interfaces in it, try to run these interfaces, find the interface call method without error, and generate the final interface call statement.

3. The fine-grained JavaScript malicious behavior detection method based on a large model according to claim 2, characterized in that, The method for finding error-free API calls specifically involves: using a feedback-oriented unit test generation algorithm to generate random values ​​and construct parameter combinations for eight common JavaScript data types, and recording error-free parameter combinations as API call statements; the eight data types are number, string, null, boolean, array, object, function, and DOM element.

4. The fine-grained JavaScript malicious behavior detection method based on a large model according to claim 1, 2, or 3, characterized in that, In step 1), a combination of dynamic generation and document mining is used to automatically generate the global interface call code of the front-end JavaScript library. The document mining method is as follows: crawl the README.md document from the GitHub repository where each front-end library is located, extract and filter the JavaScript code snippets that can run in the browser environment, and merge the extracted example code with the dynamically generated interface call code to build a more comprehensive set of interface call code that is closer to real use scenarios, thereby driving the complete execution of the library code.

5. The fine-grained JavaScript malicious behavior detection method based on a large model according to claim 1, 2, or 3, characterized in that, In step 2), the specific implementation of collecting function-level runtime behavior data attributed by call stack using instrumentation is as follows: First, analyze the typical characteristics of the JavaScript malicious behavior and correspond them to the relevant APIs in JavaScript. By monitoring typical characteristic APIs such as storage, event handling, network requests, DOM operations, and page jumps, collect dynamic runtime behavior data, and use the underlying functions of the call stack as the attribution objects to realize the collection of function-level runtime behavior data.

6. The fine-grained JavaScript malicious behavior detection method based on a large model according to claim 5, characterized in that, The implementation of function-level runtime behavior data collection specifically involves recording the API interface name, the timestamp when the API is called, the API call parameters and call result data, the underlying function name of the call stack, the execution script ID, the execution script URL, and the line and column numbers of the underlying stack frame of the call stack as logs.

7. The fine-grained JavaScript malicious behavior detection method based on a large model according to claim 6, characterized in that, In step 3), the specific implementation of using a domain-specific language to structure the collected runtime behavior data is as follows: design a domain-specific language oriented towards JavaScript behavioral semantics to represent function runtime behavior data in a unified and structured manner, compressing function behavior sequences while retaining behavioral semantic information. The structured representation of function runtime behavior data specifically includes JavaScript API function behavior names and function behavior-related data.

8. The fine-grained JavaScript malicious behavior detection method based on a large model according to claim 1, 2, 3, 6, or 7, characterized in that, In step 4), the specific implementation of combining thought chain and self-reflection prompts to guide the large model in semantic judgment is as follows: For each malicious behavior, a thought chain prompt is designed to help identify whether the function behavior sequence conforms to the preset malicious behavior characteristics. After the large model reasons and thinks according to the thought chain, it gives the output result, including the malicious behavior type and the judgment basis. For the initial judgment result of the large model, the result of each malicious behavior type is reflected on in combination with the self-reflection prompts and a second judgment result is given to obtain the finally determined malicious behavior type.

Citation Information

Patent Citations

  • Code detection and protection method, system, equipment and medium

    CN121351072A

  • KR1018586200000B1