# 🦠Malware Analysis - Malicious Software Investigation Procedure

## Intro

> Malware analysis is the process of examining malicious software to understand its behaviour, origin, and impact. 

N.B. Safety is the most important aspect, as improper handling can lead to infections or data breaches. 
It is crucial for identifying threats, developing defences, and improving incident response, helping cybersecurity professionals protect systems and data from attacks.

### ⚠️ Appropriate Malware Handling

The most vulnerable time during any malware analysis is when malware is in transit.
moving malware from one machine to another can be dangerous and may pose the risk of accidental detonation. 
There are a number of steps that can be taken to reduce this risk as prevention of not possible

1. Changing the File Type extension - changing a windows executable (.exe) to something inert like ".thisisnotmalware" can ensure that detonating this will not result in an infection
2. Ensure all malware samples are contained within an Archived Zipped file and also password protect these Zip File - (Standard Password: infected)

### 🧪Lab Setup

When preforming Analysis of an executable it is important to ensure your tooling is established and ready to analyse the malware 
In some cases malware may attempt to delete itself, if this is the case we require active tools to detect why this was the case and later attempt to debug it.

Have the following tools running prior to execution:
- System Informer
- Process Monitor capture mode enabled
- Reg Shot (with first snapshot taken)
- Wireshark (On the REMnux machine) in monitoring mode `wireshark &`

Follow the following process when investigating malware:
1. Ensure both machines are on the host only adapter
2. Ensure the REMnux machine is set as the DNS server of the Flare VM
3. Ensure that the REMnux machine is pingable by the Flare VM 
4. Ensure that both VM's are not internet accessible 
5. After Config, ensure a snapshot is taken of both machine as a pristine state

---

### Breakdown
Malware Analysis is Always broken down to the four main processes

- Basic Static Analysis 
	This involves investigating the statically available IOC’s of a malicious File 
	Such as: Strings, Dll’s, Libraries etc. 
- Basic Dynamic Analysis
	This involves detonating the malicious file to obtain the available IOC’s 
	Such as: Second Stage Payloads, Connections (Host based Indicators/Network Based Indicators)
- Advanced Static Analysis 
	This involves decompiling the malicious file to investigate the assembly.
- Advanced Dynamic Analysis 
	This involves running the malicious file through a debugger to investigate the potential anti-analysis nature of the file.

Static and dynamic malware analysis are two fundamental techniques used in cybersecurity to examine and understand the behaviour of malware. Here's a brief comparison of the two:

1. **Static Malware Analysis:**
- **Method:** Analyses the malware without executing it. This involves examining the code, binaries, and other static properties of the malware to understand its potential behaviour.
- **Tools:** Disassemblers (like IDA Pro), debuggers (like OllyDbg), and hexadecimal editors.
- **Advantages:** Safe as the malware does not run; can reveal malware intended to avoid detection when active; good for initial quick assessments.
- **Disadvantages:** Less effective against sophisticated malware that uses obfuscation and encryption to hide its true intent; cannot see runtime behaviours.

1. **Dynamic Malware Analysis:**  
- **Method:** Involves executing the malware in a controlled environment (often a virtual machine) to observe its behaviour during runtime.
- **Tools:** Sandboxes (like Cuckoo Sandbox), system monitoring tools (like Process Monitor), and network traffic analyzers (like Wireshark).
- **Advantages:** Can observe actual behaviour as it happens; effective in analysing polymorphic and encrypted malware; can capture system-level interactions and network traffic.
- **Disadvantages:** Riskier as it involves running the malware; sophisticated malware may detect the analysis environment and alter its behaviour.

---

## 1️⃣ Basic Static Analysis 

The process of basic static analysis does not include the detonation of the executable/malware as in the process of **Static** this involves analysing the file without detonation

### 🧠 Gathering Information
First steps when conducting **Static Analysis** is to gather the information surrounding the file itself such as:

SHA256 File Hash:
MD5 File Hash:
Original File Name:
Current File Name:
File Size:
File Type: 

We can use the following command to assist in extracting the file hash:
```powershell
get-filehash <INSERT FILE NAME> -alg sha256sum
```
^ This will extract the SHA256 hash value of the given file

```powershell
get-filehash <INSERT FILE NAME> -alg md5sum
```
^ This will extract the MD5 hash value of a given file

The above commands are relative to the PowerShell command line alternative methods are utilised with processes such as CMD.

### 🔍Performing Open Source Intelligence (OSINT) 

Whenever possible, it’s easier to obtain information from existing file analysis services than to manually perform the lengthy process of malware analysis. 
Many providers already host and analyze previously submitted files.

Here are some great sources of Malware Analysis Intelligence Providers:
- **[VirusTotal](https://www.virustotal.com/)** - Aggregates results from 70+ AV engines, sandboxes, and threat intel feeds.  
- **[Hybrid Analysis](https://www.hybrid-analysis.com/)** - Free sandbox analysis by CrowdStrike Falcon Sandbox; great for dynamic behavior reports.  
- **[Joe Sandbox](https://www.joesandbox.com/)** - Advanced multi-platform sandboxing with in-depth static and dynamic analysis.  
- **[ANY.RUN](https://any.run/)** - Interactive malware sandbox for dynamic analysis; allows manual control during execution.  
- **[MalwareBazaar](https://bazaar.abuse.ch/)** - Threat intel repository by Abuse.ch for downloading and researching malware samples

This will provide a high level overview of the executable and or if it has ever been seen previously.
See the Image below if an example malicious file:
![[Pasted image 20250318071614.png]]

> ⚠️ Please exercise caution when uploading files to these sites as the results are publicly visible!  

### 🪢Identifying strings within malware 

what are strings? - Within programming strings are just a bunch of characters that together make up a word.
In the context of malware analysis, these strings may be a domain, an IP, etc. 

In turn these strings have been embedded into the executable and can be easily analysed if not properly obfuscated. 
These strings may include information used to exfiltrate data or download a second stage payload.

 To extract these **Strings** from an executable we can utilise many tools to assist, one common one is FLOSS.
 
 Which can be utilised as below
```bash
floss <INSERT FILE NAME>
```
^ This will present a dump of all identified strings greater than four characters

Use pestr to extract ASCII and Unicode strings from malware in the command line
```text
pestr <filename> | more
```
> By default, strings extracts only ASCII-encoded strings

```text
pestr <filename> --encoding=1 | more
```
> extract Unicode strings

- The string %s?i=%s&c=%s&p=%s resembles a URL pattern
- string that ends with \CurrentVersion\Run could be a reference to the registry key
- Look for file extensions (.tmp, .exe), this could indicate file creation activity
- Look for user agent strings (Mozilla/4.0), this could indicate web connection attempts

Comparing these Strings to other indicator identified throughout the investigation may prove to be crucial for identifying hardcoded indicators (which isn't always the case)

### Breaking down the structure of an executable 

This poses the question, what does an executable or a portable executable look like, 
we know what a text file or a power shell script look like but what is an executable .

In simple terms it is a compiled bunch of bytes, and breaking this down may reveal some information crucial to an investigation.
To break down an executable we can use a tool called **PEview**. 

`PEview` is a tool used primarily in Windows environments to examine the details of Portable Executable (PE) files. These files include executable (.exe), dynamic link libraries (.dll), and other file types used by the Windows operating system.
In the context of malware analysis, tools like PEview are used in static analysis to quickly assess the composition and potential capabilities of a suspicious file without executing it. By examining the PE structure, analysts can identify signs of malware, such as unusual sections, unexpected imports, or exports, and other indicators of compromise.

To use [[PEview]] we can download it from [HERE](http://wjradburn.com/software/PEview.zip)
This is a Graphical Tool and not Command line based (which we love) so upon running this tool it will immediately ask you for an executable to examine.

Select which PE to exam and it will immediately load the structure of the binary.
On the right hand side column you will see the binary byte array for the executable, this is literally the PE in it's entirety 
On the left hand side is a handy reference to the different headers that make up the binary 

Headers to Note:
IMAGE_NT_HEADERS > IMAGE_FILE_HEADER > Time Date Stamp   -  This is the time stamp of the initial compile of the code to executable format (N.B this can be illegitimate caution is advised)
IMAGE_SECTION_HEADER .text -  Comparing the virtual size of the binary and the raw size of the binary is a good way to tell if this is a **Packed** binary (This will need converted from HEX)
SECTION .rdata > IMPORT Address Table - This is the Import Address Table, also known as the Windows API Calls table, this will list all windows API calls
	A Great resource to identify malicious API calls is [MalAPI.io](https://MalAPI.io) an online catalogue of Windows APIs that are commonly used in malware

> A packed binary refers to an executable file that has been compressed or encrypted using a technique known as "packing." This is commonly done to reduce the file size or protect the executable from being easily analysed or reverse-engineered

> A Custom made Cheat Sheet of API calls is also available HERE -> [[Windows API Calls]]

#### 📦Packed vs Unpacked Malware:
**Unpacked Malware:** This type of malware is in its original form, making it easier for security software to analyse and detect because all its components are visible and straightforward.
**Packed Malware:** Packed malware has been modified using a tool that compresses or encrypts its contents to hide its true nature. This makes it difficult for antivirus programs to detect it directly because the malicious code is concealed.

**How Malware Gets Packed:**
1. **Choosing a Tool:** Malware creators pick a tool that can compress or encrypt the malware effectively.
2. **Packing the Malware:** They run the malware through this tool, which scrambles the data, making it look harmless or confusing to security systems.
3. **Executing the Malware:** The packed malware includes a small piece of code that, when run, unpacks the malware in the computer's memory, allowing it to carry out its harmful activities without ever showing the original malicious code on the hard drive.

In essence, packed malware is tougher to spot and analyse because it’s disguised, whereas unpacked malware is more straightforward and easier to handle for security systems.

Packed malware hides its true functionality by compressing or encrypting the malicious code, making static analysis difficult due to high entropy, limited strings, and minimal imports. The real payload is only revealed at runtime when the malware unpacks itself in memory. Unpacked malware, on the other hand, exposes its logic directly, allowing analysts to see readable strings, clear API imports, and a normal file structure, making static analysis more effective and faster.

#### Combination Analysis

##### PEstudio
The Amazing tool known as [[PEstudio]] is great for basic static analysis as it combines the majority of tools previously referenced, The tool is able to gather the following information: (Hash values, File type, Compiler timestamp, Indicators, and many more). Within the indicators section PEstudio is able to evaluate the byte array and strings to extract information that aligns with known attacker indicators, such as malicious API calls or URL references.

**PEstudio** also exposes the executable’s imports, showing the specific Windows APIs and functions the binary relies on, which can help infer behaviour and capability.** Within the libraries section of PEstudio this is able to list out the dynamic link libraries utilised in the executable.

##### PEframe
Additionally the tool known as **PEframe** is useful for lightweight static analysis and triage of Windows executables. The tool is able to gather key metadata such as hash values, file type, entropy, strings, and basic header information. PEframe also performs automated checks against common malware indicators, including suspicious strings, packing techniques, and known bad characteristics, allowing an analyst to quickly assess whether a binary warrants deeper investigation before moving on to more advanced static or dynamic analysis.

```bash
peframe <filename> | more
```

##### Detect It Easy (DIE)
Another Great tool to give a high level overview, entropy results, Strings and more is [[Detect It Easy (DIE)]]
**Detect It Easy (DIE)** is commonly used for static analysis to identify file format characteristics and applied protections. The tool is able to determine the executable type, architecture, compiler, linker, and detect the presence of packers, cryptors, or obfuscation techniques. Detect It Easy uses signature-based detection and heuristics to highlight how a binary was built and protected, allowing an analyst to quickly understand whether the file is packed or intentionally obfuscated before proceeding with deeper reverse engineering or dynamic analysis.

##### CAPA
Another Great utility for a general overview of an executable is **[[CAPA]]**
Capa is a tool used in the field of malware analysis and reverse engineering, designed to help security professionals automatically identify the capabilities of executable files. Developed by Mandiant, CAPA operates by inspecting binary files (such as those ending in .exe or .dll) to discover and classify a wide range of features and behaviours that are often seen in malicious software.

To use Capa we can use the following command:
```bash
capa <INSERT FILE NAME>
```

This will present the following output example
![[Pasted image 20250318144758.png]]

---

## 2️⃣ Basic Dynamic Analysis

Basic dynamic analysis is the process of examining executable files or malware by running them in a controlled environment to observe their behaviours and interactions with the system and network.

Dynamic malware analysis can be broken down into two primary components based on the types of data collected during the analysis: host-based indicators and network-based indicators. Here’s how each plays a crucial role in understanding and identifying malware activities:

1. **Host-Based Indicators:** - These are the signs and signals of malicious activity that can be observed on the computer where the malware is executed. Host-based indicators provide insights into how the malware interacts with the system’s files, registry, processes, and other critical components.
 **Examples:** File Modifications, Registry Changes, Process Behaviour, System Logs, Memory Anomalies
 
2. **Network-Based Indicators:** - These indicators capture the interactions between the malware and network resources, revealing how the malware communicates, propagates, or exfiltrates data.
**Examples:** Network Traffic, DNS Requests, HTTP Requests, Port Activity

Use a "Give as you go" attitude, sometimes malware will require dependencies such as specific web connections, additional files or specific environments.
During your analysis if you uncover these dependencies give the malware what it requires to allow you to continue analysing. 

#### Host Based Indicators

##### Proc Mon
When detonating a malware sample or executable it is common for the malware to create sub-processes that carry out specific functions for the malware 
A great tool for detecting these processes is **[[Procmon]]** a.k.a. Process Monitor, this will be able to show the analyst which processes spawned as a result of execution

When using this tool, it is recommended to filter by the processes name, this will assist in identifying exactly what the process spawns upon execution 
This will also ensure no other Windows processes are mixed in with the ones spawned.

Just Like many EDR/XDR solutions Procmon also has the utility to graphically map parent - child process relationships, utilising the Process Tree section of the application
This will allow the analyst to identify any spawned processes from the initial execution of the sample.
This can also assist with identifying the Process ID of the malware in order to filter by this to see other processes spawned. 

Additionally you can filter by the exact process name you are examining, then export the results to a CSV for later analysis

##### ProcDot

ProcDOT is a visual correlation tool used to analyse and understand process behaviour during malware execution. Rather than inspecting individual log entries, it allows an analyst to observe how processes, files, registry keys, and network activity interact over time, making complex behaviour far easier to interpret.

To use ProcDOT effectively, system activity is first captured using Process Monitor during the execution of a suspicious sample. The analyst applies appropriate filters to focus on the target process and its child processes, ensuring unnecessary background noise is reduced. Once execution is complete, the captured Procmon logs are exported in CSV format, preserving all recorded events for further analysis.

These exported CSV logs are then imported into ProcDOT, which parses the data and correlates events into a structured visual graph. Each node and connection represents relationships such as process creation, file writes, registry modifications, or network activity. This visualisation allows the analyst to quickly identify suspicious behaviour patterns, such as persistence mechanisms, dropped files, or injected processes, without manually reviewing thousands of individual Procmon events.

![[Pasted image 20260212140527.png]]

##### System Informer
When analysing a suspicious executable, it is common for malicious activity to be distributed across multiple running components. **System Informer** enables an analyst to inspect live system activity at a granular level, making it easier to spot abnormal processes, spawned children, and unexpected services.

By providing detailed insight into process relationships and runtime attributes, the tool helps determine how a sample behaves after execution and supports accurate identification of the core malicious process.

##### Regshot
Regshot is commonly used during malware analysis to identify changes made to the Windows Registry as a result of executing a suspicious file. The tool works by taking an initial snapshot of the registry before execution and a second snapshot after the sample has run, then comparing the two to highlight any added, modified, or deleted keys and values. 

This allows an analyst to clearly see persistence mechanisms, configuration changes, or system modifications introduced by the malware, helping to confirm impact and guide further investigation or remediation.

#### Network Based Indicators

##### Wireshark
When detonating a malware sample or executable it is common for the malware to reach out to an external domain, this may be for a number of reasons
- Second Stage Payload
- Exfiltration of Data
- etc
A Great tool for detecting these network requests is [[Wireshark]], as it can identify the application that issued the request, and later we can add these requests to an IPS or create YARA rules 

> for network based indicators please try (when possible) to capture traffic on an additional host rather than the one the malware is executed on. 

To do this ensure that both the Flare VM and REMnux host are on the same network and run the following command on the REMnux host:
```bash
wireshark &
```
> this runs Wireshark from the command line and in the background.
> Then continue capturing traffic on the `ens33` default network adapter.

Malware often attempts to resolve domain names in order to communicate with external infrastructure such as command-and-control servers or download locations. In a controlled malware analysis environment, this behaviour can be safely observed by providing a simulated DNS or network responder. Tools such as **FakeDNS** and **INetSim** are commonly used for this purpose, each serving a slightly different role.

##### FakeDNS 
A lightweight tool designed specifically to respond to DNS requests made by malware. It listens for DNS queries within the analysis environment and returns predefined or fake IP addresses for any requested domain. This allows the malware to believe DNS resolution has succeeded, which can trigger additional behaviour such as outbound connections or payload retrieval attempts. FakeDNS is particularly useful when the goal is to capture and log domain lookups with minimal additional network simulation.

```bash
fakedns
```

##### INetSim 
A more comprehensive simulated internet environment. In addition to DNS responses, it emulates multiple common network services such as HTTP, HTTPS, FTP, SMTP, and others. When malware attempts to contact a domain or service, INetSim responds with realistic server behaviour, enabling analysts to observe follow-up actions like data exfiltration attempts, beaconing patterns, or file downloads. This makes INetSim well suited for deeper behavioural analysis where full network interaction is required, while still keeping all activity contained within the lab.

##### Identifying Reverse/Bind Shells

One of the most common types of malware is a RAT or remote access trojan, in this instance a shell is spawned on the victims machine which allows for command injection by the attacker. many techniques are deployed for this to be successful and in some instances these RAT's are established as persistent either in the the victims auto-runs or start-up directory.

To identify these shells we can use tools like [[TCP view]] to assist in identifying connection spawned on suspicious ports by the parent malicious executable.
Another tool that can assist with identifying these connection is Procmon, and can essentially do the same thing as TCPview

If it is the case where we can identify that a sample is preforming a DNS query to initialise a connection to a potential C2 but as we are in a segmented environment this connection will never occur especially because it is done so utilising DNS quires, we can do some trickery and spoof the malware into thinking the domain it is querying is actually the host that it is on (Teehee). this DNS request can be obtained from tools such as Wireshark

How to spoof the etc/hosts file for malicious DNS queries:
Built into Cmder is the Nano text editor, we can use this to edit the hosts file on the Flare VM host using the following command:

```sh
nano C:\Windows\System32\drivers\etc\hosts
```

The cool thing about our Flare VM is that it has the best of both Windows and Linux (intentionally) so the hosts file can be edited to contain domain names and have them associated with IP addresses.

To associate a domain with the host VM we can input the following into the hosts file:

```text
127.0.0.1 <NAME OF MALICIOUS DNS QUERY DOMAIN>
```
^ CTRL + O (to write to the file), Enter (to confirm), CTRL + X (to save and exit the editor)

---

## 3️⃣ Advanced Static Analysis

The first stage of advanced static analysis is being able to understand the binary in a low level
This means converting the many many bits ("1's" and "0's") that make up such an executable / application

To convert these so called bit's into readable format we can use a tools known as [Cutter](https://github.com/luke-mckeever/Cyber_Vault/blob/main/Tooling/Blue%20Team%20Tools/Cutter.md)
This tool will decompile the binary that we would like to investigate, this will then convert the binary into a language known as assembly [[Cutter]]

> Assembly is a low-level programming language that provides a direct way to write instructions for a computer's CPU. It's closely tied to the hardware and is specific to each processor architecture.

A full breakdown of how to use cutter is located in the tools section of this repo - [HERE](https://github.com/luke-mckeever/Cyber_Vault/blob/main/Tooling/Blue%20Team%20Tools/Cutter.md)

#### Understanding Assembly Registers 

###### CPU Instructions

|**Operation**|**Destination**|**Source**|                                  **Description**                                      |
|-------------|---------------|----------|---------------------------------------------------------------------------------------|
|    `mov`    |     `edx`     |   `eax`  |                       Copies the value in `eax` into `edx`                            |
|    `jmp`    |     `edx`     |     -    |               Jumps to the address stored in `edx`. `eax` is not used                 |
|    `sub`    |     `edx`     |   `eax`  |           Subtracts the value in `eax` from `edx`, result stored in `edx`             |
|    `push`   |       -       |   `edx`  |           Pushes the value in `edx` onto the stack. `eax` is not involved             |
|    `pop`    |     `edx`     |     -    |         Pops the top value from the stack into `edx`. `eax` is not involved           |
|    `call`   |     `edx`     |     -    | Calls the procedure at the address in `edx`; pushes return address onto the stack     |
|    `ret`    |       -       |     -    | Returns from procedure by popping the return address from the stack and jumping to it |

###### Memory Registers
**Instruction Pointer (IP):**  
The Instruction Pointer is a register in the CPU that keeps track of the address of the next instruction to run. It's also called the **Program Counter**.
- In early Intel 8086 processors (16-bit), it was called **IP**.
- In 32-bit systems, it became **EIP** (Extended Instruction Pointer).
- In 64-bit systems, it’s known as **RIP** (Register Instruction Pointer).

The above is same for the below General-Purpose Registers:

- **`eax` or `rax` ** – **Accumulator Register**: Used for arithmetic operations and storing return values from functions.
- **`edx` or `rdx`** – **Data Register**: Often used in input/output operations and as an extension of `eax` in multiplication/division.
- **`ebx` or `rbx`** – **Base Register**: Can be used to store base addresses for data access.
- **`ecx` or `rcx`** – **Counter Register**: used in counting operations such as loops, etc.
- **`esp` or `rsp`** – **Stack Pointer**: Points to the top of the current stack frame; used to manage function calls and local variables.
- **`ebp` or `rbp`** – **Base Pointer**: Points to the base of the current stack frame; used to access function parameters and local variables.
- **`eip` or `rip`** – **Instruction Pointer**: Holds the address of the next instruction to execute.
- **`esi` or `rsi`** – **Source Index Register**: used for string operations. It is used with the Data Segment (DS) register as an offset.
- **`edi` or `rdi`** – **Destination Index Register**: used for string operations. It is used with the Extra Segment (ES) register as an offset
-  **`R8-R15`** – not present in 32-bit systems. (**R8D** (lower 32 bits), **R8W** (lower 16 bits), **R8B** (lower 8 bits), etc.)

**Zero Flag:**
Denoted by ZF, the Zero Flag indicates when the result of the last executed instruction was zero. For example, if an instruction is executed that subtracts a RAX from itself, the result will be 0. In this situation, the ZF will be set to 1.

**Sign Flag:**
The Sign Flag or SF indicates if the result of an operation is negative or the most significant bit is set to 1. If these conditions are met, the SF is set to 1; otherwise, it is set to 0.

**Trap Flag:**
The Trap Flag or TF indicates if the processor is in debugging mode. When the TF is set, the CPU will execute one instruction at a time for debugging purposes. This can be used by malware to identify if they are being run in a debugger.

###### Segment Registers:
Segment Registers are 16-bit registers that convert the flat memory space into different segments for easier addressing. There are six segment registers, as explained below:
**Code Segment:** The Code Segment (CS ) register points to the Code section in the memory.
**Data Segment:** The Data Segment (DS) register points to the program's data section in the memory.
**Stack Segment:** The Stack Segment (SS) register points to the program's Stack in the memory.
**Extra Segments (ES, FS, and GS):** These extra segment registers point to different data sections. These and the DS register divide the program's memory into four distinct data sections.


|  **General Registers**  |  **Segment Registers **  |  **Status Registers**  |  **Instruction Pointer**  |
| ----------------------- | ------------------------ | ---------------------- | ------------------------- |
|  RAX, EAX, AX, AH, AL   |            CS            |          EFLAGS        |         EIP, RIP          |
|  RBX, EBX, BX, BH, BL   |            SS            |                        |                           |
|  RCX, ECX, CX, CH, CL   |            DS            |                        |                           |
|  RDX, EDX, DX, DH, DL   |            ES            |                        |                           |
|  RBP, EBP, BP           |            FS            |                        |                           |
|  RSP, ESP, SP           |            GS            |                        |                           |
|  RSI, ESI, SI           |                          |                        |                           |
|  RDI, EDI, DI           |                          |                        |                           |
|  R8-R15                 |                          |                        |                           |


##### Format of an Assembly API call
Assembly API calls are made using  the specific syntax accredited to them per Microsoft official documentation or their structured syntax 
This will look something like the following

```asm
0x004010e3    push    0                                      //pushing the integer value of 0 to the stack
0x004010e4    push    0                                      //pushing the integer value of 0 to the stack
0x004010e9    push    0                                      //pushing the integer value of 0 to the stack
0x004010ea    push    0                                      //pushing the integer value of 0 to the stack
0x004010eb    push    str.<some string> ; 0x00403387         //pushing the sting of <some string> to the stack
0x004010ec    call    dword [<name of api>] ; 0x00403388     //preforming the api call of <name of api> from the stack 
```

> The above assembly language can be used to populate the memory stack with the pre-selected variables and preform the API call  

##### Classic Function Call (Initialisation of main)

```asm
int main (int argc, char **argv, char **envp)     //initialise with preset variables (comminly not utilised)
0x00401530      push     ebp                      //push ebp: preserves the calling function base address
0x00401531      mov      ebp, esp                 //mov ebp, esp: move the stack pointer value into the base pointer
0x00401533      and      esp, 0xffffffff0         //and esp, 0xffffffff0: verify stack
0x00401536      sub      esp, 0x10                //sub esp, 0x10: subtrack 16 from the stack, creating room for 16 pointers
0x00401539      call     dbg.__main               //call dbg.__main: main call of function
```

--- 

## 4️⃣ Advanced Dynamic Analysis

Advanced Dynamic Analysis involves executing (or detonating) a suspicious file in a controlled environment, similar to basic dynamic analysis, to observe its behavior in real-time. However, this approach goes further by incorporating debugging techniques to gain deeper insights into the malware’s inner workings.

Using tools such as x64dbg, OllyDbg, or WinDbg, analysts can interact with the malware at the instruction level, allowing them to:

- Set breakpoints and step through code
- Monitor memory modifications
- Observe function calls and API usage
- Bypass anti-analysis techniques (e.g. unpacking routines, environment checks)  

This method is crucial for uncovering obfuscated logic, hidden payloads, or conditional execution paths that wouldn’t be visible through automated dynamic analysis alone. It enables analysts to reverse engineer the malware’s functionality, persistence mechanisms, C2 infrastructure, and more.

### 🐞Debugging 

> The main aspect of this process allows the analyst to step through potential malicious code and executables as to manually detonate assemble instructions one after another.

> The purpose of this is to identify where instructions are being executed, how they are being executed and most importantly when they are being executed as this will allow for the demonstration of function calls.

> A debugger will also allow and assist in memory analysis and during the step-through of the assembly the contents of the memory stark are present and visible for inspection. A debugger will also support the export of memory dump files at any stage of the assembly’s detonation. 

> Lastly the entire purpose of a debugger (compared to a decompiler) is to be able to set breakpoints.  Breakpoints allow for the manual stoppage of the assembly instruction.

[[x32dbg & x64dbg]] are open-source, user-friendly debuggers designed for analyzing 32-bit and 64-bit executables, respectively. They provide a powerful interface for reverse engineers and malware analysts to interact with binary files at the instruction level.

##### Cheat Sheet - Quick reference guide for keyboard shortcuts §

|   **Shortcut**    |          **Details**           |
| ----------------  |  ----------------------------  |
|        F9         |  Run/Continue execution        |
|        F8         |  Step Over                     |
|        F7         |  Step Into                     |
|        F4         |  Run Until Selection           |
|        F2         |  Toggle Breakpoint             |
|     Shift+F7      |  Step Into (Skip System Code)  |    
|     Ctrl+F7       |  Step Out (Run Until Return )  | 
|     Ctrl+F2       |  Restart Debugging             | 

#### ⛓️‍💥Breakpoints 

A **breakpoint** is a marker you set in a debugger (like **x64dbg, OllyDbg, WinDbg, or Cutter**) that tells the program to **pause execution** when it reaches a certain instruction.  

Think of it like putting a “stop sign” in the malware’s code so you can carefully examine what it’s doing **before it continues running**.

##### 🛠 Types of Breakpoints
1. **Software Breakpoints (`INT 3`)**
   - Inserted into the code (e.g., at an API call like `WriteProcessMemory`).
   - Most common for malware debugging.

2. **Hardware Breakpoints**
   - Set on memory reads/writes or execution of an instruction.
   - Useful when you **can’t modify the code** (e.g., malware checksums itself).

3. **Conditional Breakpoints**
   - Only trigger if certain conditions are true (e.g., when a register equals a specific value).
   - Great for skipping unnecessary code loops.

##### 🎯 Why Breakpoints Are Critical in Malware Analysis
- **Catch API Calls**: Stop at functions like  
  - `VirtualAllocEx` → to see memory allocation for shellcode  
  - `WriteProcessMemory` → to inspect injected payload  
  - `CreateRemoteThread` → to analyze execution in another process  
- **Prevent Damage**: Pause before destructive functions like `DeleteFile`, `CryptEncrypt`, or registry modifications.
- **Unpack Malware**: Break just before or after the unpacking routine to extract the decrypted payload.
- **Study Control Flow**: Follow jumps, loops, or obfuscated logic in a controlled way.

##### ⚙️ How to Use Breakpoints Efficiently
1. **Target High-Value API Calls**
   - Set breakpoints on imports often abused by malware:
     - `OpenProcess`, `VirtualAllocEx`, `WriteProcessMemory`, `CreateRemoteThread`
     - `GetProcAddress`, `LoadLibrary` (API resolution)
     - `WinExec`, `ShellExecuteA`, `CreateFileA/W`, `RegSetValueExA`

2. **Use Breakpoints as Safety Nets**
   - Place them **before potentially harmful actions** so you can intercept and examine before the system is affected.

3. **Leverage Hardware Breakpoints**
   - For packed or self-modifying malware, use hardware breakpoints on memory regions to catch when unpacked code gets executed.

4. **Step Around Loops**
   - Don’t waste time stepping through thousands of NOPs or junk instructions — use conditional breakpoints or **step over** to save time.

5. **Combine With Logging**
   - In x64dbg, you can attach a log message to a breakpoint (e.g., “CreateRemoteThread called!”) without always halting execution.

#### 🚨 Example in Malware Debugging
Imagine you’re analyzing malware that injects shellcode into `explorer.exe`:

- **Breakpoint 1:** Set on `OpenProcess` → identify the target PID.  
- **Breakpoint 2:** Set on `VirtualAllocEx` → grab the memory address allocated in the target.  
- **Breakpoint 3:** Set on `WriteProcessMemory` → dump the shellcode being injected.  
- **Breakpoint 4:** Set on `CreateRemoteThread` → control when the malicious code starts executing.  

By using these breakpoints, you intercept the full injection chain without letting the malware fully execute and damage your system.

> For full list of API Calls which are beneficial for inserting breakpoints and can suggest malicious intentions see [[Windows API Calls]]

---

## 💡Specialty Malware Analysis

### MalDoc Analysis

**Summary:** Identify and dissect malicious Microsoft Office documents that may contain macros, embedded scripts, or exploits.  
**How To (Detailed):**

1. **Initial Inspection:**
    - Check the file extension (e.g., `.doc`, `.docm`, `.xls`, `.ppt`).
    - Run `file` or `trid` to confirm actual file type.
    - Use `oleid` to detect potential risks like macros, encryption, or suspicious streams.
2. **Macro Extraction: (.docm, .xlsm, .pptm)*
    - Run `oledump.py <file>` to extract and view VBA macros.
      This will output a list of the contained streams within the file. (if a stream is flagged with a "M" this incites a macro is contained)
    - To dump the contents of the macro, use `oledump.py -s <stream#> --vbadecompresscorrupt <file>` to dump macro code.
    - Deobfuscate strings or code using regex searches, CyberChef, or Python scripts.
3. **Behavioral Testing:**
    - Execute the sample in a sandbox (e.g., `REMnux`, `Flare VM`, or a Windows VM with monitoring tools).
    - Capture network traffic with `Wireshark` and monitor system changes with `Procmon` or `Sysmon`.
4. **Analysing Malicious Templates**
	- Word documents are able to utilise templates, TA's are able to abuse this by hosting said templates on malicious domains that additionally download malware.
	- These templates are stored within the `word/_rels` directory.
	- Open the file `settings.xml.rels` to view the current template for the document.

### PDF Analysis

**Summary:** Examine PDFs for hidden JavaScript, embedded files, or exploits targeting PDF readers.  
**How To (Detailed):**

1. **File Verification:**
    - Confirm file type with `file <sample.pdf>`.
    - Use `pdfid.py <sample.pdf>` to detect suspicious keywords (e.g., `/JavaScript`, `/OpenAction`, `/Launch`).
2. **Object Extraction:**
    - Parse with `pdf-parser.py <sample.pdf>`.
    - Extract and review suspicious objects (e.g., object streams containing JavaScript).
    - Decode encoded streams using built-in flags or export for manual analysis.
3. **Embedded Content Analysis:**
    - Look for embedded files, images, or executables.
    - Dump suspicious objects and analyze them separately.
4. **Dynamic Testing:**
    - Open the PDF in a controlled VM with logging tools.
    - Capture any spawned processes, network connections, or dropped files.

### Malicious Images

**Summary:** Investigate images that may hide payloads via steganography or malformed file structures.  
**How To (Detailed):**

1. **Header & Metadata Inspection:**
    - Open the image in a hex editor to check for abnormal headers or appended data.
    - Use `exiftool <image>` to review metadata for anomalies or hidden fields.
2. **Structural Validation:**
    - Confirm file integrity with tools like `binwalk` to detect embedded files or archives.
    - Compare reported file size vs. expected content size.
3. **Steganography Detection:**
    - Use `steghide extract -sf <image>` (if password known, try dictionary attack).
    - Run `zsteg <image.png>` for PNG-specific stego detection.
    - Cross-check with online steganalysis tools.
4. **Execution Safety Check:**
    - Test rendering the image in an isolated VM.
    - Watch for crashes or suspicious memory usage (could indicate malformed exploit payloads).
5. **IOC Extraction:**
    - Record hashes, extracted hidden content, and any embedded executables.
    - Add findings to a central analysis log.

--- 

## 🐢 Shell Code Analysis 

> Shellcode is a small piece of malicious code, often written in assembly, that attackers inject into a vulnerable process to gain control of a system, typically used to spawn a shell or execute arbitrary commands.

**[[SCdbg]]** is a Windows-based shellcode analysis tool that emulates execution to safely reveal malicious behavior. By loading raw shellcode (binary or hex) with commands like `scdbg.exe -f shellcode.bin`, analysts can trace API calls, view disassembly, inspect register states, and simulate network activity. This helps uncover actions such as file drops, process injection, or command-and-control connections without risking live execution. Pairing scdbg with tools like IDA Pro or x64dbg enhances deeper analysis, though all work should always be performed in a controlled lab environment.

```bash
scdbg.exe /f shellcode.bin -s -1        //this will pass out all the shell code api instructions
```


### 🔪 Carving Shellcode from Memory

Shell code will rarely be easily analysed in raw format and will be more commonly injected into memory at runtime, therefore to be able to analyse said shellcode, we require the use of a debugger and then be able to preform a memory dump at the memory location of the injection.

- **1. Pre-Analysis**
	- Get an understanding of what api calls are made with the executable. 
	- This can be achieved with tools such as: [[CAPA]] or [[PEstudio]] (imports).
	- This will assist in identifying the `WriteProcessMemory` or `CreateRemoteThread` API calls as both of these are indicative of process injection attacks.
- **2. Identification of Process Injection**
	- Using [[Cutter]] open the file, more commonly no debug symbols / memory addresses will be present such as `int_MAIN()`
	- To identify the starting point of the executable we will need to work backwards form the end and identify when the C runtime variable was initiated
	- Go to the entry point of the process identified with `entry0()`
	- Identify the last `call` this is the last time the `eax` register was changed click into this call function
	- Go to the bottom of the call graph and identify the last `move` call for the `eax` register, taking note of the value passed in e.g. `0x00408010` 
	- Moving up through the graph look for the most previous reference to the value moved into the `eax` register
	- Typically the previous function call to this will be **Main Function** of the program
	- It may be good practice to rename this function to later assist or for future identification 
	- Look through the function to identify all other function calls (typically the last)
	- Here we will be able to identify the memory injection API calls such as `WriteProcessMemory` or `CreateRemoteThread` 
	- Take note of the memory locations of each call. (for shell code use the function `WriteProcessMemory`)
- **3. Extracting the shellcode**
	- Now we will need move over to a debugger such as [[x32dbg & x64dbg]] to create a dump of the memory
	- `CTRL + G` will allow you to instantly jump to a specific memory address.
	- Create a breakpoint (`F2`) on the API call for `WriteProcessMemory`. 
	- Execute the program until it reaches this breakpoint 
	- This type of API call accepts 4 inputs and delivers 1 output. (see a full breakdown of this API [here](https://learn.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-writeprocessmemory))
	- The third input known as `lpBuffer` is the input that contains the data that will be written to memory
	- So we move back three arguments from the initial call of `WriteProcessMemory`. this will then be the register that contains the shellcode 
	- Right click on this argument, select follow in dump, this will allow us to see exactly what is stored in this register at this time of the programs execution
	- The bottom left corner panel will then show the hexdump of the register.
	- Highlight the characters that we want to pull out of memory, right click, go to binary and then select save to file 
	- Save this file as a .bin file 
- **4. Analysing the shellcode**
	- Open this file with [[SCdbg]] to analyse the capabilities of the shell code and extract the given IOC's 

--- 

## 📜 Scripted Malware Analysis

> Scripted malware refers to malicious code written in scripting languages like JavaScript, PowerShell, or VBA, often heavily obfuscated to hide its true intent. Instead of compiled binaries, it relies on scripts to execute tasks such as downloading payloads, stealing data, or evading detection, making it lightweight, flexible, and harder for traditional defences to analyze.

All of the following sections will contain program code relative to their heading that is obfuscated or deliberately transformed to conceal its true purpose, structure, or logic by using techniques such as variable renaming, string encoding, control-flow alteration, or junk code insertion. 
This code will need to be rewritten (de-obfuscated) in order to properly understand it and analyze it.

### PowerShell Obfuscation 

**PowerShell** is a command-line shell and scripting language built on top of the **.NET runtime (Common Language Runtime, CLR)**. 
Instead of working with plain text like traditional shells, it operates on **.NET objects** in memory. 
Every command (called a _cmdlet_) executes as compiled .NET code, passing rich objects through the pipeline rather than strings. 
This gives it deep access to the Windows API, the registry, WMI, COM, and system internals—essentially acting as a managed interface between the OS kernel, user-mode processes, and the administrator or script running it.

#### Terms
- **Invoking expression**: Executes a string as PowerShell code, often used to run hidden or downloaded payloads.
- **Objects**: PowerShell works with .NET objects, giving direct access to Windows internals.
- **Case insensitivity**: Cmdlets and variables run regardless of casing, useful for obfuscation.
- **Base64 encryption**: Encodes commands/payloads to hide them, commonly seen with `-EncodedCommand`.
- **Pipes**: Chain cmdlets together; attackers use them to hide logic in complex pipelines.
- **Decompression**: Expands compressed payloads (e.g., Gzip/Deflate) at runtime to evade detection.
- **Classes**:
    - **MemoryStream.IO**: Loads payloads into memory without touching disk.
    - **System.IO**: Reads/writes files, often abused to drop or modify data stealthily.

#### De-Obfuscation
**Writing encrypted text to a variable:**
> it's pretty common in malicious PowerShell scripts to use multiple encryption methods to obfuscate what's actually happening so writing this text to a variable will allow us to output the contents of this variable without having to completely understand how it has been encrypted.
- Remove the Invoke expression parameter. `IEX()`
- Copy the remainder of the contents (object), 
- Open a new PowerShell window, and create a new variable name with the `$` character and make it equal to the contents just copied e.g. `$VARIABLE = Value`
- To print out the contents of the variable use the write host command: `write-host $VARIABLE`

### VBS Obfuscation 

VBA (**Visual Basic for Applications**) is a built-in scripting language used inside Microsoft Office apps like Word and Excel to automate tasks. At a low level, it can interact with the Windows API, files, and the registry, giving it much more power than just “macros.” From a malicious perspective, attackers often abuse VBA macros to auto-execute when a document is opened, run obfuscated code, drop payloads, or launch PowerShell — making it a classic vector for malware delivery.

#### Terms 
- **Dim**: Used to declare variables; often abused in obfuscated code where variables with meaningless names hide malicious logic.
- **WScript.Shell**: Provides access to Windows shell functions; attackers use it to run commands, launch executables, or call PowerShell.
- **oExec**: An object returned by `WScript.Shell.Exec`; malware uses it to run external processes and interact with their input/output.
- **Update function**: Commonly masquerades as a benign routine but often hides code that downloads or executes updated malware payloads.
- **DCOM/COM**: Interfaces that allow scripts to interact with system components; exploited for persistence, lateral movement, or launching system utilities remotely.
- **ShellExecute**: Executes programs or opens files/URLs; heavily abused to launch payloads or trigger system tools like `cmd.exe` or `powershell.exe`.
- **msbuild.exe**: A legitimate Microsoft build tool that can compile and execute inline code; abused by attackers as a “living off the land” binary (LOLBin) to run malicious scripts without dropping a traditional executable.

### HTML/HTA Obfuscation

(Coming Soon)


### JavaScript obfuscation 

(Coming Soon)


---

## C# & the .NET Framework (.dll Analysis)
 
> **C#** is a modern, object-oriented programming language developed by Microsoft, designed for building everything from desktop apps to web services. It’s tightly integrated with the **.NET Framework**, which is a large runtime environment and library collection that provides pre-built functionality (like file I/O, networking, cryptography, and UI components) and manages code execution through the **Common Language Runtime (CLR)**. 
> From a security perspective, this combo is powerful because attackers can write compact C# programs that leverage .NET’s deep access to Windows internals, sometimes embedding malware logic inside otherwise normal-looking applications.

When code is written in C#, the host does not understand how to execute such code but many IDE's are able to understand it, it works by conversion:
1. C# Code/Language -> source code 
2. C# Compiler -> assembly (coverts to a .exe file)
3. IL / Intermediate Language -> takes care of the creation 
4. CLR / Common Language Runtime -> ready's for execution
5. OS / Operating System - > executed locally on host

To analyse a .NET written executable we can utilise a tool called [[dnSpy]], **dnSpy** is a powerful .NET reverse engineering tool used to decompile, debug, and analyze applications written in **C# or VB.NET**. It allows security researchers and malware analysts to view and edit the **source code** of .NET executables (`.exe`, `.dll`) directly, even if the original source is unavailable.

### Analysing DLL's 

>A **DLL (Dynamic Link Library)** is a file that contains reusable **code, data, or resources** that programs can load and execute **on demand**. DLLs typically use the `.dll` file extension and are designed to be shared across multiple applications, helping reduce duplication and save memory.

DLL files are not natively ran by themselves and contain code that may be required by another program, Given these files cannot be analysed like a normal .exe file 
we must use alternative methods for dynamic analysis.

1. **Identify the MAIN class of the dll**
- Using dnSPY identify the variable name that follow the class naming convention of `private static void`. this is the class name of the dll
1. **Execute the dll**
- Using the native rundll32 broker use the following command:
```bash
rundll32 linklibraryfilename.dll,mainclass
```

---

## Analysing GO Malware

> **Go** (also known as **Golang**) is an open-source programming language developed by Google, designed for simplicity, speed, and efficient concurrency—ideal for building scalable, high-performance systems.

#### Static GO Malware indicators
Identification of **GO** malware can be easily verified using a string dump of the malware:

```bash
floss <malware.exe>
```

The Following strings are immediate indicators that the sample is written in GOL:
- `.symtab` - essential header section of go executables, as go is x86 architecture based [[PE-bear]] will be required to view contents of headers 
- ` GO build ID: "423843247324983749890900098345665745678763"` - build id for go compiled executable
- `golang.org/x/sys/` - library import source

#### Dynamic GO Malware Indicators
Using [[Wireshark]] to listen for `http` traffic
- `Go-http-client/1.1` - default user agent used for go executable connections


## Mobile Malware Analysis

> When analysing IOS and Android malware the Mobile Security Framework a.k.a. [[MobSF]] is essential.

To use the Mobile Security Framework to analyse mobile malware 
1. Browse to the web portal for the docker container 
2. Upload the malware sample (please ensure this sample is armed with the correct file extension)
3. This will then redirect you to a full breakdown of the file 

Specifically for APK or Android packages, these files are java binaries and not machine level code
Navigate to the `Decompiled Code` section and select `View Source`, this will show the original source code for the sample

---

## Automating Malware Analysis

Automating malware analysis is essential for scaling incident response and threat intelligence efforts, enabling analysts to triage large volumes of suspicious files and URLs quickly and consistently. By combining static and dynamic analysis tools, scripting, and sandbox environments, automation reduces manual overhead, highlights key indicators of compromise (IOCs), and accelerates time-to-insight. Each workflow below contributes a unique capability — from interactive sandboxes to fully scripted pipelines — offering flexibility based on use case, environment, and technical maturity.


#### **1. [[Blue Jupyter]]**
[**Blue Jupyter**](https://github.com/HuskyHacks/blue-jupyter) is a Jupyter Notebook–based malware triage pipeline designed for static analysis automation. It allows analysts to process malware samples inside an isolated Docker container, automatically extracting metadata, calculating hashes, querying VirusTotal, defanging malicious content, and presenting the results in a structured notebook format. It’s ideal for blue teamers who want a repeatable, auditable, and modifiable environment for early-stage triage and analysis, especially in conjunction with other tools from the PMAT framework.

#### **2. AnyRun**
**AnyRun** is a cloud-based interactive malware sandbox that supports live behavioral analysis in a virtualized Windows environment. It allows users to interact with the malware during execution — such as clicking dialog boxes or entering passwords — which is especially useful for unpacking samples that require user interaction. AnyRun offers API access for automation, enabling users to submit samples and retrieve detailed behavior reports, network traffic, process trees, and extracted IOCs without manual intervention.

#### **3. Hybrid Analysis**
**Hybrid Analysis**, by CrowdStrike, provides both static and dynamic analysis using a sandbox engine that integrates AV engines, behavioral scoring, and threat intelligence feeds. Through its API, users can automate the submission of files or URLs, and extract comprehensive reports including YARA matches, behavioral signatures, and network indicators. Its layered scoring system and integration with Falcon Insight make it well-suited for enriching threat intel pipelines or validating suspected malware in an automated SOC workflow.

#### **4. Scripting-Based Analysis**
**Scripting-based analysis** refers to fully custom automation workflows built using languages like Python, PowerShell, or Bash. These scripts can chain together multiple tools — such as hash calculators, static analyzers (e.g. `pefile`, `yara`, `strings`), and sandbox submission APIs — to automate entire malware analysis pipelines. Scripting allows fine-grained control over logic, custom IOC extraction, post-processing, alerting, and integration with platforms like SIEMs or case management tools, making it the most flexible but also most technically demanding automation method.

#### **5. [Tria.ge by Recorded Future](https://tria.ge)**
Recorded Future’s **Triage** (formerly Hatching’s sandbox) is designed for high‑volume automated malware analysis across Windows, Linux, macOS, and Android. It supports live VM interaction, behavioral and static tasks, and offers a REST API for submission, status tracking, and report retrieval. In automation, you’d submit samples programmatically (optionally in interactive or automatic mode), poll status/events, retrieve summary or full reports, and ingest IOCs or configuration extractions into downstream systems.  It is optimized for scale and integrates with orchestration tools (e.g. SOAR) and connectors. 

---

## Creating Detection Logic for Malware Families 

> [[YARA]] is an open-source tool used to detect and classify malware by matching custom rules against files or memory. These rules define patterns—like strings or byte sequences—commonly found in specific malware. Security analysts use YARA for threat hunting, malware classification, and integrating automated detection into tools like VirusTotal, Hybrid Analysis, and sandbox environments. It plays a key role in automating and enriching malware analysis workflows.

#### YARA rule template:
```YARA
rule YARA_Example {
	
	meta:
		last_updated = "10-10-2025"
		author = "Anonymous"
		description = " A Sample template for YARA rules"
		
	strings:
		//Fill out this section when identifying strings
		
	condition:
		//Fill out this section to select the conditions that must be met to meet this rule
		
}
```

#### YARA rule example:
```YARA
rule YARA_Example {
	
	meta:
		last_updated = "10-10-2025"
		author = "Anonymous"
		description = " A Sample template for YARA rules"
		
	strings:
		$string1 = "<insert identified string>" ascii    //identifies if a string is contained
		$string2 = "<insert identified string2>" ascii   //identifies if another string is containted
		$PE_magic_byte = "MZ" ascii                      //identifies if the MZ magic byte is contained 
		$suspicious_hex_code = { FF E4 ?? 00 FF}         //identifies if a string of hex code is contained where `??` is a wildcard
		
	condition:
		$PE_magic_byte at 0                              //detect if variable is at 0 in hex
		($string1 and $string2) or                       //detect only if both varriables are present
		$suspicious_hex_code                             //detect if both variables or last variable
		
}
```

To invoke a YARA rule and run it against file or directory we can use the following command:
```bash
yara64 <yararulename>.yara -r <filename or folder/directory> -s -w -p 64 
```
where: 
- (-s) will provide the detection location of the string in memory location via strings 
- (-w) suppresses warnings from YARA
- (-p) is the number of threads used for processing
- (-r) will recursively run rule against all subfolders contained

---

## Malware Analysis Report Writing:

Template Link **[HERE](https://github.com/HuskyHacks/PMAT-labs/blob/main/labs/5-3.ReportWriting/ReportTemplate.docx)**

Template for a malware analysis report:
```text

for all screenshots provide a description

[-- Cover Page --]
- Logo front and centre
- Name of the report 
- Name of malware Analysed (can use psudo name here also)
- Date + Author + Version
  
[-- Table Of Contents --]
- 1. Executive Summary
- 2. High Level Technical Summary
- 3. Malware Compsition
- 4. Basic Static Analysis
- 5. Basic Dynamic Analysis
- 6. Advanced Static Analysis
- 7. Advanced Dynamic Analysis
- 8. Indicators of Compramise
	- Network Based IOC's 
	- Host Based IOC's 
- 9. Rules and Signatures
- 10. Apendencies 

[-- Executive Summary --]
SHA256 HASH right at the top
A Very high level overwiew of how this malware came about when and where
what it consists of: language, OS, and essentially what happens when it's executed.
how are we preventing this malware

[-- High Level Technical Summary --]
Break down the malware, what parts do what. 
this file does this that file does that 
use diagrams to explain the technical detail

[-- Malware Composition --]
break down the malware into it's bare bones compositions
file hashes for the malware, what these parts do
screenshots of the plaintext (if applicable)

[-- Basic Static Analysis --]

[-- Basic Dynamic Analysis --]

[-- Advanced Static Analysis --]

[-- Advanced Dynamic Analysis --]

[-- Indicators of Compramise --]
provide a list of IOC's and where they were found
use screenshots to asist in verifying their legitimacy

[-- Rules and Signatures --]
what yara rules were written (do not provide content just list)
use this to collect strings url's and user agents that can be used to write the YARA rules 

[-- Apendencies  --]
only include YARA code if it is concise 
provide a list of contacted urls or ip's and over which ports

```

---

## Example Malware Analysis

### 



---

## Resources
List of other beneficial Knowledge Articles: 
- [Malware Types](https://github.com/luke-mckeever/Cyber_Vault/blob/main/Knowledge%20Articles/All%20Knowledge%20Articles/Malware%20Types.md)
- [Malware Analysis Framework](https://github.com/luke-mckeever/Cyber_Vault/blob/main/Knowledge%20Articles/All%20Knowledge%20Articles/Malware%20Analysis%20Framework.md)
- [MITRE ATT&CK Framework](https://github.com/luke-mckeever/Cyber_Vault/blob/main/Knowledge%20Articles/All%20Knowledge%20Articles/MITRE%20ATT%26CK%20Framework.md)
- [Flare VM - Malware Lab Provisioning](https://github.com/luke-mckeever/Cyber_Vault/blob/main/Knowledge%20Articles/All%20Knowledge%20Articles/Flare%20VM%20-%20Malware%20Lab%20Provisioning.md)
- [A Programs Perspective of Memory](https://github.com/luke-mckeever/Cyber_Vault/blob/main/Knowledge%20Articles/All%20Knowledge%20Articles/A%20Program%E2%80%99s%20Perspective%20of%20Memory.md)
- [Email Attachment Analysis](https://github.com/luke-mckeever/Cyber_Vault/blob/main/Knowledge%20Articles/All%20Knowledge%20Articles/Email%20Attachment%20Analysis.md)

List of other beneficial Cheat Sheets:
- [Magic Bytes](https://github.com/luke-mckeever/Cyber_Vault/blob/main/Cheat%20Sheets/All%20Cheetsheets/Magic%20Bytes.md)
- [URL Encoding](https://github.com/luke-mckeever/Cyber_Vault/blob/main/Cheat%20Sheets/All%20Cheetsheets/URL%20Encoding.md)
- [Ports & Protocols](https://github.com/luke-mckeever/Cyber_Vault/blob/main/Cheat%20Sheets/All%20Cheetsheets/Ports%20%26%20Protocols.md)
-[Useful (Cyber) Domains](https://github.com/luke-mckeever/Cyber_Vault/blob/main/Cheat%20Sheets/All%20Cheetsheets/Useful%20(Cyber)%20Domains.md)
- [Windows API Calls](https://github.com/luke-mckeever/Cyber_Vault/blob/main/Cheat%20Sheets/All%20Cheetsheets/Windows%20API%20Calls.md)

#### Tools
- [Virus Total](https://github.com/luke-mckeever/Cyber_Vault/blob/main/Tooling/Blue%20Team%20Tools/Virus%20Total.md)
- [Floss](https://github.com/luke-mckeever/Cyber_Vault/blob/main/Tooling/Blue%20Team%20Tools/Floss.md)
- [PEview](https://github.com/luke-mckeever/Cyber_Vault/blob/main/Tooling/Blue%20Team%20Tools/PEview.md)
- [PEstudio](https://github.com/luke-mckeever/Cyber_Vault/blob/main/Tooling/Blue%20Team%20Tools/PEstudio.md)
- [Detect It Easy (DIE)](https://github.com/luke-mckeever/Cyber_Vault/blob/main/Tooling/Blue%20Team%20Tools/Detect%20It%20Easy%20(DIE).md)
- [CAPA](https://github.com/luke-mckeever/Cyber_Vault/blob/main/Tooling/Blue%20Team%20Tools/CAPA.md)
- [Wireshark](https://github.com/luke-mckeever/Cyber_Vault/blob/main/Tooling/Blue%20Team%20Tools/Wireshark.md)
- [Procmon](https://github.com/luke-mckeever/Cyber_Vault/blob/main/Tooling/Blue%20Team%20Tools/Procmon.md)
- [TCP view](https://github.com/luke-mckeever/Cyber_Vault/blob/main/Tooling/Blue%20Team%20Tools/TCP%20view.md)
- [Cutter](https://github.com/luke-mckeever/Cyber_Vault/blob/main/Tooling/Blue%20Team%20Tools/Cutter.md)
- [x32dbg & x64dbg](https://github.com/luke-mckeever/Cyber_Vault/blob/main/Tooling/Blue%20Team%20Tools/x32dbg%20%26%20x64dbg.md)

#### Other great resources
- PMAT - Labs Malware Samples - Available [Here](https://github.com/HuskyHacks/PMAT-labs/tree/main/labs) 
- Malware Zoo - Live Malware samples - Available [HERE](https://github.com/ytisf/theZoo)  
- Malware Bazaar - Largest Malware sample database - Available [HERE](https://bazaar.abuse.ch/browse/)
- VX Underground - Complete sample and research malware site - Available [HERE](https://vx-underground.org/)
	- Their Git Hub is also available [HERE](https://github.com/vxunderground)