Ringo Nguyen
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee
    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee
  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # Malware-Analysis **Table of Content** ```sh 1. Basic Static Analysis 2. Advanced Static Analysis 3. Basic Dynamic Analysis 4. Advanced Dynamic Analysis ``` ### Basic Static Analysis Objectives **Objectives** ```sh 1. Lab setup for malware analysis 2. Searching for strings in a malware 3. Fingerprinting malware through hashes 4. Signature-based detection mechanisms ``` --- ## 1. VM Setup ![Screenshot 2024-02-20 at 3.30.40 PM](https://hackmd.io/_uploads/B196nFz2a.png) >**You need to have at least 60GB for the VM to work, I allocated 125GB on mine.​ The FLARE VM is a Windows-based VM well-suited for malware analysis created by Mandiant (Previously FireEye). It contains some of the community's favorite malware analysis tools.** * **VirtualBox**: >###### Virtual machines offer an optimal platform for examining malware. Popular software such as Oracle VirtualBox and VMWare Workstation are utilized for creating and utilizing virtual environments. These tools enable the creation of snapshots that can be reverted to as needed, making them highly suitable for conducting malware analysis. * **FLARE VM GitHub page:** > ###### The FLARE VM, developed by Mandiant (previously FireEye), is a Windows-based virtual machine designed specifically for malware analysis. It comes preloaded with popular malware analysis tools favored by the community. Additionally, it offers customization options, allowing users to install their own tools onto the VM. FLARE VM is compatible with both Windows 7 and Windows 10 operating systems. For a comprehensive list of pre-installed tools and installation instructions, users can refer to the GitHub page or the Mandiant blog dedicated to the VM. Given its Windows-based nature, FLARE VM enables dynamic analysis of malware targeting Windows systems. ## Practice Session: ##### The following steps illustrate how Virtual Machines are employed for the analysis of malware: ```sh 1. Establish a new Virtual Machine with a fresh installation of the operating system. 2. Configure the machine by installing necessary analysis tools. 3. Capture a snapshot of the machine current state. 4. Import or download malware samples into the VM and conduct analysis. 5. Restore the machine to the previously saved snapshot once the analysis is finished. ``` #### 1. > ##### We needed to have at least 60GB for the VM to work, I allocated 125GB on mine.​The FLARE VM is a Windows-based VM well-suited for malware analysis created by Mandiant (Previously FireEye). It contains some of the community's favorite malware analysis tools. ​ ![Confi](https://hackmd.io/_uploads/HyEdWBMha.png) #### 2. ![Screenshot 2024-02-20 at 10.10.10 AM](https://hackmd.io/_uploads/rJL74rGh6.png) ![Screenshot 2024-02-20 at 10.10.21 AM](https://hackmd.io/_uploads/Hy7e4BG26.png) ![Screenshot 2024-02-20 at 10.10.32 AM](https://hackmd.io/_uploads/HJ6B4rG2a.png) #### 3. ![Screenshot 2024-02-20 at 10.26.42 AM](https://hackmd.io/_uploads/BJAUHrfha.png) #### 4. ![Screenshot 2024-02-20 at 10.52.10 AM](https://hackmd.io/_uploads/HkOIsHGhp.png) --- >https://www.youtube.com/watch?v=BiSdnusy2AQ >https://www.youtube.com/watch?v=AP9c-zBuh-0 ![Screenshot 2024-02-20 at 11.03.37 AM](https://hackmd.io/_uploads/Sy80aHf36.png) #### 5. ![Screenshot 2024-02-20 at 11.05.52 AM](https://hackmd.io/_uploads/rJVP0SGna.png) ![Screenshot 2024-02-20 at 11.05.59 AM](https://hackmd.io/_uploads/HycCCrzh6.png) ![Screenshot 2024-02-20 at 11.06.05 AM](https://hackmd.io/_uploads/rkLuAHf3T.png) --- ## 2. String Search * #### **How a string search works:** > ##### **A string search involves examining the binary data within a malware sample, disregarding its file format, to detect sequences of ASCII or Unicode characters followed by a null character. While this method identifies potential strings, not all such sequences are meaningful strings; some may represent memory addresses or assembly instructions. Consequently, string searches often yield false positives, appearing as irrelevant data. Analysts must distinguish valuable strings from irrelevant ones and disregard the latter.** * #### **Basic String Search:** > * ###### **Windows has its own tool called strings.exe, found in the FLARE VM software package. This tool is part of a set of tools created by Microsoft for examining Windows computers. It's already installed in the FLARE VM, so you can use it right away. One of the advantage of the command line version of strings is that it can save the results to a file, which makes it easier to study them later.** >* ###### **In the FLARE VM, you just need to run a command with the path to the malware file to start searching for hidden text.** >* ###### **The FLARE VM offers other tools for string searches. For instance, CyberChef, accessible through Desktop > FLARE > Utilities > Cyberchef, features a recipe for basic string searches. Similarly, PEstudio, found at Desktop > FLARE > Utilities > pestudio, includes a string search function along with additional details such as encoding, string size, offset in the binary, and hints regarding the string's purpose. PEstudio also incorporates a blacklist column to match strings against known signatures.** * #### **What to search for?** >###### **In conducting a string search, it's essential for an analyst to discern meaningful strings from irrelevant ones. It's helpful to understand what to focus on during this process. While a string search can yield valuable insights, certain artifacts can serve as Indicators of Compromise (IOCs) and prove particularly useful. These include:** ```sh 1. Windows Functions and APIs, like SetWindowsHook, CreateProcess, InternetOpen, etc. These provide insights into potential malware functionality. 2. IP Addresses, URLs, or Domains, which may indicate potential command and control (C2) communication. For instance, the killswitch domain of the Wannacry malware was detected through a string search. 3. Diverse strings, such as Bitcoin addresses or text employed in message boxes. This information aids in providing context for further malware analysis. ``` ## Practice Session: ##### The following steps illustrate Searching for strings in a malware: ![Screenshot 2024-02-20 at 12.10.12 PM](https://hackmd.io/_uploads/ryl46Lfnp.png) ![Screenshot 2024-02-20 at 12.10.23 PM](https://hackmd.io/_uploads/Hk1pRIznT.png) --- > ##### PEstudio also provides some additional information about the strings, like, the encoding, size of the string, offset in the binary where the string was found, and a hint to guess what the string is related to. It also has a column for a blacklist, which matches the strings against some signatures.​ ![Screenshot 2024-02-20 at 12.10.31 PM](https://hackmd.io/_uploads/BJL8TUG2a.png) --- > ##### Security researchers maintain databases of known malware and ransomware signatures, including their SHA-256 hashes. When a suspicious file is encountered, its hash can be compared against these databases to determine if it matches a known threat.​ ![Screenshot 2024-02-20 at 12.10.39 PM](https://hackmd.io/_uploads/HkKwRUf3p.png) --- > ##### The malware authors know this and don't want a simple string search to thwart their malicious activities. Therefore, they deploy techniques to obfuscate strings in their malware. Malware authors use several techniques to obfuscate the key parts of their code. These techniques often render a string search ineffective, i.e., we won't find much information when we search for strings. ![Screenshot 2024-02-20 at 12.10.46 PM](https://hackmd.io/_uploads/H1UCA8fna.png) --- > ##### Stack string is a code obfuscation technique that makes string data in a program harder to analyze. A region of memory used for local variables and function call information.Tight strings are a combination of encoded strings and stackstrings. They are made up of individual bytes that are constructed on the stack at runtime.​ ![Screenshot 2024-02-20 at 12.19.47 PM](https://hackmd.io/_uploads/SkIkeDfn6.png) ![Screenshot 2024-02-20 at 12.19.57 PM](https://hackmd.io/_uploads/SkHqyvMnT.png) --- ## 3. Fingerprinting ![Screenshot 2024-02-20 at 12.25.39 PM](https://hackmd.io/_uploads/ryk7Zwf2T.jp) >* ##### When analyzing malware, it's crucial to distinguish between different samples and identify them uniquely. Unlike file names, which can be easily duplicated or changed, a more reliable method is needed. This is where hash functions come in. A hash function takes input of any length and produces a fixed-length unique output, based on the contents of the file or data. This process is irreversible, meaning you can't recreate the original file from its hash. Hash functions ensure that even a small change in the file's content results in a completely different hash, making it highly unlikely for two files with different content to have the same hash. >* ##### File names don't affect the hash since they are not part of the file's content. Therefore, changing a file's name doesn't alter its hash. >* ##### Hashes serve various purposes in malware analysis, such as uniquely identifying malware samples, searching for them in repositories and databases, and serving as Indicators of Compromise (IOCs). Additionally, hashes are commonly used to securely store passwords for user authentication. * #### Commonly Employed Techniques for Calculating File Hashes: ```sh 1. Md5sum 2. Sha1sum 3. Sha256sum ``` >* ###### **The first two hashing algorithms are now deemed insecure or susceptible to collision attacks, where multiple inputs yield the same hash. Although the probability of a collision attack with these hash functions is low, it remains possible. Consequently, sha256sum is presently regarded as the most secure approach for computing file hashes. Within the provided virtual machine (VM), multiple utilities are available for computing file hashes.** * #### Imphash: >* ###### **short for "import hash," is a unique identifier derived from the imports of an executable file. Imports encompass the functions that an executable relies on from other files or Dynamic Link Libraries (DLLs). Imphash represents a hash of these imported functions and libraries, including their sequence within the sample. This feature aids in recognizing samples associated with the same threat groups or engaged in similar operations.** * #### Fuzzy hashes: >* ###### **also known as SSDEEP, offer another means to detect comparable malware. They operate as Context Triggered Piecewise Hashes (CTPH), wherein a file is segmented into sections, and the hashes of these segments are calculated. This process generates multiple inputs with similar byte sequences, even if the entire files differ.** ## Practice Session: ##### The following steps illustrate Fingerprinting malware through hashes: > Advanced ransomware variants encrypt files using different keys or algorithms for different sections of the file. This could result in different hash values for different sections of the encrypted file. Ransomware developers may use various techniques to obfuscate their code or dynamically generate parts of the payload. ​ ![Screenshot 2024-02-20 at 12.51.39 PM](https://hackmd.io/_uploads/B16F5wfha.png) --- >A slight change in the contents of a file would result in a different hash. However, some types of hashes can help identify the similarity among different files. https://bazaar.abuse.ch/browse.php?search=imphash%3A756fdea446bc618b4804509775306c0d ![Screenshot 2024-02-20 at 1.08.31 PM](https://hackmd.io/_uploads/S19biPfnp.png) ![Screenshot 2024-02-20 at 12.51.46 PM](https://hackmd.io/_uploads/rkoBqvfhT.png) ![Screenshot 2024-02-20 at 12.51.53 PM](https://hackmd.io/_uploads/BkuVcPG2a.png) --- ## 4. Signature-based detection > ##### **Signatures serve as a method to recognize specific content within a file. They can be likened to patterns embedded within the file's data. These patterns typically consist of byte sequences, regardless of their location within the file. Security experts commonly utilize signatures to pinpoint patterns within files, ascertain if a file is malicious, and discern suspected behavior and the malware family it may belong to.** #### Yara Rule: >###### **Yara rules, known as a versatile signature-based tool for malware researchers, facilitate the identification of binary and textual patterns within files. TryHackMe offers a dedicated room for exploring Yara rules. The security community maintains an open-source repository of Yara rules, providing valuable resources for analysis. However, it's crucial to consider context when interpreting rule matches, as some patterns may not indicate malicious content. Always consult the documentation for each rule for clarity on its intended use.** #### Capa: >###### **Capa is developed by Mandiant and available as an open-source tool, aids in discerning the capabilities within a PE file. By analyzing signatures such as imports, strings, and mutexes, Capa endeavors to identify the behavioral traits of the file.** >> * ###### **Capa correlates the identified capabilities with the MITRE ATT&CK framework and Malware Behavior Catalog (MBC). The final table displays the capabilities alongside the corresponding matched signatures and the number of hits for each capability. Additionally, Capa indicates the presence of obfuscated stackstrings in the sample, potentially suggesting the usefulness of running FLOSS against it. To access further details about the sample, users can employ the -v or -vv operator, which provide results in verbose or very verbose mode, respectively, revealing addresses associated with the identified capability.** ## Practice Session: ##### The following steps illustrate Signature-based detection mechanisms: ![Screenshot 2024-02-20 at 1.24.25 PM](https://hackmd.io/_uploads/SJK3ADzh6.png) ![Screenshot 2024-02-20 at 1.24.32 PM](https://hackmd.io/_uploads/B1DTCPz2a.png) ![Screenshot 2024-02-20 at 1.24.39 PM](https://hackmd.io/_uploads/HJIm1uz36.png) --- ### Advanced Static Analysis Objectives > ###### Advanced static analysis is a technique used to examine the code and structure of malware without running it. This helps in identifying the behavior and weaknesses of the malware, enabling the creation of antivirus signatures for its detection. Additionally, analyzing the code and structure helps researchers gain a deeper understanding of how the malware operates, leading to the development of new defense mechanisms against it. **Objectives** ```sh 1. Understand how advanced static analysis is performed.​ 2. Exploring Ghidra's disassembler functionality.​ 3. Understanding and identifying Ghidra disassembler ``` ### 1. Performing advanced static analysis >* **on malware is a vital procedure for comprehending its actions and recognizing potential risks. The primary aims of this approach include uncovering the malware's functionalities, pinpointing its attack routes, and recognizing its methods of evasion.** **The steps involved in conducting advanced static analysis are as follows:** ```sh 1. Determine the malware's entry point and observe the system calls it initiates. 2. Identify and scrutinize the various sections of the malware's code using tools like debuggers and hex editors. 3. Analyze the control flow graph of the malware to delineate its execution path. 4. Investigate the dynamic behavior of the malware by analyzing the system calls it makes during execution. 5. Utilize the gathered insights to comprehend the evasion techniques employed by the malware and assess the potential harm it can inflict. ``` --- ### 2. Ghidra Overview: * ##### Ghidra is a software reverse engineering tool that allows users to analyze compiled code to understand its functionality. It is designed to help analysts and developers understand how the software works by providing a platform to decompile, disassemble, and debug binaries.​ **Features:** >* ##### Decompilation: Ghidra provides the functionality to transform binary files into readable C code, simplifying the understanding of software operations for developers.** >* ##### Disassembly: Ghidra is capable of dissecting binary files into assembly language, allowing analysts to delve into the intricate details of the code's low-level functions. >* ##### Debugging: Ghidra offers an in-built debugger, empowering users to step through code and closely examine its behavior. >* ##### Analysis: Ghidra has the ability to automatically detect functions, variables, and other code components, assisting users in comprehending the overall structure of the code.** #### **Exploring the Ghidra Layout** >* ###### Program Trees: This feature displays different sections of the program, allowing users to click on each section to explore its contents. For a comprehensive understanding of headers and PE sections, users can refer to the Dissecting PE Headers room. >* ###### Symbol Tree: This component contains crucial sections such as Imports, Exports, and Functions, each offering extensive insights into the analyzed program. >* ###### Imports: This segment provides details about the libraries imported by the program. Clicking on each API call reveals the assembly code utilizing that specific API. >* ###### Exports: Here, users can find the API or function calls exported by the program. This section proves valuable when analyzing a DLL, as it lists all the functions contained within it. >* ###### Functions: This section presents the functions detected within the code. Clicking on each function leads to the disassembled code of that particular function. Additionally, it includes the entry function, which marks the beginning of the analyzed program. Functions labeled with generic names starting with FUN_VirtualAddress are those that Ghidra has not assigned specific names to. >* ###### Data Type Manager: This area displays various data types identified in the program. >* ###### Listing: This window showcases the disassembled code of the binary, presenting values in the following sequence: Virtual Address, Opcode, Assembly Instruction (e.g., PUSH, POP, ADD, XOR, etc.), Operands, and Comments. >* ###### Decompile: In this section, Ghidra translates assembly code into pseudo C code, offering users a clearer understanding of the assembly code during analysis. >* ###### Toolbar: This section provides various options for use during analysis. ## Practice Session: ##### The following steps illustrate exploring Ghidra's disassembler functionality: ![Screenshot 2024-02-20 at 2.05.58 PM](https://hackmd.io/_uploads/SyUJtOfha.png) ![Screenshot 2024-02-20 at 2.06.04 PM](https://hackmd.io/_uploads/r1UyK_fh6.png) ![Screenshot 2024-02-20 at 3.46.59 PM](https://hackmd.io/_uploads/H1iMlcfhT.png) ![Screenshot 2024-02-20 at 4.05.11 PM](https://hackmd.io/_uploads/Syp74cM3T.png) ![Screenshot 2024-02-20 at 4.06.23 PM](https://hackmd.io/_uploads/r1eK49M2p.png) ![Screenshot 2024-02-20 at 4.16.10 PM](https://hackmd.io/_uploads/r1HCIcGnT.png) >* ###### Program Trees: Shows sections of the program. We can click on different sections to see the content within each.​ >* ###### Symbol Tree: Contains important sections like Imports, Exports, and Functions. Each section provides a wealth of information about the program we are analyzing.​ ```sh 1. Imports: This section contains information about the libraries being imported by the program. Clicking on each API call shows the assembly code that uses that API.​ 2. Exports: This section contains the API/function calls being exported by the program. This section is useful when analyzing a DLL, as it will show all the functions dll contains. 3. Functions: This section contains the functions it finds within the code. Clicking on each function will take us to the disassembled code of that function. It also contains the entry function. Clicking on the entry function will take us to the start of the program we are analyzing. Functions with generic names starting with FUN_VirtualAddress are the ones that Ghidra does not give any names to. ``` >* ###### Data Type Manager: This section shows various data types found in the program. >* ###### Listing: This window shows the disassembled code of the binary, which includes the following values in order.​ ```sh 1. Virtual Address​ 2. Opcode​ 3. Assembly Instruction (PUSH, POP, ADD, XOR, etc.)​ 4. Operands​ 5. Comments​ ``` > * Decompile: Ghidra translates the assembly code into a pseudo C code here. This is a very important section to look at during analysis as it gives a better understanding of the assembly code. >* Toolbar: It has various options to use during the analysis.​ ![Screenshot 2024-02-20 at 4.40.33 PM](https://hackmd.io/_uploads/S1sOh9M2a.png) ![Screenshot 2024-02-20 at 4.41.55 PM](https://hackmd.io/_uploads/SkL6h5fnT.png) >https://isc.sans.edu/diary/A+few+Ghidra+tips+for+IDA+users+part+4+function+call+graphs/25032 --- ![Screenshot 2024-02-20 at 4.43.46 PM](https://hackmd.io/_uploads/B1Z9pcz2a.png) ![Screenshot 2024-02-20 at 4.48.40 PM](https://hackmd.io/_uploads/rJxuMoGhT.png) ![Screenshot 2024-02-20 at 4.49.09 PM](https://hackmd.io/_uploads/rk3OGsf2T.png) ![Screenshot 2024-02-20 at 4.53.36 PM](https://hackmd.io/_uploads/HJuFGiM2T.png) #### Here's a breakdown of the information:​
.text Section (Executable Code): ```sh 2. Name: ".text" 3. Virtual Address: 0x004001f8 4. Size of Raw Data: 0x0002b99f 5. Characteristics: IMAGE_SCN_CNT_CODE 6. .rdata Section (Read-only Data): 7. Name: ".rdata" 8. Virtual Address: 0x00400220 9. Size of Raw Data: 0x0001e800 10. Characteristics: IMAGE_SCN_CNT_INITIALIZED_DATA 11. .data Section (Initialized Data): 12. Name: ".data" 13. Virtual Address: 0x00400248 14. Size of Raw Data: 0x00002768 15. Characteristics: IMAGE_SCN_CNT_INITIALIZED_DATA 16. .rsrc Section (Resource Data): 17. Name: ".rsrc" 18. Virtual Address: 0x00400298 19. Size of Raw Data: 0x00000348 20. Characteristics: IMAGE_SCN_CNT_INITIALIZED_DATA 21. .reloc Section (Relocation Data): 22. Name: ".reloc" 23. Virtual Address: 0x004002c0 24. Size of Raw Data: 0x00002be8 25. Characteristics: IMAGE_SCN_CNT_INITIALIZED_DATA ``` >#### Each section in a PE file serves a specific purpose, such as storing executable code, read-only data, initialized data, resource information, and relocation data. The characteristics provide additional details about the section, such as whether it contains code or data. The PE header, describing the layout and characteristics of different sections within the executable. ![Screenshot 2024-02-20 at 5.10.03 PM](https://hackmd.io/_uploads/SJnUNsM3T.png) #### An undefined function typically occurs in situations​ ```sh 1. Incomplete or Obfuscated Code:​ 2. If the code is obfuscated or uses unconventional control flow patterns, Ghidra may struggle to identify the start of functions.​ a. Dynamic Code Generation:​ Programs that generate code dynamically during runtime can present challenges for static analysis tools, leading to undefined functions. 3. Complex Control Flow:​ Functions with complex or unusual control flow structures might not be easily recognized by the static analysis algorithms.​ ``` ![Screenshot 2024-02-20 at 5.18.10 PM](https://hackmd.io/_uploads/HkGSHsz2T.png) ![Screenshot 2024-02-20 at 5.19.44 PM](https://hackmd.io/_uploads/BJlFRHjG36.png) #### Code unit of x86 assembly instructions: ```sh 1. LEA EAX,[ESP + 0x2c]​ 2. JNC LAB_00405dcf​ 3. JNC LAB_00406545​ 4. JNC LAB_004065e6​ 5. JNC LAB_0040678f​ 6. CMP word ptr [EAX + 0x2],0x2a​ 7. PUSH ESI​ 8. PUSH ESI​ 9. PUSH ESI​ 10. PUSH ESI​ 11. PUSH param_2​ 12. PUSH EBX​ 13. PUSH ESI​ 14. PUSH ESI​ 15. CMP byte ptr [EBP + local_20+0x1],0xa​ 16. PUSH EBX​ 17. JNZ LAB_00424e01​ 18. PUSH EDI​ 19. DEC EAX​ 20. JNZ LAB_004285e0​ 21. MOVAPD XMM1,xmmword ptr [DAT_00434720]​ 22. MOVAPD XMM4,xmmword ptr [DAT_00434740]​ 23. MOVAPD XMM6,xmmword ptr [DAT_00434750]​ 24. MOVAPD XMM5,xmmword ptr [DAT_00434760]​ 25. MOVAPD XMM1,xmmword ptr [DAT_00434720]​ ``` ![Screenshot 2024-02-20 at 5.22.39 PM](https://hackmd.io/_uploads/ryZIUjM2T.png) ![Screenshot 2024-02-20 at 5.24.21 PM](https://hackmd.io/_uploads/H1m1vjzhT.png) ![Screenshot 2024-02-20 at 5.24.49 PM](https://hackmd.io/_uploads/B11ewiMn6.png) ![Screenshot 2024-02-20 at 5.25.53 PM](https://hackmd.io/_uploads/SkHfwoG26.png) #### Key aspects that a function graph in Ghidra can reveal:​ > * Basic Block Layout:Shows the sequence and connections between basic blocks within a function.​ > * Control Flow:​ Arrows depict how program execution flows between basic blocks.​ > * Function Entry/Exit:​ Clearly highlights where a function begins and ends.​ > * Conditional Branches/Jumps:​ Identifies decision points in the code where different paths may be taken.​ > * Loops:​ Recognizes repetitive patterns in basic blocks, indicating loop structures.​ > * Function Calls:​ Edges represent calls to other functions, allowing for tracing execution flow.​ > * Data Flow Analysis:​ Illustrates data flow between registers and memory locations.​ > * Anomalies/Abnormalities:​ Unusual patterns may indicate obfuscation, anti-analysis, or security concerns.​ > * Graph Navigation:​ Provides tools for easy exploration, zooming, and panning.​ > * Comments/Annotations:​ Allows analysts to add comments and annotations directly on the function graph.​ --- ![Screenshot 2024-02-21 at 3.13.42 PM](https://hackmd.io/_uploads/r19qtAXha.png) ![Screenshot 2024-02-21 at 3.14.26 PM](https://hackmd.io/_uploads/B1XAt0m2a.png) ```sh * MOV EAX, dword ptr [EBP + param_1]: Move the value at the memory address [EBP + param_1] into the EAX register.​ * MOV dword ptr [EDI + 0x30], EAX: Move the value in EAX into the memory location at [EDI + 0x30].​ * MOV EAX, dword ptr [EBP + param_2]: Move the value at the memory address [EBP + param_2] into the EAX register.​ * MOV dword ptr [EDI + 0x34], EAX: Move the value in EAX into the memory location at [EDI + 0x34].​ * LEA EAX, [EDI + 0x18]: Load the effective address of [EDI + 0x18] into EAX.​ * PUSH EAX: Push the value of EAX onto the stack.​ * PUSH EDI: Push the value of EDI onto the stack.​ * PUSH FUN_00401123: Push the address of the function FUN_00401123 onto the stack.​ * PUSH ECX: Push the value of ECX onto the stack.​ * CALL ___vcrt_EventRegister: Call the function ___vcrt_EventRegister with the arguments pushed onto the stack.​ * MOV ESI, EAX: Move the return value of the function call into the ESI register.​ * ADD ESP, 0x10: Adjust the stack pointer to remove the pushed arguments.​ * TEST ESI, ESI: Test the value of ESI.​ * JZ LAB_00401044: Jump to the label LAB_00401044 if ESI is zero (zero flag is set). ``` --- ![Screenshot 2024-02-21 at 3.18.20 PM](https://hackmd.io/_uploads/BJx3qCXnT.png) ![Screenshot 2024-02-21 at 3.19.32 PM](https://hackmd.io/_uploads/S1BlsA7hT.png) ![Screenshot 2024-02-21 at 3.20.16 PM](https://hackmd.io/_uploads/BkIEsR736.png) > * This assembly code defines a function FUN_00401000. It starts by setting up the stack frame, checking conditions, and performing operations based on those conditions. The function involves moving values between registers and memory locations, calling another function (___vcrt_EventRegister), and making conditional jumps. --- ![Screenshot 2024-02-21 at 2.54.47 PM](https://hackmd.io/_uploads/S1_IHA73T.png) #### Parameter Adjustment:​ * ##### If the second parameter (param_2) is zero, it is set to the value of the first parameter (param_1) plus 0x20.​ ```sh 1. Memory Writes: * The function writes the values of param_3 and param_4 to specific memory locations (param_1 + 0x30 and param_1 + 0x34, respectively).​ 2. Event Registration: * The function calls the ___vcrt_EventRegister function with several parameters, including param_2, FUN_00401123, param_1, and param_1 + 0x18. The result is stored in uVar1.​ 3. Conditional Execution:​ * If the result (uVar1) of the event registration is zero, it calls another function FUN_0040105d with specific parameters.​ * If the result is greater than zero, it modifies uVar1 by performing a bitwise OR operation with 0x80070000.​ 4. Return:​ * The function returns the final value of uVar1.​ ``` --- ![Screenshot 2024-02-21 at 2.54.57 PM](https://hackmd.io/_uploads/rkM0IAmnp.png) ![Screenshot 2024-02-21 at 2.55.04 PM](https://hackmd.io/_uploads/S1O-P07nT.png) ![Screenshot 2024-02-21 at 2.55.13 PM](https://hackmd.io/_uploads/By5Hw0Xhp.png) ![Screenshot 2024-02-21 at 2.55.21 PM](https://hackmd.io/_uploads/BJfhU0m2a.png) #### Here's a breakdown:​ * #### Function Signature: ```sh undefined __stdcall entry(void) This indicates that entry is a function with no specified return type (undefined), and it follows the __stdcall calling convention. ``` * #### Assumed FS Offset: ```sh assume FS_OFFSET = 0xffdff000 This statement indicates that the function assumes a specific offset for the FS (Frame Segment) register. FS is often used for thread-local storage, and setting this offset is part of the function's assumptions.​ ``` * #### Return Type: ```sh undefined AL:1 <RETURN> The function has an undefined return type (undefined), and it suggests that the return value might be present in the AL (accumulator) register, taking up 1 byte.​ ``` * #### Function Body: ```sh 00410b65 e8 e1 04 00 00 CALL ___security_init_cookie​ 00410b6a e9 80 fe ff ff JMP FUN_004109ef​ The function body starts with a call to ___security_init_cookie. This is likely a security-related initialization routine.​ Following the call, there's an unconditional jump (JMP) to another function labeled FUN_004109ef. This jump serves as a flow override, indicating that control will be transferred to the specified function.​ ``` * #### Flow Override: ###### -- Flow Override: CALL_RETURN (CALL_TERMINATOR) ```sh This comment indicates that the flow override at the end of the function involves a call-return mechanism, suggesting a function call (CALL) followed by a return (JMP) to another function. In summary, this part of the disassembly is describing the entry point of the program (entry function). It involves security-related initialization (___security_init_cookie) and a jump to another function (FUN_004109ef) after the initialization. The use of __stdcall suggests a specific calling convention used in Windows API functions. ``` --- ![Screenshot 2024-02-21 at 2.55.28 PM](https://hackmd.io/_uploads/r10M90Qha.png) ![Screenshot 2024-02-21 at 3.19.46 PM](https://hackmd.io/_uploads/SkGDjR7np.png) ![Screenshot 2024-02-21 at 3.19.57 PM](https://hackmd.io/_uploads/Sk_120X3p.png) ![Screenshot 2024-02-21 at 3.20.03 PM](https://hackmd.io/_uploads/Hy6enAQ2a.png) * ##### Function Signature: ```sh Name: FUN_004109ef​ Calling Convention: __stdcall (standard calling convention where parameters are pushed onto the stack in reverse order and the callee is responsible for cleaning up the stack)​ ``` * ##### Return Type:​ ```sh The function returns an integer (int), and the result is stored in the EAX register.​ ``` * ##### Function Body: ```sh The function begins with some prologue code, which includes pushing values onto the stack and making a call to __SEH_prolog4 (Structured Exception Handling prolog).​ The function initializes the C runtime environment by calling ___scrt_initialize_crt and checks the result in the AL register.​ There is a conditional jump (JNZ) to the label LAB_00410a0e if the zero flag is not set (indicating a non-zero value in AL).​ ``` * ##### Stack Variables: ```sh The function uses local variables stored on the stack.​ local_8 is at offset -0x8 on the stack.​ local_1d is at offset -0x1d on the stack.​ local_28 is at offset -0x28 on the stack.​ ``` * ##### Function Flow:​ ```sh The function has references (XREF) to specific points in the code where it is being called, including a reference from the entry point.​ ``` * ##### Code Flow Control: ```sh The conditional jump (JNZ) indicates that the function might take different paths based on the result of the test (TEST instruction on AL).​ ``` --- ![Screenshot 2024-02-21 at 3.20.10 PM](https://hackmd.io/_uploads/HJM4pAXha.png) * #### Code Flow: ```sh There is a label named LAB_00410a07, which is referenced by a jump instruction (JZ) at the end of the code block (00410a29). This creates a loop where the code jumps back to LAB_00410a07 if the zero flag is set (i.e., the result of the CMP instruction indicates equality).​ ``` * #### Loop Logic:​ ```sh The loop initializes with the instruction PUSH 0x7 and proceeds to clear the BL register with XOR BL, BL. This value is then stored in the byte at the address [EBP + local_1d] (effectively clearing a byte in the local variable).​ ``` * #### Memory Operations: ```sh The instruction AND dword ptr [EBP + local_8], 0x0 performs a bitwise AND operation, effectively clearing the contents of the dword at the address [EBP + local_8].​ ``` * #### Function Calls:​ ```sh The code makes a call to ___scrt_acquire_startup_lock after clearing certain memory locations.​ ``` * #### Variable Modifications:​ ```sh The byte at [EBP + local_28] is set to the value in the AL register.​ The code checks a condition involving a comparison of the value at the address [DAT_0044d2e0] and the value in the ECX register.​ ``` * #### Loop Termination: ```sh The loop terminates if the result of the CMP instruction indicates equality (JZ jumps if zero).​ ``` --- ![Screenshot 2024-02-21 at 3.20.17 PM](https://hackmd.io/_uploads/B1P02CXh6.png) ![Screenshot 2024-02-21 at 3.20.24 PM](https://hackmd.io/_uploads/BJNelJV3p.png) ![Screenshot 2024-02-21 at 3.20.31 PM](https://hackmd.io/_uploads/r1VypAX3a.png) ![Screenshot 2024-02-21 at 3.20.38 PM](https://hackmd.io/_uploads/ryYeaAX2a.png) * #### Push Value:​ ```sh The value 0x7 is pushed onto the stack.​ ``` * #### Function Call: ```sh The ___scrt_fastfail function is called with the argument 0x7. This function likely handles or logs a fast failure condition. ``` * #### Test and Jump: ```sh The result of the function call is tested (TEST EAX, EAX).​ If the result is non-zero (not zero), the program jumps to the address LAB_00410a78.​ ``` * #### Move and Jump:​ ```sh If the result is zero, the value -2 (0xfffffffe) is moved to the memory location [EBP + local_8].​ The value 0xff is moved to the EAX register.​ The program unconditionally jumps to the address LAB_00410b5f.​ ``` --- ![Screenshot 2024-02-21 at 3.20.45 PM](https://hackmd.io/_uploads/Sy0kT0Xna.png) * #### Function Call: ```sh The code pushes the value 0x7 onto the stack.​ Calls the function ___scrt_fastfail with the argument 0x7. This function likely handles or logs a fast failure condition. ``` * #### Test and Jump: ```sh Tests the result of the function call by checking the EAX register. If the result is non-zero (not zero), the program jumps to the address LAB_00410a78. ``` * #### Move and Call Initialization Function: ```sh * If the result is zero, it moves the value of ECX to the memory location [DAT_0044d2e0].​ * Pushes DAT_0042d2e0 and DAT_0042d2bc onto the stack.​ * Calls the function __initterm_e with these arguments. This function likely initializes some terms during program startup.​ * Pops ECX twice from the stack.​ * Tests the result (TEST EAX, EAX) and jumps to LAB_00410a5b if zero.​ ``` * #### Initialization and Jump:​ ```sh * Pushes DAT_0042d2b8 and DAT_0042d260 onto the stack.​ * Calls the function __initterm with these arguments, likely involving further initialization.​ * Pops ECX twice from the stack.​ * Moves the value 0x2 to the memory location [DAT_0044d2e0].​ * Unconditionally jumps to the address LAB_00410a7d.​ * this code block seems to be involved in handling initialization routines and fast failure conditions during program startup.​ ``` --- ![Screenshot 2024-02-21 at 3.50.32 PM](https://hackmd.io/_uploads/SyxdMkE26.png) * ##### This part of the code appears to be related to the handling of fast failure conditions:​ ```sh Move Register:​ Moves the value in register CL to register BL with the instruction MOV BL, CL.​ Move to Memory:​ Moves the value in register BL to the byte at the memory location [EBP + local_1d] with the instruction MOV byte ptr [EBP + local_1d], BL.​ ``` --- ![Screenshot 2024-02-21 at 3.50.39 PM](https://hackmd.io/_uploads/Skh6fkE26.png) ![Screenshot 2024-02-21 at 3.50.46 PM](https://hackmd.io/_uploads/HkXl7JV36.png) * #### Push Value onto Stack:​ ```sh Pushes the value at the memory location [EBP + local_28] onto the stack with the instruction PUSH dword ptr [EBP + local_28].​ ``` * #### Function Call - Release Startup Lock: ```sh Calls the function ___scrt_release_startup_lock with the value popped from the stack as an argument. This function is likely related to releasing a lock during startup.​ ``` * #### Pop Value from Stack:​ ```sh Pops a value from the stack into the ECX register with the instruction POP ECX.​ ``` * #### Function Call - FUN_00411153:​ ```sh Calls the function FUN_00411153 and moves the result into the ESI register.​ ``` * #### Comparison and Jump:​ ```sh Compares the dword at the memory location pointed to by ESI with zero (EDI). If the comparison is true (zero), it jumps to the address LAB_00410aad.​ ``` --- ![Screenshot 2024-02-21 at 3.50.53 PM](https://hackmd.io/_uploads/Hy1Z7JV3a.png) ![Screenshot 2024-02-21 at 3.50.59 PM](https://hackmd.io/_uploads/ry_BQk4hp.png) * #### Push Register onto Stack:​ ```sh Pushes the value in the ESI register onto the stack with the instruction PUSH ESI.​ ``` * #### Function Call - FUN_004103ec:​ ```sh Calls the function FUN_004103ec with the value popped from the stack as an argument. The result of this function call is not explicitly used or stored.​ ``` * #### Pop Register from Stack: ```sh Pops a value from the stack into the ECX register with the instruction POP ECX.​ ``` * #### Test AL Register:​ ```sh Performs a test on the AL register, setting the zero flag based on the result.​ ``` * #### Conditional Jump:​ ```sh Jumps to the address LAB_00410aad if the zero flag is set (indicating that the result of the test on the AL register was zero).​ ``` --- ![Screenshot 2024-02-21 at 3.51.06 PM](https://hackmd.io/_uploads/Sy6rmkV2p.png) * #### Push Registers onto Stack:​ ```sh Pushes the values in the EDI and 0x2 registers onto the stack with the instructions PUSH EDI and PUSH 0x2 respectively. ``` * #### Duplicate EDI Value:​ ```sh Pushes the value of the EDI register onto the stack again with the instruction PUSH EDI.​ ``` * #### Move Value from Memory to Register:​ ```sh Moves the double-word (4 bytes) value from the memory address pointed to by ESI into the ESI register with the instruction MOV ESI, dword ptr [ESI]. ``` * #### Move Value from Register to Register:​ ```sh Moves the value in the ESI register into the ECX register with the instruction MOV ECX, ESI. ``` * #### Function Call - _guard_check_icall:​ ```sh Calls the function _guard_check_icall with the values on the stack as arguments.​ ``` * #### Indirect Call - ESI:​ ```sh Calls the function located at the address stored in the ESI register with the instruction CALL ESI. ``` --- ![Screenshot 2024-02-21 at 3.51.12 PM](https://hackmd.io/_uploads/rJdImyNhp.png) * #### Function Call - FUN_00411159:​ ```sh Calls the function FUN_00411159 with no arguments.​ ``` * #### Move Value to Register:​ ```sh Moves the return value of the function (presumably an address) into the ESI register with the instruction MOV ESI, EAX.​ ``` * #### Compare Value in Memory with Register:​ ```sh Compares the double-word (4 bytes) value at the memory address pointed to by ESI with the value in the EDI register with the instruction CMP dword ptr [ESI], EDI. ``` * #### Jump if Zero (JZ): ```sh Jumps to the destination address LAB_00410acb if the zero flag is set, indicating that the values in memory and EDI are equal. ``` --- ![Screenshot 2024-02-21 at 4.06.45 PM](https://hackmd.io/_uploads/BJKM8J4np.png) * #### Function Call - FUN_004103ec: ```sh Calls the function FUN_004103ec with an argument retrieved from ESI.​ Saves the value of the ECX register and restores it after the call.​ ``` * #### Test Result - TEST AL, AL:​ ```sh Tests the low byte (AL) of the EAX register for zero.​ If the result is zero (ZF flag is set), it means the function result was zero, and the program proceeds to the next instruction. ``` * #### Jump if Zero (JZ) - LAB_00410acb:​ ```sh Jumps to the destination address LAB_00410acb if the zero flag is set.​ ``` * #### Function Call __register_thread_local_exe_atexit_callback: ```sh 1. Calls the function __register_thread_local_exe_atexit_callback with an argument retrieved from ESI.​ 2. Saves the value of the ECX register and restores it after the call.​ ``` --- ![Screenshot 2024-02-21 at 4.06.52 PM](https://hackmd.io/_uploads/ryprv1E26.png) * #### Function Call (FUN_004103ec): ```sh 1. The value in the ESI register is pushed onto the stack (PUSH ESI).​ 2. The function FUN_004103ec is called, and the result is stored in the AL register.​ ``` * #### Test and Jump:​ ```sh 1. The AL register is tested for zero (TEST AL, AL).​ 2. If the result is zero (JZ), the control flow goes to LAB_00410acb.​ ``` * ### Function Calls (FUN_00414722 and ___scrt_get_show_window_mode):​ ```sh 1. In LAB_00410acb:​ 1. The EDI register is pushed onto the stack (PUSH EDI).​ 2. FUN_00414722 is called, and the result is stored in the ECX register.​ 3. ___scrt_get_show_window_mode is called, and the result is stored in the AX register.​ ``` * #### Data Manipulation and More Function Calls:​ ```sh 1. The lower word of EAX (AX) is moved to EAX (MOVZX EAX, AX).​ 2. The value in EAX is pushed onto the stack (PUSH EAX).​ 3. The function __get_wide_winmain_command_line is called.​ 4. The value in EAX is again pushed onto the stack (PUSH EAX).​ ``` * #### Additional Function Calls:​ ```sh 1. FUN_00402d70 and FUN_004147be are called with appropriate parameters.​ ``` * #### Conditional Jump (JNZ):​ ```sh 1. The result of is_managed_app is tested, and if it's non-zero, the control flow goes to LAB_00410b04.​ ``` --- ![Screenshot 2024-02-21 at 4.06.59 PM](https://hackmd.io/_uploads/SJZLPyE3T.png) * #### Function Call (__SEH_epilog4): ```sh The function __SEH_epilog4 is called using CALL __SEH_epilog4.​ This function likely performs cleanup related to Structured Exception Handling (SEH).​ ``` * #### Return (RET):​ ```sh The RET instruction is encountered, indicating the end of the function.​ The control flow returns to the calling function.​ ``` --- ![Screenshot 2024-02-21 at 4.07.06 PM](https://hackmd.io/_uploads/HkBUD1E2a.png) --- ### *Summary code from the decompile of “FUN_004109ef” ​* * ##### The code appears to be part of the initialization and startup routine of a program. While the code itself doesn't explicitly exhibit malicious behavior, several characteristics may be of interest from a malware analysis perspective:​ > **Code Obfuscation:** ```sh The code includes function calls with names like ___scrt_initialize_crt, ___scrt_fastfail, ___scrt_acquire_startup_lock, and others, which could be attempts to obfuscate or hide the true functionality. ``` > **Dynamic Behavior:​** ```sh The function appears to perform various initialization steps, including acquiring and releasing startup locks, initializing certain data, and calling several functions. The dynamic nature of these operations may be an attempt to make analysis more challenging.​ ``` > **Control Flow Complexity**:​ ```sh There are conditional jumps (JNZ, JZ) based on the results of tests (TEST, CMP). This kind of control flow complexity is sometimes used in malware to make static analysis more difficult. ``` > **Function Call Sequences**: ```sh The sequence of function calls involves initialization routines, thread-related operations, and checks. This could be typical in the startup routine of a program but might also be designed to confuse analysts.​ ``` > **Use of Function Pointers**:​ ```sh The code involves function pointer calls, such as CALL ESI, where the destination address is loaded from a memory location. This kind of indirect call can make the code harder to analyze statically. ``` > **Exit Points and Process Termination:** ```sh There are calls to functions like _exit and __cexit, which are associat. ``` --- ![Screenshot 2024-03-15 at 9.37.41 AM](https://hackmd.io/_uploads/SJDUy0WRa.png) Decompile code​ ``` ​ /* WARNING: Function: __SEH_prolog4 replaced with injection: SEH_prolog4 */​ /* WARNING: Function: __SEH_epilog4 replaced with injection: EH_epilog3 */​ ​ int FUN_004109ef(void)​ ​ {​ code *pcVar1;​ bool bVar2;​ bool bVar3;​ undefined4 uVar4;​ int iVar5;​ code **ppcVar6;​ uint *puVar7;​ undefined4 uVar8;​ undefined4 uVar9;​ ​ uVar4 = ___scrt_initialize_crt(1);​ if ((char)uVar4 != '\0') goto LAB_00410a0e;​ do {​ ___scrt_fastfail();​ LAB_00410a0e:​ bVar2 = false;​ uVar4 = ___scrt_acquire_startup_lock();​ } while (DAT_0044d2e0 == 1);​ if (DAT_0044d2e0 == 0) {​ DAT_0044d2e0 = 1;​ iVar5 = __initterm_e((undefined **)&DAT_0042d2bc,(undefined **)&DAT_0042d2e0);​ if (iVar5 != 0) {​ return 0xff;​ }​ __initterm((undefined **)&DAT_0042d260,(undefined **)&DAT_0042d2b8);​ DAT_0044d2e0 = 2;​ }​ else {​ bVar2 = true;​ }​ ___scrt_release_startup_lock((char)uVar4);​ ppcVar6 = (code **)FUN_00411153();​ if ((*ppcVar6 != (code *)0x0) && (uVar4 = FUN_004103ec((int)ppcVar6), (char)uVar4 != '\0')) {​ uVar9 = 0;​ uVar8 = 2;​ uVar4 = 0;​ pcVar1 = *ppcVar6;​ _guard_check_icall();​ (*pcVar1)(uVar4,uVar8,uVar9);​ }​ puVar7 = (uint *)FUN_00411159();​ if ((*puVar7 != 0) && (uVar4 = FUN_004103ec((int)puVar7), (char)uVar4 != '\0')) {​ __register_thread_local_exe_atexit_callback(*puVar7);​ }​ FUN_00414722((HMODULE)0x0);​ ___scrt_get_show_window_mode();​ __get_wide_winmain_command_line();​ iVar5 = FUN_00402d70((HINSTANCE)&DAT_00400000);​ FUN_004147be((HMODULE)0x0);​ bVar3 = is_managed_app();​ if (bVar3) {​ if (!bVar2) {​ __cexit();​ }​ ___scrt_uninitialize_crt('\x01','\0');​ return iVar5;​ }​ /* WARNING: Subroutine does not return */​ _exit(iVar5);​ } ``` * Initialization:​ The function begins by pushing the value 0x14 onto the stack and calling ___scrt_initialize_crt.​ It checks the result with a TEST and JNZ (jump if not zero) instructions. If the result is non-zero, it jumps to LAB_00410a0e.​ * Fast Fail:​ If the result is zero, it proceeds to call ___scrt_fastfail. This function is likely related to handling critical errors or abnormal conditions.​ * Acquiring Startup Lock:​ It XORs BL with itself (XOR BL, BL), then calls ___scrt_acquire_startup_lock and stores the result in byte ptr [EBP + local_28].​ * Initialization Checks and Jump:​ It compares the result of the previous function call with ECX and jumps to LAB_00410a07 if they are equal.​ Further checks and jumps are made, including a jump to LAB_00410a78 if certain conditions are met.​ * Release Startup Lock: If the conditions are not met, it releases the startup lock using ___scrt_release_startup_lock.​ * Function Calls:​ There are several function calls, including FUN_00411153, FUN_004103ec, FUN_00411159, and others.​ * Exit Handling:​ The function ends with calls to exit-related functions such as __cexit, ___scrt_uninitialize_crt, and an SEH (Structured Exception Handling) epilog, followed by a RET instruction.​ --- # Phase 2: ## Basic Dynamic Analysis #### Basics Dynamic Analysis Objective 1. **Sandboxing and malware analysis:** * Creating separated environments for safe software testing.​ 2. **Setting up a sandbox:** * Creating a specific environment using virtualization and monitoring tools.​ 3. **Using ProcMon to monitor processes:** * Real-time tracking of system events and file access.​ 4. **Identifying malware API calls:** * intercepting and evaluating API usage to discover malicious behavior.​ 5. **Detecting process alterations with ProcExp:** * Examining process details for evidence of malicious interference.​ 6. **Tracking registry changes using Regshot:** * Take registry snapshots to evaluate malware-induced changes.​ --- **Pre-requisites:** Before starting this room, it is recommended that you complete the following rooms for a better understanding of the content in this room 1. **Introduction to Windows API:** Understanding the Fundamental Features of the Windows Application Programming Interface. 1. **Windows Internals:** Understanding the internal functions and structure of the Windows operating system. 1. **Introduction to Malware Analysis:** Learn the principles of analyzing harmful software for identification and prevention. 1. **Basic Static Analysis:** Learning how to examine software without executing it, which is critical for security and debugging. --- ## What is Basic Dynamic Analysis? ##### Dynamic analysis refers to the process of evaluating a program's performance while it is actively running. Often referred to as dynamic code scanning, this methodology is instrumental in pinpointing and resolving bugs, memory concerns, and application crashes as they arise during execution. ​ ##### * By conducting analysis in real-time, it enables more effective diagnosis and prompt correction of issues encountered during the program's operation.​ ## Definition of sandbox ##### A sandbox serves as a controlled environment for testing new code alterations and experimental features, segregating them from the main production environment or code repository. ​ * ##### This concept is commonly utilized in software development, encompassing areas like web development, automation, and version control. * ##### Additionally, the notion of a "sandbox" extends to computing and networking, referring to various forms of isolated spaces such as security sandboxes and search engine sandboxes. * ##### These isolation areas aim to shield live systems from potential disruptions caused by incoming data until specific conditions or criteria are fulfilled. --- ### In order to establish a sandbox, the following components are generally required: 1. An isolated system, preferably a virtual machine, disconnected from live or production networks, specifically designated for malware analysis. ​ 2. The capability for the isolated or virtual machine to preserve its initial clean state and revert to that state upon completion of malware analysis. * This feature, often referred to as creating and reverting a snapshot, is essential to prevent contamination from prior malware infections during the analysis of subsequent samples. ​ 3. Monitoring tools to analyze malware behavior while it operates within the virtual environment. * These tools may be automated, as observed in automated sandbox setups, or manual, necessitating analyst intervention during analysis. * Further exploration of these tools will be undertaken later in this context. ​ 4. A file-sharing mechanism enabling the introduction of malware into the virtual machine and facilitating the transfer of analysis data or reports. * Typically, shared directories or network drives serve this purpose. * However, caution must be exercised to ensure that the shared directory remains unmounted while executing malware, as malicious software may infect all accessible files. * This precaution is particularly critical in cases involving ransomware, which could potentially encrypt all shared drives or directories.​ --- ## Virtualization: * Commercial and free virtualization tools a are Oracle's VirtualBox and VMware's Player and Workstation. ​ * These applications empower users to create Virtual Machines (VMs) that operate independently from their local system. ​ * VMware Player lacks the capability to create snapshots, which are indispensable for dynamic malware analysis. Consequently, it is deemed unsuitable for such security tasks. ​ * Both VMware Workstation and VirtualBox offer snapshot functionality, rendering them appropriate choices for malware analysis. While VirtualBox is provided free of charge, VMware Workstation requires a paid license.​ * In addition to these desktop-focused solutions, server-based virtualization software such as XenServer, QEmu, and ESXi facilitate virtualization on dedicated servers.​ * This setup is frequently adopted by enterprises to fulfill their virtualization requirements. Similarly, security research entities often leverage analogous technologies to establish VM farms, enabling large-scale virtualization initiatives.​ --- ## ProcMon Process Monitor is a Windows tool designed to monitor system issues by providing real-time views of registry, filesystem, process, and network activity. * * It originated from the merging of two tools: RegMon (Registry Monitor) and Filemon (File Monitor), developed by Mark Russinovich and Bryce Cogswell. * Similar tools to Process Monitor today include SpyStudio.exe, Sysmon.exe, Procexp.exe, and perfmon.exe. - Sysadmins utilize Process Monitor for troubleshooting operating system issues. --- ## Instructions for ProcMon Installation: 1- Begin by downloading the latest version of Process Monitor. visit the website at https://learn.microsoft.com/en-us/sysinternals/downloads/procmon Click on the "Download Process Monitor" ![Screenshot 2024-03-18 at 10.21.20 PM](https://hackmd.io/_uploads/By0RLd80T.jpg) 2- Next, right-click on the ProcessMonitor.zip file and select open. Proceed to extract its contents into the same folder. ![Screenshot 2024-03-18 at 10.24.50 PM](https://hackmd.io/_uploads/SJNpPuLC6.jpg) 3- Following extraction, you will find a ProcessMonitor folder containing TXT, CHM, and EXE files. Click on the the Procmon.exe, and Process Monitor should start immediately. ![Screenshot 2024-03-18 at 10.23.33 PM](https://hackmd.io/_uploads/SyB0PuLAa.jpg) * Note: These screenshots belong mac operating system to demonstrate how to install ProcMon, however, it is not working on MacOS. The same procedure can be applied on Windows OS to install ProcMon.​ --- ![Screenshot 2024-03-18 at 8.13.19 PM](https://hackmd.io/_uploads/r1dSK8LCp.png) --- ![Screenshot 2024-03-18 at 8.50.09 PM](https://hackmd.io/_uploads/BkyPbw80T.png) --- ![Screenshot 2024-03-18 at 8.50.38 PM](https://hackmd.io/_uploads/ByJF-vURT.png) --- ![Screenshot 2024-03-18 at 8.51.13 PM](https://hackmd.io/_uploads/B10qZvIAa.png) --- ## Advanced Filtering: Preset filters are readily visible within ProcMon, such as the one designed to filter out Procmon.exe. ​ * Implementing filters is straightforward: users select filtering values such as Process Name, specify its relation, value, and action. When the checkbox is activated, the filter takes effect; otherwise, it remains inactive. ​ * In the provided screenshot, the first filter is not currently active. However, the second filter specifies that if the Process Name is Procmon.exe, then exclude that event from reporting. ​ * Consequently, events associated with Procmon.exe are absent from view. ​ ![Screenshot 2024-03-18 at 10.30.53 PM](https://hackmd.io/_uploads/HJwiYuLA6.png) --- ## Process Tree:​ ProcMon offers the capability to visualize all current processes arranged in a hierarchical parent-child relationship, thus creating a process tree. ​ * This feature is accessible by clicking the icon in the menu. It aids in identifying the parent processes and their corresponding children. ​ ![Screenshot 2024-03-18 at 10.34.58 PM](https://hackmd.io/_uploads/ry-bcuIRT.png) --- ## API Logger: The API Logger serves as a user-friendly tool, offering rudimentary details regarding the APIs accessed by a specific process.​ To initiate the API Logger on the provided VM, follow these steps: 1. Navigate to the directory ~Desktop\Tools\Utilities\ApiLogger.exe. ​ 2. Execute the ApiLogger.exe application. ​ ![Screenshot 2024-03-18 at 10.36.59 PM](https://hackmd.io/_uploads/SyAF5O8RT.png) * Click on the highlighted three-dot menu to open a new process. ![Screenshot 2024-03-18 at 10.40.43 PM](https://hackmd.io/_uploads/HyzuidLRa.png) * Utilize the file browser that appears to select the executable for monitoring API calls.​ ​ ![Screenshot 2024-03-18 at 10.40.43 PM](https://hackmd.io/_uploads/S1wTjdICp.png) * After selecting the executable, click 'Inject & Log' to initiate the API logging process. View the log of API calls in the lower pane.​ * Monitor running processes and their corresponding Process IDs (PIDs) in the upper pane.​ ![Screenshot 2024-03-18 at 10.45.13 PM](https://hackmd.io/_uploads/B10I3d8R6.png) In the 'msg' field, basic information about the API called is displayed alongside the PID of the monitored process. ​ * To log API calls of a currently running process, one can click on the 'PID' menu in the API logger. ​ * This action opens the following window:​ ![Screenshot 2024-03-18 at 10.47.50 PM](https://hackmd.io/_uploads/B18gpOIAp.png) ## API Monitor:​ API Monitor offers more comprehensive insights into a process's API calls. It is available in both 32-bit and 64-bit versions to accommodate the respective architectures of processes.​ To launch API Monitor, users can navigate to either of the following paths:​ * For the 64-bit version: ~Desktop\Tools\Utilities\apimonitor-x64.exe​ * For the 32-bit version: ~Desktop\Tools\Utilities\apimonitor-x86.exe​ ![Screenshot 2024-03-18 at 10.49.06 PM](https://hackmd.io/_uploads/SkgLpOLAp.png) ##### API Monitor features several tabs, as numbered in the provided image: ![Screenshot 2024-03-18 at 10.50.21 PM](https://hackmd.io/_uploads/Skuq6dLCT.png) 1. API Group Filter: Allows selection of the API group to monitor, such as 'Graphics and Gaming' or 'Internet' related APIs. Only APIs from the chosen group will be displayed. 2. Monitored Processes: Displays the processes currently being monitored for API calls. Clicking 'Monitor New Process' initiates monitoring for a new process. 3. API Calls: Provides details about each API call, including the API call itself, Module, Thread, Time, Return Value, and any errors. Users can monitor this 4. Running Processes: Lists the running processes that API Monitor can monitor. 5. API Parameters: Shows the parameters of the API call, including their values before and after the API call. 6. Hex Buffer: Displays the hexadecimal buffer of the selected value. 7. Call Stack: Presents the call stack of the process. 8. Output: Shows the output of API Monitor.​ --- Upon clicking the 'Monitor New Process' option in Tab 2, users encounter the following prompts: ![Screenshot 2024-03-18 at 10.52.03 PM](https://hackmd.io/_uploads/ryVeRdLCT.png) * In this menu, users can select the process from a specified path, input any arguments required by the process, designate the directory from which to initiate the process, and choose the method for attaching API Monitor. ​ After opening a process, the tabs are populated with relevant information, as depicted in the following image:​ ![Screenshot 2024-03-18 at 10.53.44 PM](https://hackmd.io/_uploads/ryvPAuLR6.png) * In Tab 1, all values are selected to monitor all API calls. * In Tab 2, the path of the monitored process is displayed. * In Tab 3, a summary of API calls is presented. The highlighted API call, RegOpenKeyExW, indicates an attempt to open a registry key. Additionally, the 'Return Value' field indicates an error, with further error details available in the 'Error' field. * Tab 5 displays the parameters of the API call before and after its execution. * Tab 6 showcases the selected value in hexadecimal format. * Tab 7 exhibits the call stack of the process.​ --- ## Process Explorer Process Explorer, part of the Sysinternals Suite, serves as an advanced alternative to the Windows Task Manager. This potent tool facilitates the identification of process hollowing and masquerading techniques. * To access Process Explorer, navigate to ~Desktop\Tools\Utilities\procexp.exe. Upon opening Process Explorer, the interface resembles the screenshot below:​ ![Screenshot 2024-03-18 at 10.55.52 PM](https://hackmd.io/_uploads/SyLk1KU0p.png) The provided screenshot displays a comprehensive view of all system processes arranged in a tree format. ​ * Additionally, it includes details such as CPU utilization, memory usage, Process IDs (PIDs), Description, and Company name for each process.​ ![Screenshot 2024-03-18 at 10.56.58 PM](https://hackmd.io/_uploads/BJuVJt8Ca.png) * Enabling the lower pane view from the 'View' menu provides users with additional information about the processes. * Upon activation, the lower pane displays details as depicted in the following screenshot.​ --- ![Screenshot 2024-03-18 at 10.58.30 PM](https://hackmd.io/_uploads/BkgSlFICT.png) - Upon selecting a process in the upper pane, the lower pane provides detailed information about that process.​ - Handles offer insight into the resources utilized by the process. - The presence of handles opened for another process or thread in another process can indicate potential code injection into that process. - Additionally, the lower pane's other tabs display DLLs and threads associated with the selected process.​ ![Screenshot 2024-03-18 at 11.03.07 PM](https://hackmd.io/_uploads/B12KxY8Ca.png) --- * For additional details about a selected process, accessing the process properties is an option. ​ * This can be done by right-clicking on the process name in the process tree and selecting 'Properties'. Upon opening the properties of a process, the interface resembles the image below:​ ![Screenshot 2024-03-18 at 11.04.24 PM](https://hackmd.io/_uploads/ryY0gt8Cp.png) --- ## Process Masquerading:​ The properties function, as illustrated in the screenshot above, provides extensive information about a process across its various tabs. ​ * The 'Image' tab, featured in the screenshot, aids analysts in overcoming this evasion tactic. * Clicking the 'Verify' button on this tab allows analysts to determine if the executable associated with the running process is signed by the relevant organization, typically Microsoft for Windows binaries. * In the provided screenshot, the Verify option has been selected, revealing the text '(No signature was present in the subject) Microsoft Corporation' at the top. * This indicates that although the executable purports to be from Microsoft, it lacks digital signing by Microsoft, suggesting it is masquerading as a Microsoft process, which could signify malicious intent. * It's important to note that this verification process only applies to the Image of the process stored on the disk. * If a signed process has been hollowed, with its code replaced by malicious code in memory, a verified signature for that process may still be obtained. ![Screenshot 2024-03-18 at 11.06.04 PM](https://hackmd.io/_uploads/rkpEbFLRp.png) --- ## Process Hollowing:​ Process Hollowing is a technique utilized by malware to disguise its presence by exploiting an already active legitimate process. ​ * In this method, the malware binary removes all code from the memory of the legitimate process and injects malicious code in its place. ​ * As a result, despite appearing as a legitimate process to analysts, it runs the malicious code authored by the malware creator.​ * Process Explorer helps in identifying this technique.​ --- Upon accessing the 'Strings' tab within a process's properties, users will find information resembling the screenshot below:​ ![Screenshot 2024-03-18 at 11.07.48 PM](https://hackmd.io/_uploads/BJIjbYL06.png) * At the bottom of the screenshot, there are options labeled 'Image' and 'Memory'. * When 'Image' is selected, Process Explorer displays strings found in the disk image of the process. ​ * Conversely, choosing 'Memory' allows Process Explorer to extract strings from the process's memory. * Under normal circumstances, the strings in the Image of a process should closely resemble those in the Memory since the same process is loaded into memory. ​ * However, if a process has been hollowed out, there will be a noticeable difference between the strings in the Image and those in the process's memory. ​ * This discrepancy indicates that the process loaded into memory differs significantly from the one stored on disk.​ --- ## Regshot Regshot is a tool designed to detect alterations to the registry (or selected file system). ​ * It proves invaluable in identifying registry key creations, deletions, or modifications during dynamic malware analysis. * Regshot operates by capturing snapshots of the registry before and after malware execution, subsequently comparing the two snapshots to pinpoint any differences. To launch Regshot in the attached VM, navigate to ~Desktop\Tools\Utilities\Regshot-x64-Unicode.exe.​ ![Screenshot 2024-03-18 at 11.09.45 PM](https://hackmd.io/_uploads/r1CMGFLR6.png) * Upon opening the Regshot-x64-Unicode.exe., selecting the "Scan dir1" option enables scanning for alterations in the file system. * However, we will solely focus on registry changes in this context.  ![image](https://hackmd.io/_uploads/BkGQftICa.png) * To commence, clicking on the '1st shot' option prompts a choice between taking a shot or taking a shot and saving it. ​ ![image](https://hackmd.io/_uploads/ry0tbtI0T.png) * Once the initial shot is captured, the interface resembles the screenshot below: ![image](https://hackmd.io/_uploads/rJAc-YUCp.png) * After saving a snapshot of the registry, we proceed to run the malware. * Once we've executed it and are sure it has carried out its malicious tasks, we'll capture a second snapshot by selecting the '2nd shot' option. ![image](https://hackmd.io/_uploads/rydrZF8Aa.png) ![image](https://hackmd.io/_uploads/SkpS-Y8Ap.png) * Having obtained both snapshots, we can now compare them to detect any registry alterations made by the malware. * This is achieved by selecting the 'Compare' option, which will display a summary resembling the screenshot below. ![image](https://hackmd.io/_uploads/SkDHlF806.png) * We observe that the summary displays additions, deletions, and modifications to both Keys and Values in the registry.  * Additionally, it highlights changes to Files and Folders, although no alterations are noted in this instance as we had deactivated the 'Scan dir1' option during snapshot capture. * If we enabled this feature and specified directories for monitoring, we would have received detailed information regarding filesystem modifications made by the malware within those selected directories. ![image](https://hackmd.io/_uploads/r1RLeFUAp.png) * For now, let's proceed to review the outcomes of our execution. * By selecting Compare > Output, Regshot furnishes us with the registry modifications, depicted in the screenshot below. ![image](https://hackmd.io/_uploads/rkUrh_UAT.png) * In the provided output, you'll find the date and time stamps of the shots taken by Regshot, alongside the computer name, username, and Regshot version.  * Below this information, there's a comprehensive list detailing the registry modifications. This begins with the Keys that were deleted following the keys tha were added. ![image](https://hackmd.io/_uploads/BJS6huIC6.png) **Advantages and Limitations of Regshot in Malware Analysis** * Regshot does not require continuous execution during malware analysis, unlike other tools like ProcExp, ProcMon, or API Monitor. - * Regshot captures snapshots before and after malware execution, eliminating the need for continuous monitoring during execution. * This approach makes Regshot immune to detection evasion techniques employed by certain malware samples. * However, Regshot lacks filtering mechanisms present in other tools, potentially leading to false positives if background processes interfere with the analysis. --- ## Advanced Dynamic analysis **Advanced Dynamics Objectives:** * The evasion techniques used to evade basic dynamic analysis. * Introduction to debuggers and how they can help us control the execution flow of malware. * Manipulating execution flow at runtime by changing registers or other parameters. * Patching malware to force it to move past the evasion techniques and onto the actual malicious content. **Advanced Dynamic Analysis Explanation** * Advanced dynamic analysis refers to a sophisticated approach to examining systems or processes that involves analyzing their behavior over time. Here are some key points about advanced dynamic analysis: * Time-dependent examination: It involves studying how a system or process evolves over time, rather than focusing solely on its static properties. * Complex system understanding: It aims to gain a deeper understanding of complex systems by observing how they respond to various inputs, stimuli, or changes. * Simulation and modeling: Advanced dynamic analysis often utilizes simulation tools and mathematical models to predict the behavior of a system under different conditions. * Identification of patterns and trends: By analyzing data collected over time, patterns, trends, and anomalies can be identified, helping in understanding system dynamics. **Pre-requisites:** To get the best learning outcome from this room, it is recommended that you complete the following rooms: ![image](https://hackmd.io/_uploads/HkPkm_L0p.png) **The Need for Advanced Dynamic Analysis:** Analyzing malware is like a cat-and-mouse game. Malware analysts keep devising new techniques to analyze malware, while malware authors devise new techniques to evade detection. This task will review some techniques that hamper our efforts to analyze malware using static or basic dynamic analysis. **Evasion of Static Analysis:** We learned techniques to perform static analysis on malware. Malware often hides or tries to look like legitimate software to evade the prying eyes of a malware analyst. Because we are not executing the malware during static analysis, the main focus of evading static analysis is to obfuscate the true functionality of the program until the program is executed. **The following techniques can be commonly used to achieve this:** * Altering the hash: As previously discussed, each file possesses a distinct hash. Exploiting this characteristic, malware creators modify their malicious code slightly to change its hash, thereby circumventing detection mechanisms based on hashes. Even a minor alteration, like adding a NOP instruction, can effectively defeat hash-based detection, unless dealing with Context-Triggered Piecewise Hashes or fuzzy hashes. * Evasion of AV signatures: Anti-virus signatures and other detection methods relying on static patterns within malware are often defeated by malware authors who manipulate these patterns to evade detection. This tactic is frequently accompanied by overall obfuscation of the malware's code. * String obfuscation: Certain malware authors encode the strings within their malicious code, decoding them only during runtime execution. Consequently, when searching for strings within the static analysis of the malware, the analyst may find no meaningful information. Malware creators might obfuscate critical strings, such as URLs and C2 domains, to prevent detection based on a single-string search. * Dynamic loading of DLLs during runtime: To avoid detection during static analysis, malware authors commonly utilize the LoadLibrary or LoadLibraryEx functions of Windows libraries to load DLLs dynamically at runtime. This approach can obscure the full set of functions linked to the malware when analyzed solely through its headers. * Packing and Obfuscation: Malware authors frequently employ packing techniques, likened to wrapping a present. Packed malware conceals its true nature, requiring unpacking to reveal the actual malicious code. Packets, resembling wrappers, decode the malware during runtime execution. Consequently, static analysis may not unveil the content of the packer, but when executed, the malware unpacks, loads the malicious code into memory, and executes it. **Evasion of Basic Dynamic Analysis:** Malware authors do not just accept their fate and let dynamic analysis detect their samples. For evasion of dynamic analysis, a host of techniques are employed. These techniques generally depend on identifying whether the malware runs in a controlled analysis environment. **The following techniques can be commonly used to achieve this:** * Detection of Virtual Machines (VMs): While some of these methods may be less effective today due to the widespread use of VMs in enterprise infrastructure, malware creators commonly attempt to discern if the malware is operating within a VM. This involves scrutinizing registry keys or device drivers linked to popular virtualization software like VMWare and Virtualbox. Similarly, indications of minimal resources, such as a single CPU and limited RAM, may suggest VM presence. In such cases, the malware may adopt an alternative non-malicious execution path to deceive analysts. * Timing Attacks: Malware frequently employs timing strategies to evade automated analysis systems. For instance, upon execution, the malware may attempt to prolong its activity by utilizing the Windows Sleep library to sleep for an extended period, causing automated analysis systems to shut down prematurely, leaving no traces of malicious activity. Although newer malware analysis systems can detect and mitigate such attacks by shortening the sleep time, malware can counteract these measures by conducting targeted timing checks. This involves noting the time of execution and comparing it with the current time after the sleep call. * Traces of User Activity: Malware seeks to identify traces of user activity on the machine. If minimal or no traces are detected, the malware may conclude that it is running in a controlled environment and opt for a different, benign execution path. Indicators of user activity may include the absence of mouse or keyboard movements, lack of browser history, no recently opened files, and limited system uptime. * Identification of Analysis Tools: Malware can query the Windows OS for a list of running processes using functions like Process32First and Process32Next. If it identifies popular monitoring tools in the list of running processes, such as ProcMon or ProcExp, the malware may switch to a benign execution path. Another method involves inspecting the names of open windows; if the malware detects tools like Ollydbg or ProcMon in the system, it may alter its execution path accordingly. ## Introduction to Debugging * Debuggers provide a malware analyst with the control desired to monitor a running program more closely, looking at the changes in different registers, variables, and memory regions as each instruction is executed. * A debugger also allows a malware analyst to change the variables' values to control the program's flow at runtime, providing greater control over the execution path the malware follows. **Types of Debuggers** ![image](https://hackmd.io/_uploads/rJx3rdI0a.png) For malware analysis, there are many options to choose a debugger from. These options include Windbg, Ollydbg, IDA, and Ghidra. We will be using x32dbg and x64dbg. **What is X32dbg?** * x32dbg is a free and open-source debugger for Windows. * It is primarily used for reverse engineering, malware analysis, and software debugging. * x32dbg provides a user-friendly graphical interface. * It offers features such as disassembly, debugging, memory manipulation, and breakpoint management. * The debugger is scriptable through its plugin system. * Widely used by security researchers, malware analysts, and software developers. * Helps analyze and understand the behavior of binary executables. * Used to identify vulnerabilities and malicious code. ## Familiarization With a Debugger The attached VM is essentially a FLARE VM, distributed by Mandiant (previously FireEye, now part of Google), widely used for reverse engineering malware. It includes all the tools required for our analysis in this room. To start, we can navigate to Desktop > Tools > debuggers > x32dbg.exe to run the debugger. We will be greeted with the following interface. ![image](https://hackmd.io/_uploads/ryfPIu8Cp.png) To open a file in the debugger, we can navigate to File > Open and open our desired file. The below screenshot shows the interface with a sample opened in the debugger. ![image](https://hackmd.io/_uploads/S18u8O8CT.png) We are currently seeing the CPU tab in the interface. Please note that we must use x32dbg for 32-bit samples and x64dbg for 64-bit samples. ![image](https://hackmd.io/_uploads/SJP6Uu806.png) As we can see in the bottom left corner, the execution of the program is paused because a System breakpoint has been reached. We can control whether to execute one instruction at a time or the whole program. ![image](https://hackmd.io/_uploads/H1eE0Iu8Ca.png) We can see Disassembly in the middle pane, with the Instruction pointer pointing to the next instruction executed if we start the program. ![image](https://hackmd.io/_uploads/S1sC8d8Cp.png) In the right pane, we can see the registers and their values. We can note that the value in EIP is the address EIP is pointing to in the disassembly pane. ![image](https://hackmd.io/_uploads/Byiyw_8R6.png) Similarly, on the bottom pane, we can see the stack view (right), the dump view (left), and the timer showing the time we spent debugging the sample (right corner). ![image](https://hackmd.io/_uploads/ByqewuU0a.png) Let's look at some of the other tabs. The breakpoints tab shows the status of breakpoints. Breakpoints are points where the execution of the program is paused for the analyst to analyze the registers and memory. A breakpoint on a specific instruction can be enabled by clicking the dot in front of that instruction in the CPU tab. ![image](https://hackmd.io/_uploads/S137PO8RT.png) Memory Map: This shows what data is stored in memory and the addresses where that data resides. In the example below the ‘.text’ section of the malware being analyzed is located at the address ’00DD1000’. The ‘Protection’ column also shows if that area in memory is executable, readable or writable. These can be identified by the flags E, R and W. This will come in handy when I explain how to use the memory map to unpack a piece of malware. ![image](https://hackmd.io/_uploads/SkFEwu8CT.png) Call Stack: This is handy when a breakpoint has been set on a specific Windows function. In a previous image, I had a breakpoint set on ‘CreateDirectoryW’ so each time the malware begins to create a directory on a compromised device, this breakpoint will be hit and x64dbg will stop on this function. Using the call stack, I can see what code written by the malware author called ‘CreateDirectoryW’ and identify where that directory is being created and what it will be called. ![image](https://hackmd.io/_uploads/r1-Lw_LRa.png) The threads running in the program are shown in the threads tab. ![image](https://hackmd.io/_uploads/H1-YvuIA6.png) Any handles to files, processes, or other resources the process accesses are shown in the handles tab. ![image](https://hackmd.io/_uploads/r1Q9vOLAa.png) ## Debugging in Practice In the debugger window, we have some features that help us control the execution. In the below screenshot, we can see some of them highlighted. ![image](https://hackmd.io/_uploads/BkPCvuLRa.png) Among these, from left to right, we have the feature for opening a new file, restarting the execution of the opened file from the start, and stopping the execution. The arrow key will execute the program until it is stopped or paused by some other control (Please do not press this button right now as it might freeze the program. If you did, kindly restart the program by terminating it through the Task Manager). Then we have the pause option. The last two options are for stepping into and stepping over. The rest of the options are also useful, but for the scope of this room, we will only be using the ones mentioned above. So now that we know how to control the execution, let's execute the program using the arrow key (Please only press it once). When we do that, we can see in the bottom right corner that the program's status changes to Running, then Paused. Along with the status, we have the reason for pausing the execution. It says "INT3 breakpoint “entry breakpoint"....". This means that we have hit a entry breakpoint, and the debugger was programmed to break execution on entry breakpoint. ![image](https://hackmd.io/_uploads/Bkpe_O8Ra.png) In the debugger, we can set where to put automatic breakpoints on a program by going to the Options > Preferences menu. The following screenshot shows the different points where breakpoints are automatically placed. We can see that TLS Callbacks and System TLS Callbacks are checked, which means execution will be broken on these events. ![image](https://hackmd.io/_uploads/S1TZudL06.png) ![image](https://hackmd.io/_uploads/HybM_d8RT.png) Controlled Execution Start: Entry breakpoint halts malware execution at the beginning for controlled analysis. Behavioral Observation: Enables scrutiny of initialization, unpacking, module loading, and communication establishment. Therefore, it will be prudent to single-step each instruction while we are in the callback. We can do that by clicking the step-into option we discussed above. After stepping into every instruction, we see the EIP moving to the next instruction, and the values in the registers and stack change accordingly. After stepping in a few instructions, we reach a push instruction. In the pane below the disassembly, we can see that the debugger tells us that the jump is not taken. The registers pane shows that the ZF is set, so the jump is not taken. ![image](https://hackmd.io/_uploads/r1BXdOICp.png) Comparison operation (cmp) between a double word (32-bit) value located at the memory address calculated by adding the value stored in the eax register to the hexadecimal offset F85CAC and the value stored in the esi register. ![image](https://hackmd.io/_uploads/Sy-E_dI0T.png) **00F81A75:** This is the memory address where the instruction is located. **39B0 AC5CF800:** This represents the hexadecimal machine code for the instruction. cmp dword ptr ds:[eax+F85CAC],esi: This is the assembly language representation of the operation. It compares the value at the memory address [eax + F85CAC] with the value in the esi register. The dword ptr specifies that the memory operand is a double word (32 bits) in size. The ds segment register is used to access the data segment of memory. Conditional jump instruction (jb), which stands for "jump if below" or "jump if not above or equal". ![image](https://hackmd.io/_uploads/HJMt__IRT.png) **00F81A96:** This is the memory address where the instruction is located. **72 DD:** This represents the hexadecimal machine code for the instruction. **jb F81A75:** This is the assembly language representation of the jump instruction. It means that if the condition (in this case, "below") is met, the control flow will be transferred to the memory address F81A75. Otherwise, the execution continues with the next instruction. ## Executing Malware Restart the debugger ![image](https://hackmd.io/_uploads/BkI7YO8Cp.png) Breakpoint reached at address 77C31A73 ![image](https://hackmd.io/_uploads/BJy4Yu80T.png) **What is Breakpoint?** In x32dbg, a breakpoint is a designated point in the program's execution where the debugger pauses or suspends the execution of the program. When a breakpoint is set at a specific memory address or line of code, the debugger interrupts the program's execution when it reaches that point, allowing the user to inspect the program's state, variables, registers, and memory contents. Breakpoints are essential for debugging because they allow developers to analyze the program's behavior and identify issues or bugs. Run the program in the debugger ![image](https://hackmd.io/_uploads/r13LKO8AT.png) The header entry point of the malware execution. ![image](https://hackmd.io/_uploads/BJ0vY_8R6.png) * 00EF0B65 is the memory address where the instruction is located. * E8 E1040000 is the instruction itself. * call <7ev3n.sub_EF104B> is the operation performed by the instruction. * This specific instruction call is invoking a subroutine located at the memory address <7ev3n.sub_EF104B>. When this instruction is executed, the control flow of the program jumps to the specified subroutine to execute its code. Go to Memory Map view ![image](https://hackmd.io/_uploads/SJY9FOUAT.png) Scroll down until you see the highlighted address (00EE1000). ![image](https://hackmd.io/_uploads/BJfiKd80T.png) ER (Execution-Related) protection refers to a feature that helps protect the debugging environment and prevent unwanted changes to the execution flow of the debugged application. ER protection mechanisms can include preventing the modification of critical registers, controlling access to certain system resources, and safeguarding against unauthorized changes to the program's execution state. These protections help ensure the integrity of the debugging process and prevent malicious interference with the debugging environment. Click run again ![image](https://hackmd.io/_uploads/ByrTF_LC6.png) This message will appear. ![image](https://hackmd.io/_uploads/HJGRtOICp.png) All your data is been hold for ransom unless your pay them with bitcoin under to the specific address or else they will be threatening to destroyed your files. Suggestion is never pay for ransomware they will continue to ask for more and hold your file for hostage. Click on “Symbols” tab ![image](https://hackmd.io/_uploads/SyrGqO8Aa.png) Why there are so many DLL running when executing 7ev3n? **What is DLL?** * ".dll" refers to Dynamic Link Libraries, which are files containing code and data that can be used by multiple programs simultaneously. * Dependency Analysis: Malware often relies on DLLs to perform various functions. Analyzing the dependencies of a malware sample can provide insight into its capabilities and behavior. * Code Injection: Malware may inject code into legitimate system DLLs or load malicious DLLs into legitimate processes to evade detection or execute malicious functionality. * Hooking and API Monitoring: Malware may hook into DLLs to intercept and manipulate system calls or monitor API calls for malicious activity. * Execution Flow: Analyzing the execution flow of a malware sample may involve tracing its interactions with DLLs to understand how it achieves its objectives and communicates with external entities. * Behavioral Analysis: Monitoring the behavior of DLLs loaded by a malware sample can reveal malicious activities such as file manipulation, network communication, or privilege escalation. * Resource Sharing: DLLs can contain resources such as icons, images, and text strings, which can be shared among multiple applications. This helps to reduce the size of individual executable files and simplify maintenance. * Persistence Mechanisms: Malware may install itself as a DLL or create malicious DLLs to establish persistence on a compromised system. * Anti-Analysis Techniques: Malware authors may use techniques such as DLL sideloading or DLL hijacking to evade detection by security tools or hinder analysis efforts. --- ### References: * https://github.com/mandiant/flare-vm/tree/main​ * https://github.com/mandiant/capa/blob/master/README.md​ * https://otx.alienvault.com/indicator/file/7DEBB7345BCFFDF1C5328F51524EE16B​ * https://github.com/Da2dalus/The-MALWARE-Repo​ * https://isc.sans.edu/diary/A+few+Ghidra+tips+for+IDA+users+part+4+function+call+graphs/25032​ * https://tryhackme.com/room/advancedstaticanalysis​ * https://tryhackme.com/room/staticanalysis1​ * https://www.youtube.com/watch?v=AP9c-zBuh-0​ * https://www.youtube.com/watch?v=KNe4hTVhpPQ&t=285s​ * https://www.youtube.com/watch?v=BiSdnusy2AQ​

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully