Security Verification and Offensive-Defensive Practice

Blue Team Manual ④ [In-Memory Trojan Edition] In-Depth Analysis: The Threat of In-Memory Trojans and Comprehensive Defense Strategies

▌Concept and Background of Memory Trojan (Memory Horse)

Origin and Development of Memory Trojan

Memory Trojan initially emerged as a technical means to bypass traditional security detection, originating from the development of webshells. Early webshells primarily maintained persistence on servers by uploading malicious files. However, with advancements in file detection technologies, this method was gradually phased out, making Memory Trojans the new attack method. It directly loads malicious code into system memory, avoiding any footprint on the file system, thereby making it difficult for traditional antivirus software and intrusion detection systems to identify.

Memory Trojans in the Current Network Environment

As modern network environments grow more complex, particularly with the popularisation of cloud computing and microservices architectures, the use cases for Memory Trojans continue to expand. The elasticity and dynamic nature of cloud computing render traditional protection methods such as file monitoring and static analysis ineffective, while the stealthiness of Memory Trojans becomes particularly prominent in such environments. Especially in containerised applications, Memory Trojans can directly attack running containers without touching the file system, making them even harder to detect.

Definition and Classification of Memory Trojans

A Memory Trojan is an attack method that runs by directly injecting malicious code into the system memory, mainly classified into the following categories:

  • Servlet-based Memory Trojans: By leveraging Servlet APIs, attackers can dynamically register malicious Servlets or Filters, bypassing regular request filtering and processing.

  • Third-Party Component-based Memory Trojans: In frameworks such as SpringMVC and Struts2, attackers inject malicious code through vulnerabilities to plant Memory Trojans in the system.

  • Java Agent-based Memory Trojans: Through the JVM's Instrumentation interface, attackers can modify runtime bytecode to achieve memory injection.

▌Technical Implementation of Memory Trojans

Memory Trojan Insertion and Protection under Servlet Specification

In Servlet-based Memory Trojans, attackers typically inject malicious code into the request processing chain of Web applications by dynamically registering Filters or Servlets. For example, an attacker can inject a malicious Filter into a Tomcat server using code like the following:

The above code demonstrates how to dynamically register a malicious Filter via ServletContext. This Filter can intercept all HTTP requests and execute specific malicious logic, such as stealing users' sensitive data or executing unauthorized commands. Protection Measures:

  • Code Review and Security Testing: Perform strict code reviews and security testing during the development and deployment phases to prevent unsecure dynamic registration code from entering production environments.

  • Using Advanced Protection Tools: Deploy security tools capable of detecting and blocking unsecure dynamic behaviours to monitor and review the Servlet registration process.

Memory Trojan Attack Paths in Third-Party Components

Taking the SpringMVC framework as an example, attackers can control the application's HTTP requests by dynamically registering a malicious Controller. Below is an example implementation of a malicious Controller:

In this example, the malicious Controller can be dynamically registered at runtime and can handle HTTP requests on specific paths. This attack method is highly stealthy because it does not require modifying existing code; it is completed entirely through runtime dynamic registration.

Protection Measures:

  • Security Configuration: Ensure the security configurations of third-party components are in place to restrict the abuse of dynamic registration functions.

  • Regular Security Auditing: Conduct regular security audits on applications, especially on components using third-party frameworks, to prevent potential security vulnerabilities.

Java Agent Advanced Attack and Defence Strategies

Java Agent allows modifying bytecode at JVM startup or runtime, which is an important pathway for Memory Trojan technology. Below is sample code for injecting a Memory Trojan via a Java Agent:

In this example, the Java Agent registers a ClassFileTransformer via the premain method during JVM startup, which dynamically modifies the bytecode of specific classes (such as HttpServlet) to inject malicious logic. This method allows the Memory Trojan to be implanted without touching the original code, providing high stealthiness.

  • Memory Forensics and Real-time Monitoring: Use memory forensics tools like Volatility to analyse activity in memory, while deploying real-time monitoring systems to detect abnormal bytecode modification behaviour.

  • Strict Access Control: Restrict the permissions for using Java Agents, ensuring that only authorised operations can load and run Agents.

▌Detection and Forensics of Memory Trojans

Technical Challenges in Memory Trojan Detection

The fileless nature of Memory Trojans makes traditional detection methods ineffective at discovering their presence. Attackers typically use obfuscation and encryption technologies to further increase the difficulty of detection. Facing these challenges, strategies to detect Memory Trojans include:

  • Anomaly Behaviour Analysis: Identify Memory Trojan activities by monitoring abnormal behaviours in memory, such as unusual memory allocation and deallocation operations.

  • Multi-layered Detection: Combine network traffic analysis, behaviour monitoring, and memory forensics tools to form a multi-layered detection system, improving the recognition rate of Memory Trojans.

Detection Methods Based on Behaviour Analysis

Behaviour analysis technology effectively identifies Memory Trojan activities by monitoring system behaviour patterns. For example, by monitoring the system's memory usage patterns, abnormal activities of Memory Trojans can be discovered. Below is a simple example code for monitoring memory usage patterns:

This code monitors JVM memory usage and triggers an alert when memory usage exceeds a preset threshold. This approach can help discover the abnormal memory behaviour of Memory Trojans.

Memory Forensics Technology and Tool Application

Memory forensics tools are one of the critical instruments for detecting Memory Trojans. Through these tools, security experts can deeply analyse memory activities and extract malicious code. Below are the basic steps for conducting memory analysis using Volatility: 1. Acquire Memory Image: Use tools like DumpIt to acquire a memory image of the target system. 2. Load Image and Analyse: Load the memory image using Volatility and use commands like pslist, malfind, etc., to analyse processes and potential malicious activities in the system. 3. Extract Malicious Code: Extract malicious code from suspicious processes or memory regions through analysis for further reverse engineering. 4. Acquire Memory Image: Use tools (such as DumpIt) to acquire the memory image of the target system. This image will contain all runtime memory data of the system, including processes, network connections, Memory Trojans, etc.

5. Load Memory Image: Load the memory image using Volatility and specify the operating system profile. The profile is used to parse the OS version and type of the memory image.

6. Analyse Processes and Modules: Use commands provided by Volatility, such as pslist, dlllist, etc., to analyse processes in memory, loaded modules, and DLLs to search for potential traces of Memory Trojans.

7. Detect Malicious Activities: Use the malfind command to detect malicious code injection activities in memory and uncover hidden Memory Trojans.

8. Extract Malicious Code: Extract and analyse suspicious code segments using memory forensics tools for further reverse engineering and protection measures.

▌Actual Case Studies of Memory Trojans

Memory Trojan Applications in Modern APT Attacks

In recent APT attacks, Memory Trojan technology has been widely applied to breach high-value targets. Below is a typical attack case analysis: Case Description: The core business system of a financial institution was attacked by an APT group. The attackers implanted a persistent backdoor on key application servers using a Java Agent Memory Trojan, continuously stealing sensitive data through this backdoor.

  • Attack Path: Attackers first gained initial system access through social engineering, and then planted malicious bytecode during JVM startup using a Java Agent Memory Trojan.

  • Memory Trojan Implementation: Using Java Agent technology, attackers modified the Servlet response logic of the core application, causing sensitive data to be forwarded to external servers controlled by the attackers without authorization.

Protection Suggestions——

  • Improve Employee Security Awareness: Enhance employees' awareness of social engineering attacks through regular security training.

  • Implement Multi-layered Security Monitoring: Deploy multi-layered security monitoring tools on critical systems to detect and respond to abnormal behaviours in real-time.

Memory Trojan Threats in Enterprise Environments

Memory Trojans pose a severe threat to key business systems in enterprise environments. Below is a case analysis of a Memory Trojan attack on an enterprise: The ERP system of a manufacturing enterprise was hit by a Memory Trojan attack, disrupting production line operations and resulting in tens of millions in economic losses. Technical Analysis:

  • Attack Method: Attackers exploited unpatched vulnerabilities in the ERP system to successfully implant a Memory Trojan, remotely controlling the system through malicious code in memory, ultimately leading to system collapse.

  • Detection and Response: Due to the fileless nature of the Memory Trojan, the enterprise's traditional security measures failed to detect the attack in a timely manner, allowing attackers to remain latent in the system for several weeks.

Protection Suggestions:

  • Regular Vulnerability Scanning and Remediation: Ensure all business systems undergo regular vulnerability scans and timely patching of discovered security flaws.

  • Strengthen System Logs and Behaviour Monitoring: Discover and respond to abnormal behaviours in a timely manner through detailed logging and behaviour monitoring.

Handling Memory Trojans in Emergency Response

During the emergency response process, detecting and clearing Memory Trojans is a critical step. Below is a practical operation guide for emergency response: 1. Initial Detection: Use behaviour monitoring and memory forensics tools to identify suspicious memory activity. 2. Isolation and Control: Once the presence of a Memory Trojan is confirmed, immediately isolate the infected system to prevent the attack from spreading. 3. Clearance and Recovery: Extract and analyse the malicious code using tools like Volatility, determine the clearance strategy, and restore the system to a normal operational state. 4. Post-Incident Analysis: After clearing the Memory Trojan, deeply analyse the attack path, summarise lessons learned, and improve security protection measures.

▌Cutting-edge Technologies in Memory Trojan Protection

Latest Technologies Enhancing Memory Protection

Faced with continuously evolving Memory Trojan technologies, the latest technologies to enhance memory protection are gradually developing. These technologies include memory sandboxing, memory integrity protection, etc., designed to restrict the execution capability of malicious code in memory. Below is an example of a basic memory sandbox implementation:

In this example, the memory sandbox restricts execution to only permitted classes; if other classes attempt to run, an exception is thrown. This method can effectively prevent Memory Trojan implantation and execution.

Building an Automated Defence System

Building an automated defence system is an effective way to counter Memory Trojan attacks. Below is the basic architecture of an automated defence system:

  • Real-time Monitoring Module: Monitors memory and system behaviour, raising timely alerts upon detecting anomalies.

  • Response Execution Module: Automatically executes operations such as isolation, blocking, and clearance according to predefined policies.

  • Analysis and Learning Module: Continuously optimises protection policies by analysing historical attack data, improving the system's defensive capabilities.

Below is a simplified code example of an automated defence system architecture:

In this example, the MemoryMonitor module is responsible for monitoring system memory, the AnomalyDetector module analyses monitoring data and detects anomalies, and the ResponseHandler module automatically takes response measures when an anomaly is detected. This architecture can be expanded into more complex systems, combining multiple detection and response mechanisms to comprehensively defend against Memory Trojan attacks.

Future Memory Security Challenges

In the future, as attackers continue to explore new memory attack methods, defending against Memory Trojans will face more challenges. Potential new attack methods may include using AI to generate malicious code, executing memory attacks in IoT devices, etc. Therefore, security experts and enterprises must:

  • Remain Forward-looking: Continuously track new technologies and threats in the memory security field, and formulate protection strategies in advance.

  • Strengthen Cross-enterprise Collaboration: Establish cross-enterprise and cross-industry collaborative protection systems to jointly address emerging memory threats.

▌Building a Memory Trojan Defence System

Building a Comprehensive Memory Trojan Defence System

Building an effective Memory Trojan defence system requires comprehensive design across strategic, tactical, and operational levels. Below is an approach to building a Memory Trojan defence system:

  • Strategic Level: Clarify the core objectives of memory security, and formulate security policies and budgets.

  • Tactical Level: Deploy multi-layered security technologies, such as memory sandboxing, behaviour monitoring, and memory forensics tools.

  • Operational Level: Implement strict security operations and emergency response measures to ensure the effectiveness of the protective system.

Security Governance and Memory Trojan Management

Security governance plays a significant role in the Memory Trojan defence system. Below are some key measures for security governance:

  • Memory Security Policy Formulation: Establish clear memory security policies to standardise memory usage and access control.

  • Security Auditing and Assessment: Conduct regular audits and assessments of memory security measures to ensure their effectiveness.

  • Incident Reporting and Emergency Response: Establish a robust incident reporting mechanism to respond rapidly when a Memory Trojan attack is discovered.

Integration of Technology and Management

In defending against Memory Trojans, the combination of technical protection and management measures is particularly important. While leveraging technical means to enhance memory security, management measures are also required to ensure these technologies are effectively implemented. Enterprises can achieve the integration of technology and management through the following paths:

  • Security Culture Building: Improve employees' security awareness, ensuring every employee recognises the importance of memory security.

  • Process Standardisation: Establish standardised security operation procedures to ensure protection measures are strictly executed at every stage.

  • Continuous Improvement: Continuously improve and optimise protection measures based on actual defense outcomes to form a dynamic memory security protection system.

▶▶▶ For more detailed content, please download the "Blue Team Guide ④ [Memory Trojan Edition] In-depth Analysis: Memory Trojan Threats and Comprehensive Defence Strategies" to obtain the full report.

To learn more about the Cyax Security Metrics Validation Platform, please call our official number at 400-860-6366 or email mkt@validations.cn to contact us. We will be delighted to assist you.